I am trying to work out how to use pytest to test the most basic Flask app. (I'm on Windows 10). Here is the app code, myapp.py:
from flask import Flask
api = Flask(__name__)
@api.route('/', methods=['GET'])
def index():
return 'Index Page'
When I go to http://127.0.0.1:5000/ in a browser, or when I use curl to issue a GET request to that URL it works correctly, I see the 'Index Page' response text.
Then I set up a basic test script, test_app.py:
import pytest
from flask import Flask
def test_assert():
assert True
def test_home_page(client):
response = client.get('/')
assert response.status_code == 200
@pytest.fixture
def client():
flask_app = Flask(__name__)
client = flask_app.test_client()
return client
I added the first trivial test_assert() function just to ensure pytest was working (I'm v new to python).
Now, when I run pytest (>pytest -v) the first (trivial) test passes, but the test_home_page() test fails. The app returns status code 404 when run through pytest.
collected 2 items
test_app.py::test_assert PASSED [ 50%]
test_app.py::test_home_page FAILED [100%]
====================================================== FAILURES =======================================================
___________________________________________________ test_home_page ____________________________________________________
client = <FlaskClient <Flask 'test_app'>>
def test_home_page(client):
response = client.get('/')
> assert response.status_code == 200
E assert 404 == 200
E -404
E +200
test_app.py:10: AssertionError
========================================= 1 failed, 1 passed in 0.28 seconds ====
I've spent a couple of days reading around trying to determine why pytest fails for this simple example -- the response should be 200, but it keeps giving 404.
Can anyone see what I've done wrong or why this won't work? Thanks.
try this:
from YOUR_MODULE import api
def test_assert():
assert True
def test_home_page(client):
response = client.get('/')
assert response.status_code == 200
@pytest.fixture
def client():
client = api.test_client()
return client
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.