dimanche 3 février 2019

How to patch an object used in fixture from within test function

I'm writing a test suite for my API and the returned result of some endpoints depend on the internal state of the application. My goal is to mock those specific 'check functions' to test all cases.

# conftest.py

@pytest.fixture(scope='module')
def flask_app():
    app = Flask(__name__)
    app.config.from_pyfile('flaskconfig.py')
    api = ApiUnderTest()
    bp = api.get_blueprint()
    app.register_blueprint(bp)
    return app


@pytest.fixture(scope='module')
def test_client(flask_app):
    client = flask_app.test_client()
    ctx = flask_app.app_context()
    ctx.push()
    yield client
    ctx.pop()

# test_case.py

@pytest.mark.parametrize('check_return', [True, False])
def test_api_call(test_client, check_return):
    # Here I want to patch the function ApiUnderTest.state.check()
    # to return the 'check_return' value. This function will be
    # evaluated when calling the endpoint

    response = test_client.get('/endpoint')

    if check_return is True:
        assert response.status_code == 200
    else:
        assert response.status_code == 409

This is some simplified code, but I think it shows what I want to achieve. The question is now: How can this be done?

I tried to patch the specific function inside test_api_call using the mock module, but this had no effect on the object instance used in conftest.py.

Aucun commentaire:

Enregistrer un commentaire