Souad
Souad

Reputation: 5094

pytest is failed: can't find the requested URL

I have this Flask app:

myapp.py :

def create_app():
    app = Flask(__name__)
    return app

app = create_app()
session = session_factory()


def connect_db():
    engine = get_engine()
    return engine.connect()

@app.route("/")
def hello():
    return "Hello everyone"

I want to write some pytest tests so I created two files:

conftest.py:

import pytest
from app.myapp import create_app

@pytest.fixture
def app():
    app = create_app()
    return app

@pytest.fixture
def client(app):
    return app.test_client()

@pytest.fixture
def runner(app):
    return app.test_cli_runner()

test_endpoints.py

import pytest
from flask import *

def test_hello(client):
    response = client.get("/")
    assert response.data == b'Hello everyone'

When I run pytest, I get this error:

>       assert response.data == b'Hello everyone'
E       assert '<!DOCTYPE HT... again.</p>\n' == 'Hello everyone'
E         + Hello everyone
E         - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
E         - <title>404 Not Found</title>
E         - <h1>Not Found</h1>
E         - <p>The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.</p>

Why pytest can't find the endpoint ? What can I add here to let it work ?

Upvotes: 1

Views: 1851

Answers (1)

AKX
AKX

Reputation: 168967

You're not adding any routes to the app you get from create_app() in your fixture.

If you consider your code

def create_app():
    app = Flask(__name__)
    return app

app = create_app()

# ...

@app.route("/")
def hello():
    return "Hello everyone"

, that hello route is only added to that global app instance, not the one you acquire from the fixture.

The Flask tutorial, which covers testing, uses blueprints to mount paths in the create_app function. You might want to do that too; something like this.

bp = Blueprint('greetings', __name__)

@bp.route("/")
def hello():
    return "Hello everyone"

def create_app():
    app = Flask(__name__)
    app.register_blueprint(bp)
    return app

Upvotes: 3

Related Questions