Running a single test works, but running multiple tests fails - Flask and Pytest

Viewed 988

This is really strange. I have the following simple flask application:

- root
- myapp
  - a route with /subscription_endpoint
- tests
  - test_az.py
  - test_bz.py

test_az.py and test_bz.py look both the same. There is a setup (taken from https://diegoquintanav.github.io/flask-contexts.html) and then one simple test:

import pytest
from myapp import create_app
import json

@pytest.fixture(scope='module')
def app(request):
    from myapp import create_app
    return create_app('testing')


@pytest.fixture(autouse=True)
def app_context(app):
    """Creates a flask app context"""
    with app.app_context():
        yield app

@pytest.fixture
def client(app_context):
    return app_context.test_client(use_cookies=True)


def test_it(client):
    sample_payload = {"test": "test"}
    response = client.post("/subscription_endpoint", json=sample_payload)
    assert response.status_code == 500

running pytest, will run both files, but test_az.py will succeed, while test_bz.py will fail. The http request will return a 404 error, meaning test_bz cannot find the route in the app. If I run them individually, then they booth succeed. This is very strange! It seems like the first test is somehow influencing the second test.

I have added actually a third test test_cz.py, which will fail as well. So only the first one will ever run. I feel like this has something todo with those fixtures, but no idea where to look.

1 Answers

Create a conftest.py for fixtures e.g. for client fixture and use the same fixture in both tests?

Now if you're saying that the provided code is the example of a test that is the same in another file, then you are creating 2 fixtures for a client. I would first clean it up and create a 1 conftest.py that contains all the fixtures and then use them in your tests this might help you.

Check out also how to use pytest as described in Flask documentation

Related