Python django.test.TestCase() Examples

The following are 30 code examples for showing how to use django.test.TestCase(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module django.test , or try the search function .

Example 1
Project: karrot-backend   Author: yunity   File: utils.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example 2
Project: zulip   Author: zulip   File: test_classes.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 3
Project: django-blog-it   Author: MicroPyramid   File: tests.py    License: MIT License 6 votes vote down vote up
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())) 
Example 4
Project: byro   Author: byro   File: helper.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 5
Project: django-auto-prefetching   Author: GeeWee   File: tests.py    License: MIT License 6 votes vote down vote up
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 
Example 6
Project: django-pgschemas   Author: lorinkoz   File: cases.py    License: MIT License 6 votes vote down vote up
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 
Example 7
Project: chain-api   Author: ResEnv   File: test_migrations.py    License: MIT License 6 votes vote down vote up
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 
Example 8
Project: Kiwi   Author: kiwitcms   File: test_serializer.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 9
Project: Kiwi   Author: kiwitcms   File: test_models.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 10
Project: seqr   Author: macarthur-lab   File: test_utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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() 
Example 11
Project: coursys   Author: sfu-fas   File: testing.py    License: GNU General Public License v3.0 5 votes vote down vote up
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))) 
Example 12
Project: bioforum   Author: reBiocoder   File: runner.py    License: MIT License 5 votes vote down vote up
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 
Example 13
Project: zulip   Author: zulip   File: test_runner.py    License: Apache License 2.0 5 votes vote down vote up
def addInfo(self, test: TestCase, msg: str) -> None:
        self.stream.write(msg)
        self.stream.flush() 
Example 14
Project: zulip   Author: zulip   File: test_runner.py    License: Apache License 2.0 5 votes vote down vote up
def addInstrumentation(self, test: TestCase, data: Dict[str, Any]) -> None:
        append_instrumentation_data(data) 
Example 15
Project: zulip   Author: zulip   File: test_runner.py    License: Apache License 2.0 5 votes vote down vote up
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() 
Example 16
Project: zulip   Author: zulip   File: test_runner.py    License: Apache License 2.0 5 votes vote down vote up
def addSkip(self, test: TestCase, reason: str) -> None:
        TestResult.addSkip(self, test, reason)
        self.stream.writeln("** Skipping {}: {}".format(  # type: ignore[attr-defined] # https://github.com/python/typeshed/issues/3139
            test.id(),
            reason))
        self.stream.flush() 
Example 17
Project: zulip   Author: zulip   File: test_runner.py    License: Apache License 2.0 5 votes vote down vote up
def addInfo(self, test: TestCase, msg: str) -> None:
        self.events.append(('addInfo', self.test_index, msg)) 
Example 18
Project: zulip   Author: zulip   File: test_runner.py    License: Apache License 2.0 5 votes vote down vote up
def run_subsuite(args: SubsuiteArgs) -> Tuple[int, Any]:
    # Reset the accumulated INSTRUMENTED_CALLS before running this subsuite.
    test_helpers.INSTRUMENTED_CALLS = []
    # The first argument is the test runner class but we don't need it
    # because we run our own version of the runner class.
    _, subsuite_index, subsuite, failfast = args
    runner = RemoteTestRunner(failfast=failfast)
    result = runner.run(deserialize_suite(subsuite))
    # Now we send instrumentation related events. This data will be
    # appended to the data structure in the main thread. For Mypy,
    # type of Partial is different from Callable. All the methods of
    # TestResult are passed TestCase as the first argument but
    # addInstrumentation does not need it.
    process_instrumented_calls(partial(result.addInstrumentation, None))
    return subsuite_index, result.events 
Example 19
Project: zulip   Author: zulip   File: test_runner.py    License: Apache License 2.0 5 votes vote down vote up
def get_tests_from_suite(suite: TestSuite) -> TestCase:
    for test in suite:
        if isinstance(test, TestSuite):
            yield from get_tests_from_suite(test)
        else:
            yield test 
Example 20
Project: interop   Author: auvsi-suas   File: pb_utils_test.py    License: Apache License 2.0 5 votes vote down vote up
def TestFieldChociesFromEnum(TestCase):
    """Tests the FieldChoicesFromEnum utility."""
    def test_generates_choices(self):
        """Tests generates choices for a sample enum."""
        self.assertEqual([(1, 'N'), (2, 'NE'), (3, 'E'), (4, 'SE'), (5, 'S'),
                          (6, 'SW'), (7, 'W'), (8, 'NW')],
                         sorted(
                             pb_utils.FieldChoicesFromEnum(
                                 interop_api_pb2.Odlc.Orientation))) 
Example 21
Project: cadasta-platform   Author: Cadasta   File: test_managers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_create_options_with_empty_list(TestCase):
        errors = []
        question = factories.QuestionFactory.create(name='qu')
        managers.create_options([], question, errors)
        assert "Please provide at least one option for field 'qu'" in errors 
