How to count sqlalchemy queries in unit tests

后端 未结 3 1235
萌比男神i
萌比男神i 2021-02-04 02:44

In Django I often assert the number of queries that should be made so that unit tests catch new N+1 query problems

from django import db
from django.conf import          


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 03:34

    what about the approach of using flask_sqlalchemy.get_debug_queries() btw. this is the methodology used by internal of Flask Debug Toolbar check its source

    from flask_sqlalchemy import get_debug_queries
    
    
    def test_list_with_assuring_queries_count(app, client):
        with app.app_context():
            # here generating some test data
            for _ in range(10):
                notebook = create_test_scheduled_notebook_based_on_notebook_file(
                    db.session, owner='testing_user',
                    schedule={"kind": SCHEDULE_FREQUENCY_DAILY}
                )
                for _ in range(100):
                    create_test_scheduled_notebook_run(db.session, notebook_id=notebook.id)
        with app.app_context():
            # after resetting the context call actual view we want asserNumOfQueries
            client.get(url_for('notebooks.personal_notebooks'))
            assert len(get_debug_queries()) == 3
    

    keep in mind that for having reset context and count you have to call with app.app_context() before the exact stuff you want to measure.

提交回复
热议问题