|
3 | 3 | from __future__ import with_statement |
4 | 4 |
|
5 | 5 | import os |
| 6 | +from functools import partial |
6 | 7 |
|
7 | 8 | import pytest |
8 | 9 |
|
|
17 | 18 | __all__ = ['django_db_setup', 'db', 'transactional_db', 'admin_user', |
18 | 19 | 'django_user_model', 'django_username_field', |
19 | 20 | 'client', 'admin_client', 'rf', 'settings', 'live_server', |
20 | | - '_live_server_helper', 'django_assert_num_queries'] |
| 21 | + '_live_server_helper', 'django_assert_num_queries', |
| 22 | + 'django_assert_max_num_queries'] |
21 | 23 |
|
22 | 24 |
|
23 | 25 | @pytest.fixture(scope='session') |
@@ -352,22 +354,34 @@ def _live_server_helper(request): |
352 | 354 | request.addfinalizer(live_server._live_server_modified_settings.disable) |
353 | 355 |
|
354 | 356 |
|
355 | | -@pytest.fixture(scope='function') |
356 | | -def django_assert_num_queries(pytestconfig): |
| 357 | +@contextmanager |
| 358 | +def _assert_num_queries(config, num, exact=True): |
357 | 359 | from django.db import connection |
358 | 360 | from django.test.utils import CaptureQueriesContext |
| 361 | + verbose = config.getoption('verbose') > 0 |
| 362 | + with CaptureQueriesContext(connection) as context: |
| 363 | + yield |
| 364 | + num_queries = len(context) |
| 365 | + failed = num != num_queries if exact else num < num_queries |
| 366 | + if failed: |
| 367 | + msg = "Expected to perform {} queries {}{}".format( |
| 368 | + num, |
| 369 | + '' if exact else 'or less ', |
| 370 | + 'but {} were done'.format(num_queries) |
| 371 | + ) |
| 372 | + if verbose: |
| 373 | + sqls = (q['sql'] for q in context.captured_queries) |
| 374 | + msg += '\n\nQueries:\n========\n\n%s' % '\n\n'.join(sqls) |
| 375 | + else: |
| 376 | + msg += " (add -v option to show queries)" |
| 377 | + pytest.fail(msg) |
| 378 | + |
359 | 379 |
|
360 | | - @contextmanager |
361 | | - def _assert_num_queries(num): |
362 | | - with CaptureQueriesContext(connection) as context: |
363 | | - yield |
364 | | - if num != len(context): |
365 | | - msg = "Expected to perform %s queries but %s were done" % (num, len(context)) |
366 | | - if pytestconfig.getoption('verbose') > 0: |
367 | | - sqls = (q['sql'] for q in context.captured_queries) |
368 | | - msg += '\n\nQueries:\n========\n\n%s' % '\n\n'.join(sqls) |
369 | | - else: |
370 | | - msg += " (add -v option to show queries)" |
371 | | - pytest.fail(msg) |
372 | | - |
373 | | - return _assert_num_queries |
| 380 | +@pytest.fixture(scope='function') |
| 381 | +def django_assert_num_queries(pytestconfig): |
| 382 | + return partial(_assert_num_queries, pytestconfig) |
| 383 | + |
| 384 | + |
| 385 | +@pytest.fixture(scope='function') |
| 386 | +def django_assert_max_num_queries(pytestconfig): |
| 387 | + return partial(_assert_num_queries, pytestconfig, exact=False) |
0 commit comments