Test Utils

Contains utilities helpful when testing peewee projects.

class count_queries([only_select=False])

Context manager that will count the number of queries executed within the context.

Parameters:only_select (bool) – Only count SELECT queries.
  1. with count_queries() as counter:
  2. huey = User.get(User.username == 'huey')
  3. huey_tweets = [tweet.message for tweet in huey.tweets]
  4. assert counter.count == 2
  • count

    The number of queries executed.

  • get_queries()

    Return a list of 2-tuples consisting of the SQL query and a list of parameters.

assert_query_count(expected[, only_select=False])

Function or method decorator that will raise an AssertionError if the number of queries executed in the decorated function does not equal the expected number.

  1. class TestMyApp(unittest.TestCase):
  2. @assert_query_count(1)
  3. def test_get_popular_blogs(self):
  4. popular_blogs = Blog.get_popular()
  5. self.assertEqual(
  6. [blog.title for blog in popular_blogs],
  7. ["Peewee's Playhouse!", "All About Huey", "Mickey's Adventures"])

This function can also be used as a context manager:

  1. class TestMyApp(unittest.TestCase):
  2. def test_expensive_operation(self):
  3. with assert_query_count(1):
  4. perform_expensive_operation()