How to count sqlalchemy queries in unit tests

后端 未结 3 1298
萌比男神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条回答
  •  忘掉有多难
    2021-02-04 03:44

    I've created a context manager class for this purpose:

    class DBStatementCounter(object):
        """
        Use as a context manager to count the number of execute()'s performed
        against the given sqlalchemy connection.
    
        Usage:
            with DBStatementCounter(conn) as ctr:
                conn.execute("SELECT 1")
                conn.execute("SELECT 1")
            assert ctr.get_count() == 2
        """
        def __init__(self, conn):
            self.conn = conn
            self.count = 0
            # Will have to rely on this since sqlalchemy 0.8 does not support
            # removing event listeners
            self.do_count = False
            sqlalchemy.event.listen(conn, 'after_execute', self.callback)
    
        def __enter__(self):
            self.do_count = True
            return self
    
        def __exit__(self, *_):
            self.do_count = False
    
        def get_count(self):
            return self.count
    
        def callback(self, *_):
            if self.do_count:
                self.count += 1
    

提交回复
热议问题