Created
August 18, 2020 12:53
-
-
Save KimSoungRyoul/030ce50fab6c896df7f38d5b74252750 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.test.utils import CaptureQueriesContext | |
from rest_framework.test import APIClient | |
def test_check_n_plus_1_problem(): | |
from django.db import connection | |
# Given: 주문이 2개더 추가되기전 API에서 발생하는 SQL Count (expected_num_queries) | |
with CaptureQueriesContext(connection) as expected_num_queries: | |
APIClient().get(path="/restaurants/") | |
# When: 주문이 2개 더 추가된 이후 API에서 발생하는 SQL Count (checked_num_queries) | |
Order.objects.create( | |
total_price=9800, | |
comment="주문데이터가 N개 생성되었다고 SQL이 N개 더 생상되면 안된다1." | |
) | |
Order.objects.create( | |
total_price=8800, | |
comment="주문데이터가 N개 생성되었다고 SQL이 N개 더 생상되면 안된다2." | |
) | |
with CaptureQueriesContext(connection) as checked_num_queries: | |
APIClient().get(path="/restaurants/") | |
# Then: 주문이 2개더 추가된다고 동일 API에서 SQL이 추가발생하면 안된다. | |
assert len(checked_num_queries.captured_queries) == len(expected_num_queries.captured_queries) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment