本文整理汇总了Python中django.test.TestCase方法的典型用法代码示例。如果您正苦于以下问题:Python test.TestCase方法的具体用法?Python test.TestCase怎么用?Python test.TestCase使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.test
的用法示例。
在下文中一共展示了test.TestCase方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def setUp(self):
assert self.migrate_from and self.migrate_to, \
"TestCase '{}' must define migrate_from and migrate_to properties".format(type(self).__name__)
executor = MigrationExecutor(connection)
old_apps = executor.loader.project_state(self.migrate_from).apps
# Reverse to the original migration
executor.migrate(self.migrate_from)
self.setUpBeforeMigration(old_apps)
# Run the migration to test
executor = MigrationExecutor(connection)
executor.loader.build_graph() # reload.
executor.migrate(self.migrate_to)
self.apps = executor.loader.project_state(self.migrate_to).apps
示例2: setUp
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def setUp(self) -> None:
assert self.migrate_from and self.migrate_to, \
f"TestCase '{type(self).__name__}' must define migrate_from and migrate_to properties"
migrate_from: List[Tuple[str, str]] = [(self.app, self.migrate_from)]
migrate_to: List[Tuple[str, str]] = [(self.app, self.migrate_to)]
executor = MigrationExecutor(connection)
old_apps = executor.loader.project_state(migrate_from).apps
# Reverse to the original migration
executor.migrate(migrate_from)
self.setUpBeforeMigration(old_apps)
# Run the migration to test
executor = MigrationExecutor(connection)
executor.loader.build_graph() # reload.
executor.migrate(migrate_to)
self.apps = executor.loader.project_state(migrate_to).apps
示例3: test_category_creation
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def test_category_creation(self):
w = self.create_post_history()
self.assertTrue(isinstance(w, PostHistory))
self.assertEqual(w.__str__(), str(w.user.get_username()) + ' ' + str(w.content) + ' ' + str(w.post.title))
# class image_file_models_test(TestCase):
# def create_image_file(self, content="simple content"):
# upload_file = open('/django_blog_it/static/favicon.png', 'rb')
# return Image_File.objects.create(Image_File=upload_file, thumbnail=upload_file, upload=upload_file)
# def test_category_creation(self):
# w = self.create_image_file()
# self.assertTrue(isinstance(w, Image_File))
# self.assertEqual(w.__str__(), str(w.date_created()))
示例4: setUp
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def setUp(self):
assert (
self.migrate_from and self.migrate_to
), "TestCase '{}' must define migrate_from and migrate_to properties".format(
type(self).__name__
)
self.migrate_from = [(self.app, self.migrate_from)]
self.migrate_to = [(self.app, self.migrate_to)]
executor = MigrationExecutor(connection)
old_apps = executor.loader.project_state(self.migrate_from).apps
# Reverse to the original migration
executor.migrate(self.migrate_from)
if self.migrate_fixtures:
self.load_fixtures(self.migrate_fixtures, apps=old_apps)
self.setUpBeforeMigration(old_apps)
# Run the migration to test
executor = MigrationExecutor(connection)
executor.loader.build_graph() # reload.
executor.migrate(self.migrate_to)
self.apps = executor.loader.project_state(self.migrate_to).apps
示例5: _run_test
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def _run_test(serializer_cls, model_cls, sql_queries=1) -> ReturnList:
"""
Boilerplate for running the tests
:return: the serializer data to assert one
"""
print(
f'Running test with serializer "{serializer_cls.__name__}" and model {model_cls.__name__}'
)
case = TestCase()
request = APIRequestFactory().get("/FOO")
with case.assertNumQueries(sql_queries):
prefetched_queryset = prefetch(model_cls.objects.all(), serializer_cls)
serializer_instance = serializer_cls(
instance=prefetched_queryset, many=True, context={"request": request}
)
print("Data returned:")
pprint_result(serializer_instance.data)
return serializer_instance.data
示例6: setUpClass
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def setUpClass(cls):
super(TestCase, cls).setUpClass()
cls.sync_public()
cls.add_allowed_test_domain()
cls.tenant = get_tenant_model()(schema_name=cls.get_test_schema_name())
cls.setup_tenant(cls.tenant)
cls.tenant.save(verbosity=cls.get_verbosity())
tenant_domain = cls.get_test_tenant_domain()
cls.domain = get_domain_model()(tenant=cls.tenant, domain=tenant_domain)
cls.setup_domain(cls.domain)
cls.domain.save()
connection.set_schema(cls.tenant)
cls.cls_atomics = cls._enter_atomics()
try:
cls.setUpTestData()
except Exception:
cls._rollback_atomics(cls.cls_atomics)
raise
示例7: setUp
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def setUp(self):
assert self.migrate_from and self.migrate_to, \
"TestCase '{}' must define migrate_from and migrate_to properties".format(type(self).__name__)
self.migrate_from = [(self.app, self.migrate_from)]
self.migrate_to = [(self.app, self.migrate_to)]
executor = MigrationExecutor(connection)
old_apps = executor.loader.project_state(self.migrate_from).apps
# Reverse to the original migration
executor.migrate(self.migrate_from)
super(TestMigrations, self).setUp()
self.setUpBeforeMigration(old_apps)
# Run the migration to test
executor = MigrationExecutor(connection)
executor.loader.build_graph() # reload.
executor.migrate(self.migrate_to)
self.apps = executor.loader.project_state(self.migrate_to).apps
示例8: test_get_m2m_fields
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def test_get_m2m_fields(self):
fields = list(self.plan_serializer._get_m2m_fields())
fields.sort()
expected_fields = list(MockTestPlanSerializer.m2m_fields)
expected_fields.sort()
self.assertEqual(expected_fields, fields)
fields = list(self.case_serializer._get_m2m_fields())
fields.sort()
expected_fields = []
for field in TestCase._meta.many_to_many:
expected_fields.append(field.name)
expected_fields.sort()
self.assertEqual(expected_fields, fields)
fields = self.product_serializer._get_m2m_fields()
expected_fields = tuple(field.name for field in Product._meta.many_to_many)
self.assertEqual(fields, ())
self.assertEqual(expected_fields, fields)
示例9: test_send_mail_to_case_author
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def test_send_mail_to_case_author(self, send_mail):
expected_subject = _('DELETED: TestCase #%(pk)d - %(summary)s') % {
'pk': self.case.pk,
'summary': self.case.summary
}
expected_body = render_to_string('email/post_case_delete/email.txt', {'case': self.case})
recipients = get_case_notification_recipients(self.case)
self.case.delete()
# Verify notification mail
send_mail.assert_called_once_with(settings.EMAIL_SUBJECT_PREFIX + expected_subject,
expected_body,
settings.DEFAULT_FROM_EMAIL,
recipients,
fail_silently=False)
示例10: _check_login
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def _check_login(self, url, permission_level, request_data=None):
"""For integration tests of django views that can only be accessed by a logged-in user,
the 1st step is to authenticate. This function checks that the given url redirects requests
if the user isn't logged-in, and then authenticates a test user.
Args:
test_case (object): the django.TestCase or unittest.TestCase object
url (string): The url of the django view being tested.
permission_level (string): what level of permission this url requires
"""
response = self.client.get(url)
self.assertEqual(response.status_code, 302) # check that it redirects if you don't login
self.client.force_login(self.no_access_user)
if permission_level == self.AUTHENTICATED_USER:
return
# check that users without view permission users can't access collaborator URLs
if permission_level == self.COLLABORATOR:
if request_data:
response = self.client.post(url, content_type='application/json', data=json.dumps(request_data))
else:
response = self.client.get(url)
self.assertEqual(response.status_code, 403)
self.login_collaborator()
if permission_level == self.COLLABORATOR:
return
response = self.client.get(url)
self.assertEqual(response.status_code, 403 if permission_level == self.MANAGER else 302)
self.client.force_login(self.manager_user)
if permission_level == self.MANAGER:
return
response = self.client.get(url)
self.assertEqual(response.status_code, 302)
self.login_staff_user()
示例11: validate_content
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def validate_content(testcase, data, page_descr="unknown page"):
"""
Validate data as HTML5.
testcase should be a unittest.TestCase object (or similar).
page_descr should be a human-readable description of the page being tested.
"""
parser = html5lib.HTMLParser(tree=html5lib.treebuilders.getTreeBuilder("dom"))
parser.parse(data)
if parser.errors:
fh = open("tmp-validation.html", "wb")
fh.write(data)
fh.close()
testcase.fail("Invalid HTML5 produced in %s:\n %s" % (page_descr, str(parser.errors)))
示例12: partition_suite_by_case
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def partition_suite_by_case(suite):
"""Partition a test suite by test case, preserving the order of tests."""
groups = []
suite_class = type(suite)
for test_type, test_group in itertools.groupby(suite, type):
if issubclass(test_type, unittest.TestCase):
groups.append(suite_class(test_group))
else:
for item in test_group:
groups.extend(partition_suite_by_case(item))
return groups
示例13: addInfo
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def addInfo(self, test: TestCase, msg: str) -> None:
self.stream.write(msg)
self.stream.flush()
示例14: addInstrumentation
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def addInstrumentation(self, test: TestCase, data: Dict[str, Any]) -> None:
append_instrumentation_data(data)
示例15: startTest
# 需要导入模块: from django import test [as 别名]
# 或者: from django.test import TestCase [as 别名]
def startTest(self, test: TestCase) -> None:
TestResult.startTest(self, test)
self.stream.writeln(f"Running {test.id()}") # type: ignore[attr-defined] # https://github.com/python/typeshed/issues/3139
self.stream.flush()