Example 22
Project: cadasta-platform   Author: Cadasta   File: test_migrations.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(UserTestCase, self).setUp()

        assert self.migrate_from and self.migrate_to
        "TestCase '{}' must define migrate_from and migrate_to "
        "properties".format(type(self).__name__)

        # get the application state pre-migration
        apps_before = self._get_apps_for_migration(
            [(self.app, self.migrate_from)])

        # Reverse to migrate_from
        call_command('migrate', 'accounts',
                     '0002_activate_users_20161014_0846', '--noinput')
        call_command('migrate', 'organization',
                     '0004_remove_Pb_project_roles', '--noinput')
        call_command('migrate', self.app, self.migrate_from, '--noinput')

        # setup pre-migration test data
        self.setUpBeforeMigration(apps_before)

        # Run the migration to test
        call_command('migrate', self.app, self.migrate_to, '--noinput')

        # get application state post-migration
        self.apps_after = self._get_apps_for_migration(
            [(self.app, self.migrate_to)]) 
Example 23
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: runner.py    License: MIT License 5 votes vote down vote up
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 
Example 24
def setUp(self):
        super().setUp()
        # ContentTypeManager uses a cache to speed up ContentType retrieval. This
        # cache persists across tests. This is fine in the context of a regular
        # TestCase which uses a transaction to reset the database between tests.
        # However, it becomes a problem in subclasses of TransactionTestCase which
        # truncate all tables to reset the database between tests. When tables are
        # truncated, ContentType objects in the ContentTypeManager's cache become
        # stale. Attempting to use these stale objects in tests such as the ones
        # below, which create LogEntry objects as a side-effect of interacting with
        # the admin, will result in IntegrityErrors on databases that check foreign
        # key constraints (e.g., MySQL). Preemptively clearing the cache prevents
        # stale ContentType objects from being used.
        ContentType.objects.clear_cache()

        self.site.domain = self.live_server_url.strip('http://')
        self.site.save()

        self.course_runs = factories.CourseRunFactory.create_batch(2)
        self.courses = [course_run.course for course_run in self.course_runs]

        self.excluded_course_run = factories.CourseRunFactory(course=self.courses[0])
        self.program = factories.ProgramFactory(
            courses=self.courses, excluded_course_runs=[self.excluded_course_run], status=ProgramStatus.Unpublished
        )

        self.user = UserFactory(is_staff=True, is_superuser=True)
        self._login() 
Example 25
Project: wagtail   Author: wagtail   File: test_views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tearDown(self):
        if hasattr(self, 'response'):
            # Make sure the response is fully read before deleting the document so
            # that the file is closed by the view.
            # This is required on Windows as the below line that deletes the file
            # will crash if the file is still open.
            b"".join(self.response.streaming_content)

        # delete the FieldFile directly because the TestCase does not commit
        # transactions to trigger transaction.on_commit() in the signal handler
        self.document.file.delete() 
Example 26
Project: wagtail   Author: wagtail   File: test_views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tearDown(self):
        # delete the FieldFile directly because the TestCase does not commit
        # transactions to trigger transaction.on_commit() in the signal handler
        self.document.file.delete() 
Example 27
Project: wagtail   Author: wagtail   File: test_views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tearDown(self):
        # delete the FieldFile directly because the TestCase does not commit
        # transactions to trigger transaction.on_commit() in the signal handler
        self.document.file.delete() 
Example 28
Project: wagtail   Author: wagtail   File: test_models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tearDown(self):
        # delete the FieldFile directly because the TestCase does not commit
        # transactions to trigger transaction.on_commit() in the signal handler
        self.document.file.delete()
        self.extensionless_document.file.delete() 
Example 29
Project: pythonic-news   Author: sebst   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_subscribe_confirm_unsubscribe_subscribe_confirm(self):
        subscription = self._subscribe()
        self._confirm(subscription)
        
        unsubscription = self._unsubscribe_via_mail(subscription)

        subscription = Subscription.objects.get(pk=subscription.pk)
        self.assertFalse(subscription.is_active)

        re_subscription = self._subscribe(i=1)
        self._confirm(re_subscription)

        re_subscription = Subscription.objects.get(pk=re_subscription.pk)
        subscription = Subscription.objects.get(pk=subscription.pk)
        self.assertTrue(re_subscription.is_active)
        self.assertFalse(subscription.is_active)



# class ReceiversEmailDigestTest(TestCase):
#     """Tests the basic receivers functionality of the emaildigest app."""
#     def setUp(self):
#         # Every test needs access to the request factory.
#         self.factory = RequestFactory()
#         self.user = CustomUser.objects.create_user(
#             username='sebst', email='hi@seb.st', password='top_secret')
#         self.other_user = CustomUser.objects.create_user(
#             username='bla1', email='two@seb.st', password='top_secret')


#     def test_lower_email_addresses(self):
#         self.fail()

#     def activate_subscription_on_verification(self):
#         self.fail()

#     def test_on_subscription_created(self):
#         self.fail()

#     def test_on_unsubscription_created(self):
#         self.fail() 
Example 30
Project: python   Author: Yeah-Kun   File: runner.py    License: Apache License 2.0 5 votes vote down vote up
def partition_suite_by_case(suite):
    """
    Partitions 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