I am writing an API in a flask and I use the application factory. This is how my __init__.py
looks.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Api
db = SQLAlchemy()
api = Api()
def create_app():
app = Flask(__name__, instance_relative_config=False)
app.config.from_object("config.Config")
db.init_app(app)
api.init_app(app)
with app.app_context():
db.create_all()
return app
In wsgi.py (which in entry point to start) I have my endpoints.
# some more imports
from application import create_app
app = create_app()
# some more endpoints
api.add_resource(Products, "/products") # GET
if __name__ == "__main__":
# some more code here..
app.run(debug=True)
Now I want to write some unittest, but the problem is I constantly get 404 not found on the enpoinds, even thought in postman it work fine.
this is my test.
from unittest import TestCase
from application import create_app
from application import db
app = create_app()
class ProductTest(TestCase):
def setUp(self) -> None:
""" Prepare new database and test client. """
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///"
with app.app_context():
db.init_app(app)
db.create_all()
self.app = app.test_client
self.app_context = app.app_context
def test_get_products(self):
with self.app() as client:
with self.app_context():
res = client.get("/products")
self.assertEqual(res.status_code, 200) # it fails - it returns 404 everytime
I suppose there is some problem with the create_app thing. I don't know exactly how to use it in test. When I write the same API but without using the application factory (and thus without create_app), this test passes.
Can anyone explain me what I am doing wrong and how to use create_app from application factory with unit testing endpoints?