lundi 26 octobre 2020

How can I make the Flask testing client have the same interface as requests?

How can I write Flask tests which can switch between blackbox testing (a remote website) and whitebox testing (a locally running Flask app)?

I'm interested in that, because I can set up such a blackbox-testing environment locally and in the CI environment. I can setup whitebox testing locally, but not in the CI environment. So I want to profit from the whitebox testing setup locally, but I don't want to duplicate my test suite. I would be nice if the client fixture would have an identical interace as requests has.

What I tried

conftest.py

import pytest
import app
import os
import requests

BASE_URL = "http://staging.example.com"

@pytest.fixture
def client():
    if os.environ.get('WHITEBOX_TESTING'):
        app.app.config['TESTING'] = True

        with app.app.test_client() as client:
            yield client
    else:
        yield requests

test_routes.py

import pytest
import requests

from .conftest import BASE_URL


@pytest.mark.route
def test_route(client):
    resp = client.get(f"{BASE_URL}/api/")
    assert resp.status_code == 200

    # This does not work! It's a function in requests, but an attribute in the flask client:
    resp_dict = resp.json()

    assert resp_dict == {"foo": "bar"}

Aucun commentaire:

Enregistrer un commentaire