I've a very basic Flask application:
#main.py
from flask import Flask
app = Flask(__name__)
@app.route('/sth/')
def hi():
return 'HI\n'
and I try to test the existence of the url, however, to me it seems the routes are not registered:
from flask import Flask
class TestSthView:
def test_sth_returns_ok(self):
app = Flask(__name__)
c = app.test_client()
resp = c.get('/sth/')
assert resp.request.path == '/sth/'
assert resp.status_code == 200
.
Could anybody point me out how can I test the existence of the /sth/ url? Why do I get 404 instead of 200 ?
I went through on many pages about testing, but I still unable to find the mistake.
Thanks.
CodePudding user response:
I believe your issue is with how you're creating a new app in your unit test when you call app = Flask(__name__)
.
If you import your app variable into your unit test (I can't say how to do this exactly without seeing your project layout) but the below code should work if they're in the same directory.
from main import app
class TestSthView:
def test_sth_returns_ok(self):
c = app.test_client()
resp = c.get('/sth/')
assert resp.request.path == '/sth/'
assert resp.status_code == 200
CodePudding user response:
#main.py
from flask import Flask
app = Flask(__name__)
@app.route('/sth/')
def hi():
return 'HI\n'
if __name__ == "__main__":
app.run()
In another terminal you do an easy request e.g.
import requests
r = requests.get('http://127.0.0.1:5000/sth/')
assert r.status_code == 200
Or you do it the Flask native way:
test_example.py
@pytest.fixture()
def app():
app = create_app()
app.config.update({
"TESTING": True,
})
# other setup can go here
yield app
# clean up / reset resources here
@pytest.fixture()
def client(app):
return app.test_client()
def yourtest(client):
response = client.get("/sth/")
assert response.request.path == "/index"
assert response.status_code == 200
using this command in your CLI
pytest test_example.py::yourtest
I didn't test it yet.
My sources:
https://docs.pytest.org/en/7.1.x/how-to/usage.html https://flask.palletsprojects.com/en/2.2.x/testing/