Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

python - Pytest teardown of postgresql database in Flask is happening before tests are done

The tests below ran fine when I was using SQLite as the test database. However, the application now requires Postgresql, which is "causing" the tests to hang. While running, when I inspect via select * from pg_stat_activity, the teardown or db.drop_all() process is trying to drop tables (some are dropped) while the second query in test_login_logout is still running.

If I remove db.drop_all() the tests run fine but obviously the database is not wiped-out. What am I doing wrong? Thanks!

@pytest.fixture(scope='module')
def test_client():
    app = create_app('testing')
    with app.test_client() as testing_client:
            with app.app_context():
                yield testing_client


@pytest.fixture(scope='module')
def init_database(test_client):

    db.create_all()

    admin_role = Role(name='admin')
    db.session.add(admin_role)

    user = User(username='testuser', password='password', role=admin_role)
    db.session.add(user)

    db.session.commit()

    yield

    db.drop_all()


class TestPublic:

    def test_login_logout(self, test_client, init_database):
        response = test_client.post('/login', data=dict(
            username='testuser', password='password'), follow_redirects=True)
        assert response.status_code == 200
        assert b"Login successful." in response.data

        response = test_client.post('/login', data=dict(
            username='x', password='x'), follow_redirects=True)
        assert response.status_code == 200
        assert b"Invalid username or password." in response.data

        response = test_client.get('/logout', follow_redirects=True)
        assert response.status_code == 200
        assert b"You have been logged out." in response.data
question from:https://stackoverflow.com/questions/65644936/pytest-teardown-of-postgresql-database-in-flask-is-happening-before-tests-are-do

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Delete the db.drop_all() statement from there and add this function, it's automatically called after all the tests finish:

def pytest_sessionfinish(session, exitstatus):
    """ whole test run finishes. """
    db.drop_all()

Source: https://docs.pytest.org/en/stable/reference.html#pytest.hookspec.pytest_sessionfinish


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...