本文整理匯總了Python中django.test.utils.CaptureQueriesContext方法的典型用法代碼示例。如果您正苦於以下問題:Python utils.CaptureQueriesContext方法的具體用法?Python utils.CaptureQueriesContext怎麽用?Python utils.CaptureQueriesContext使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.test.utils
的用法示例。
在下文中一共展示了utils.CaptureQueriesContext方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_running_without_changes
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_running_without_changes(self):
project_state = self.set_up_test_model("test_arstd")
operation = AlterStorageEngine("Pony", from_engine="MyISAM", to_engine="InnoDB")
assert table_storage_engine("test_arstd_pony") == "InnoDB"
# Forwards - shouldn't actually do an ALTER since it is already InnoDB
new_state = project_state.clone()
operation.state_forwards("test_arstd", new_state)
capturer = CaptureQueriesContext(connection)
with capturer, connection.schema_editor() as editor:
operation.database_forwards("test_arstd", editor, project_state, new_state)
queries = [q["sql"] for q in capturer.captured_queries]
assert not any(q.startswith("ALTER TABLE ") for q in queries)
assert table_storage_engine("test_arstd_pony") == "InnoDB"
# Backwards - will actually ALTER since it is going 'back' to MyISAM
with connection.schema_editor() as editor:
operation.database_backwards("test_arstd", editor, new_state, project_state)
assert table_storage_engine("test_arstd_pony") == "MyISAM"
# Copied from django core migration tests
示例2: test_ticket11881
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_ticket11881(self):
"""
Subqueries do not needlessly contain ORDER BY, SELECT FOR UPDATE or
select_related() stuff.
"""
qs = Book.objects.all().select_for_update().order_by(
'pk').select_related('publisher').annotate(max_pk=Max('pk'))
with CaptureQueriesContext(connection) as captured_queries:
qs.aggregate(avg_pk=Avg('max_pk'))
self.assertEqual(len(captured_queries), 1)
qstr = captured_queries[0]['sql'].lower()
self.assertNotIn('for update', qstr)
forced_ordering = connection.ops.force_no_ordering()
if forced_ordering:
# If the backend needs to force an ordering we make sure it's
# the only "ORDER BY" clause present in the query.
self.assertEqual(
re.findall(r'order by (\w+)', qstr),
[', '.join(f[1][0] for f in forced_ordering).lower()]
)
else:
self.assertNotIn('order by', qstr)
self.assertEqual(qstr.count(' join '), 0)
示例3: test_add_field
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_add_field(self):
"""
Tests adding fields to models
"""
# Create the table
with connection.schema_editor() as editor:
editor.create_model(Author)
# Ensure there's no age field
columns = self.column_classes(Author)
self.assertNotIn("age", columns)
# Add the new field
new_field = IntegerField(null=True)
new_field.set_attributes_from_name("age")
with CaptureQueriesContext(connection) as ctx, connection.schema_editor() as editor:
editor.add_field(Author, new_field)
drop_default_sql = editor.sql_alter_column_no_default % {
'column': editor.quote_name(new_field.name),
}
self.assertFalse(any(drop_default_sql in query['sql'] for query in ctx.captured_queries))
# Ensure the field is right afterwards
columns = self.column_classes(Author)
self.assertEqual(columns['age'][0], "IntegerField")
self.assertEqual(columns['age'][1][6], True)
示例4: test_basic
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_basic(self):
querysets = [
Tag.objects.filter(name='test'),
Tag.objects.filter(name='test').select_related('parent'),
Tag.objects.filter(name='test').prefetch_related('children'),
Tag.objects.filter(name='test').annotate(Count('children')),
Tag.objects.filter(name='test').values_list('name'),
Tag.objects.order_by().union(Tag.objects.order_by().filter(name='test')),
Tag.objects.all().select_for_update().filter(name='test'),
]
supported_formats = connection.features.supported_explain_formats
all_formats = (None,) + tuple(supported_formats) + tuple(f.lower() for f in supported_formats)
for idx, queryset in enumerate(querysets):
for format in all_formats:
with self.subTest(format=format, queryset=idx):
if connection.vendor == 'mysql':
# This does a query and caches the result.
connection.features.needs_explain_extended
with self.assertNumQueries(1), CaptureQueriesContext(connection) as captured_queries:
result = queryset.explain(format=format)
self.assertTrue(captured_queries[0]['sql'].startswith(connection.ops.explain_prefix))
self.assertIsInstance(result, str)
self.assertTrue(result)
示例5: test_postgres_options
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_postgres_options(self):
qs = Tag.objects.filter(name='test')
test_options = [
{'COSTS': False, 'BUFFERS': True, 'ANALYZE': True},
{'costs': False, 'buffers': True, 'analyze': True},
{'verbose': True, 'timing': True, 'analyze': True},
{'verbose': False, 'timing': False, 'analyze': True},
]
if connection.pg_version >= 100000:
test_options.append({'summary': True})
for options in test_options:
with self.subTest(**options), transaction.atomic():
with CaptureQueriesContext(connection) as captured_queries:
qs.explain(format='text', **options)
self.assertEqual(len(captured_queries), 1)
for name, value in options.items():
option = '{} {}'.format(name.upper(), 'true' if value else 'false')
self.assertIn(option, captured_queries[0]['sql'])
示例6: test_for_update_sql_generated_of
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_for_update_sql_generated_of(self):
"""
The backend's FOR UPDATE OF variant appears in the generated SQL when
select_for_update() is invoked.
"""
with transaction.atomic(), CaptureQueriesContext(connection) as ctx:
list(Person.objects.select_related(
'born__country',
).select_for_update(
of=('born__country',),
).select_for_update(
of=('self', 'born__country')
))
features = connections['default'].features
if features.select_for_update_of_column:
expected = ['"select_for_update_person"."id"', '"select_for_update_country"."id"']
else:
expected = ['"select_for_update_person"', '"select_for_update_country"']
if features.uppercases_column_names:
expected = [value.upper() for value in expected]
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, of=expected))
示例7: test_update_parent_filtering
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_update_parent_filtering(self):
"""
Updating a field of a model subclass doesn't issue an UPDATE
query constrained by an inner query (#10399).
"""
supplier = Supplier.objects.create(
name='Central market',
address='610 some street',
)
# Capture the expected query in a database agnostic way
with CaptureQueriesContext(connection) as captured_queries:
Place.objects.filter(pk=supplier.pk).update(name=supplier.name)
expected_sql = captured_queries[0]['sql']
# Capture the queries executed when a subclassed model instance is saved.
with CaptureQueriesContext(connection) as captured_queries:
supplier.save(update_fields=('name',))
for query in captured_queries:
sql = query['sql']
if 'UPDATE' in sql:
self.assertEqual(expected_sql, sql)
示例8: test_for_update_sql_generated_of
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_for_update_sql_generated_of(self):
"""
The backend's FOR UPDATE OF variant appears in the generated SQL when
select_for_update() is invoked.
"""
with transaction.atomic(), CaptureQueriesContext(connection) as ctx:
list(Person.objects.select_related(
'born__country',
).select_for_update(
of=('born__country',),
).select_for_update(
of=('self', 'born__country')
))
features = connections['default'].features
if features.select_for_update_of_column:
expected = ['select_for_update_person"."id', 'select_for_update_country"."id']
else:
expected = ['select_for_update_person', 'select_for_update_country']
expected = [connection.ops.quote_name(value) for value in expected]
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, of=expected))
示例9: test_makes_no_db_queries
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
res = client.get("/api/v1/classify_client/")
assert res.status_code == 200
assert len(queries) == 0
示例10: test_apis_make_a_reasonable_number_of_db_queries
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_apis_make_a_reasonable_number_of_db_queries(client, endpoint, Factory):
"""
Naive versions of these views could easily make several queries
per item, which is very slow. Make sure that isn't the case.
"""
Factory.create_batch(100)
queries = CaptureQueriesContext(connection)
with queries:
res = client.get(endpoint)
assert res.status_code == 200
# Anything under 100 isn't doing one query per recipe.
assert len(queries) < 100
示例11: test_apis_makes_a_reasonable_number_of_db_queries
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_apis_makes_a_reasonable_number_of_db_queries(endpoint, Factory, client, settings):
# Naive versions of this view could easily make several queries
# per item, which is very slow. Make sure that isn't the case.
Factory.create_batch(100)
queries = CaptureQueriesContext(connection)
with queries:
res = client.get(endpoint)
assert res.status_code == 200
# Pagination naturally makes one query per item in the page. Anything
# under `page_size * 2` isn't doing any additional queries per recipe.
page_size = settings.REST_FRAMEWORK["PAGE_SIZE"]
assert len(queries) < page_size * 2, queries
示例12: test_makes_no_db_queries
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
url = reverse("selfrepair:index", args=["en-US"])
res = client.get(url)
assert res.status_code == 200
assert len(queries) == 0
示例13: test_prefetch
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_prefetch(self):
descriptor_schema_1 = DescriptorSchema.objects.create(
contributor=self.contributor,
)
descriptor_schema_2 = DescriptorSchema.objects.create(contributor=self.user,)
for _ in range(5):
collection = Collection.objects.create(
contributor=self.contributor, descriptor_schema=descriptor_schema_1
)
assign_perm("view_collection", self.contributor, collection)
for _ in range(5):
collection = Collection.objects.create(
contributor=self.user, descriptor_schema=descriptor_schema_2
)
assign_perm("view_collection", self.contributor, collection)
request = factory.get("/", "", format="json")
force_authenticate(request, self.contributor)
conn = connections[DEFAULT_DB_ALIAS]
with CaptureQueriesContext(conn) as captured_queries:
response = self.collection_list_viewset(request)
self.assertEqual(len(response.data), 10)
self.assertEqual(len(captured_queries), 60)
示例14: test_prefetch
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_prefetch(self):
self.relation_group.delete()
self.relation_series.delete()
descriptor_schema_1 = DescriptorSchema.objects.create(
contributor=self.contributor,
)
descriptor_schema_2 = DescriptorSchema.objects.create(contributor=self.user,)
self.collection.descriptor_schema = descriptor_schema_1
self.collection.save()
self.collection_2.contributor = self.user
self.collection_2.descriptor_schema = descriptor_schema_2
self.collection_2.save()
for i in range(5):
relation = Relation.objects.create(
contributor=self.contributor,
type=self.rel_type_group,
category="replicates-{}".format(i),
collection=self.collection,
)
assign_perm("view_relation", self.contributor, relation)
for i in range(5):
relation = Relation.objects.create(
contributor=self.user,
type=self.rel_type_group,
category="replicates-{}".format(i),
collection=self.collection_2,
)
assign_perm("view_relation", self.contributor, relation)
conn = connections[DEFAULT_DB_ALIAS]
with CaptureQueriesContext(conn) as captured_queries:
response = self._get_list(self.contributor)
self.assertEqual(len(response.data), 10)
self.assertEqual(len(captured_queries), 12)
示例15: test_lbheartbeat_makes_no_db_queries
# 需要導入模塊: from django.test import utils [as 別名]
# 或者: from django.test.utils import CaptureQueriesContext [as 別名]
def test_lbheartbeat_makes_no_db_queries(dockerflow_middleware, rf):
queries = CaptureQueriesContext(connection)
request = rf.get("/__lbheartbeat__")
with queries:
response = dockerflow_middleware.process_request(request)
assert response.status_code == 200
assert len(queries) == 0