pnuckowski / aioresponses

Aioresponses is a helper for mock/fake web requests in python aiohttp package.
MIT License
513 stars 86 forks source link

running the first example, as a decorator - fixture 'mocked' not found #218

Open rnusser opened 2 years ago

rnusser commented 2 years ago

If I run the first example, as it is, I get the error:

fixture 'mocked' not found

However if placed in a class it works:

import aiohttp
import asyncio
from aioresponses import aioresponses
from unittest import TestCase

class ClientTest(TestCase):
    @aioresponses()
    def test_request(self, mocked):
        loop = asyncio.get_event_loop()
        mocked.get('http://example.com', status=200, body='test')
        session = aiohttp.ClientSession()
        resp = loop.run_until_complete(session.get('http://example.com'))

        assert resp.status == 200

Python 3.10.4 aiohttp 3.8.1 aioresponses 0.7.3 pytest 7.1.2

Pacheco95 commented 2 years ago

Same problem here:

Python 3.9.13
aiohttp 3.8.1
aioresponses 0.7.3
pytest 7.1.2
marcinsulikowski commented 2 years ago

Pytest does a lot of magic things behind the scenes with test functions that take arguments. With pytest it'd be better to use Pytets fixtures instead of the @aioresponses decorator:

import asyncio

import aiohttp
import pytest
from aioresponses import aioresponses

@pytest.fixture
def mocked():
    with aioresponses() as m:
        yield m

def test_request(mocked):
    loop = asyncio.get_event_loop()
    mocked.get('http://example.com', status=200, body='test')
    session = aiohttp.ClientSession()
    resp = loop.run_until_complete(session.get('http://example.com'))
    assert resp.status == 200

Looks like the README should be updated.

mxr commented 2 weeks ago

On my end I have to specify ClientSession(loop=loop) for the examples to work, otherwise this line crashes with RuntimeError: no running event loop. Is that expected? I can post more about my environment if not