Reputation: 543
I don't know why my pytest fails when they shouldn't.
I have a REST API flask server, with the following folder structure:
.
├── api
│ ├── conf
│ ├── database
│ ├── error
│ ├── handlers
│ ├── models
│ ├── roles
│ ├── schemas
│ └── test.db
├── main.py
├── tests
│ ├── conftest.py
│ └── test_routes.py
My tests are:
tests/conftest.py:
import pytest
from main import app as flask_app
@pytest.fixture
def app():
yield flask_app
@pytest.fixture
def client(app):
return app.test_client()
tests/test_routes.py:
def test_algorithms_get(app, client):
res = client.get('/algorithms')
assert res.status_code == 200
Now, I tried running python3 -m pytest
in the .
folder both with flask server running and not, but the test always fails and I get 404 status_code instead of 200. I know for sure that the route is perfectly working, but I can't get why the test fails.
This is the first time I use pytest (or any Unit Test framework) so I'm sure I'm missing something, any help would be much appreciated.
Upvotes: 2
Views: 1772
Reputation: 543
Solved. It was a configuration error.
Indeed, I was making a mistake in the create_app() factory.
As I learned also, it is much better to define the create_app in the init.py file in the parent directory of your server (I was defining the function in main.py).
To be clear I moved the create_app factory definition here (*):
.
├── api
│ ├── __init__.py *
│ ├── conf
│ ├── database
│ ├── error
│ ├── handlers
│ ├── models
│ ├── roles
│ ├── schemas
│ └── test.db
├── main.py
├── tests
│ ├── conftest.py
│ └── test_routes.py
New tests/conftest.py:
import pytest
from api import create_app
@pytest.fixture
def app():
flask_app = create_app({'TESTING': True})
yield flask_app
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture
def runner(app):
return app.test_cli_runner()
Finally, I call python3 -m pytest
in the uppermost folder (.
) to run the tests.
Now tests are working and I'm also able to create different configurations for testing and other use cases.
Upvotes: 1