0

I'm new to Python and to Flask but I did manage to create an API that uses SQLAlchemy to interact with the DB.

Now, I'm trying to use integration tests to test my API but the db doesn't create before the API starts so an exception is thrown when I try to access one of it's tables... As I was saying, everything works fine when I manually run the API.

Here is my integration test:

@pytest.fixture()
def app():
    db = SQLAlchemy()
    app = create_app(
        db,
        "sqlite:///:memory:",
        5,
        "secret"
    )
    app.config.update({
        "TESTING": True,
    })

    with app.app_context():
        db.create_all()
    
    yield app.test_client()

    # clean up / reset resources here

def test_valid_create_profile_request_returns_200(app):
    response = app.post("/profiles/",data=json.dumps(dict(name="my_profile")), content_type="application/json")
    assert response.status_code == 200

This is the error message that is thrown when I try to write to the DB:

E       sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: profile_model
E       [SQL: INSERT INTO profile_model (id, name) VALUES (?, ?)]
E       [parameters: ('da134852-db67-11ec-9bcd-d27906eb9227', 'my_profile')]
E       (Background on this error at: https://sqlalche.me/e/14/e3q8)

What am I doing wrong?

RiskX
  • 561
  • 6
  • 20
  • Your `create_all` does not see your models. You should import them before `create_all`. This is a similar topic: https://stackoverflow.com/questions/20744277/sqlalchemy-create-all-does-not-create-tables – jorzel May 24 '22 at 18:22
  • @jorzel Thank you so much for you answer, it led me to fix the problem. The problem however wasn't that I didn't import the models, it was that I created a new instance of SQLAlchemy for the sake of the test but my models where inhriting from a different instance, for a global location I created for the sake of the program. Stupid python patterns. Thanks again – RiskX May 25 '22 at 04:32

0 Answers0