Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock streaming API in python for unit test

I have an async function that calls a streaming api. What is the best way to write unit test for this function? The api response has to be mocked.

I tried with aiounittest and used mock from unittest. But this calls the actual api instead of getting the mocked response. Also tried with pytest.mark.asyncio annotation, but this kept giving me the error - coroutine was never awaited. I have verified that pytest-asyncio has been installed.

I am using VS Code and Python 3.6.6

Here is the relevant code snippet:

async def method1():
    response = requests.get(url=url, params=params, stream=True)
    for data in response.iter_lines():
        # processing logic here
        yield data

Pasting some of the tests I tried.

def mocked_get(*args, **kwargs):
#implementation of mock

class TestClass (unittest.TestCase):
    @patch("requests.get", side_effect=mocked_get)
    async def test_method (self, mock_requests):
        resp = []
        async for data in method1:
            resp.append (data)
    
        #Also tried await method1
    
        assert resp
    

Also tried with class TestClass (aiounittest.AsyncTestCase):

like image 408
D George Avatar asked Oct 15 '22 23:10

D George


1 Answers

Use asynctest instead of aiounittest.

  1. Replace unittest.TestCase with asynctest.TestCase.
  2. Replace from unittest.mock import patch with from asynctest.mock import patch.
  3. async for data in method1: should be async for data in method1():.
import asynctest
from asynctest.mock import patch


class TestClass(asynctest.TestCase):
    @patch("requests.get", side_effect=mocked_get)
    async def test_method(self, mock_requests):
        resp = []
        async for data in method1():
            resp.append(data)

        assert resp
like image 70
aaron Avatar answered Oct 29 '22 01:10

aaron