'flask test_client returns 404 for valid url

I've been writing an API and I want to test it. Get requests to API by requests are working well but when I want to test by test_client I have always received

<Response streamed [404 NOT FOUND]>

I handled a 404 error and checked if the URL is correct and it’s correct, SERVER_NAME also is matched with an app URL.

I'm using Python 3, Flask, flask_restplus, pytest

Here is some code that I use:

test_api.py

import pytest


@pytest.mark.parametrize("entity, expected", RESPONSE.items())
@pytest.mark.usefixtures("app")
def test_api_1(app, entity, expected):

    with app.test_client() as client:
        response = client.get(f"/api/{entity}")

    actual = response.json

    assert actual == expected

conftest.py

import pytest

from flask_app import create_app
from flask_app.extensions import db


@pytest.yield_fixture(scope="session", autouse=True)
def app():
    _app = create_app()
    _app.config.testing = True
    _app.engine = db.get_engine(_app)
    _app.connection = _app.engine.connect()
    ctx = _app.app_context()
    ctx.push()
    yield _app

    ctx.pop()

And app config:

<Config {'DEBUG': True, 'TESTING': True, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': 'key', 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'USE_X_SENDFILE': False, 'SERVER_NAME': '0.0.0.0:8020', 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': '0.0.0.0', 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(seconds=43200), 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093, 'API_URL_PREFIX': '/api', 'APP_PORT': '8020', 'POSTGRES': {'user': 'test', 'pw': 'temporal', 'db': 'test', 'host': 'postgres', 'port': '5432'}, 'RESTPLUS_JSON': {'default': <function decimal_json_default at 0x1065179d8>}}>


Solution 1:[1]

Find a place after the app instance is created where you can put in a breakpoint() if on Python 3.7+ or pytest.set_trace() if on some other version.

Look at the app.url_map and iterate over the Rule instance using iter_rules. See if anything looks funny.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KetZoomer