Python django.test.TestCase() Examples

The following are 30 code examples of django.test.TestCase(). 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 also want to check out all available functions/classes of the module django.test , or try the search function .
Example #1
Source File: utils.py    From karrot-backend with GNU Affero General Public License v3.0 7 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
Source File: test_migrations.py    From chain-api with 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 #3
Source File: test_serializer.py    From Kiwi with 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 #4
Source File: cases.py    From django-pgschemas with 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 #5
Source File: test_models.py    From Kiwi with 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 #6
Source File: tests.py    From django-auto-prefetching with 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 #7
Source File: test_views.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 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 #8
Source File: runner.py    From python with Apache License 2.0 6 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 
Example #9
Source File: tests.py    From pythonic-news with GNU Affero General Public License v3.0 6 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 #10
Source File: test_classes.py    From zulip with 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 #11
Source File: test_models.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 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 #12
Source File: tests.py    From django-blog-it with 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 #13
Source File: helper.py    From byro with 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 #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_connect_isolation_level(self):
        """
        The transaction level can be configured with
        DATABASES ['OPTIONS']['isolation_level'].
        """
        import psycopg2
        from psycopg2.extensions import (
            ISOLATION_LEVEL_READ_COMMITTED as read_committed,
            ISOLATION_LEVEL_SERIALIZABLE as serializable,
        )
        # Since this is a django.test.TestCase, a transaction is in progress
        # and the isolation level isn't reported as 0. This test assumes that
        # PostgreSQL is configured with the default isolation level.

        # Check the level on the psycopg2 connection, not the Django wrapper.
        default_level = read_committed if psycopg2.__version__ < '2.7' else None
        self.assertEqual(connection.connection.isolation_level, default_level)

        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS']['isolation_level'] = serializable
        try:
            # Start a transaction so the isolation level isn't reported as 0.
            new_connection.set_autocommit(False)
            # Check the level on the psycopg2 connection, not the Django wrapper.
            self.assertEqual(new_connection.connection.isolation_level, serializable)
        finally:
            new_connection.close() 
Example #15
Source File: test_views.py    From connect with MIT License 5 votes vote down vote up
def setUp(self):
        """Setup the SubscriptionUpdateViewTest TestCase"""
        self.view = views.SubscriptionUpdateView()
        factory = RequestFactory()
        self.view.request = factory.get('/')
        self.user = mommy.make('accounts.User')
        self.group = mommy.make('groups.Group')
        self.user.add_to_group(self.group.pk)
        self.view.request.user = self.user
        self.view.kwargs = {'group_id': self.group.pk} 
Example #16
Source File: tests.py    From jeeves with MIT License 5 votes vote down vote up
def tearDownClass():
        time = sum([float(q['time']) for q in connection.queries])
        t = Template("{{count}} quer{{count|pluralize:\"y,ies\"}} in {{time}} seconds:\n\n{% for sql in sqllog %}[{{forloop.counter}}] {{sql.time}}s: {{sql.sql|safe}}{% if not forloop.last %}\n\n{% endif %}{% endfor %}")
        print >> sys.stderr, t.render(Context({'sqllog': connection.queries, 'count': len(connection.queries), 'time': time}))

        # Empty the query list between TestCase.
        connection.queries = []

    # Tests that writes create the appropriate rows with associated Jeeves
    # bookkeeping. 
Example #17
Source File: tests.py    From django-scarface with MIT License 5 votes vote down vote up
def connection_test(a=None, connection=None):
    return a, connection


    # class ExtractKeysCommand(TestCase):
    #     def test_command_output(self):
    #         out = StringIO()
    #         call_command("extract_keys", file="local_push.p12", password="bazinga",
    #                      stdout=out)
    #         out_getvalue = out.getvalue()
    #         self.assertIn('SCARFACE_APNS_CERTIFICATE', out_getvalue) 
Example #18
Source File: test_ajax.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def _assert_default_tester_is(self, expected_value):
        for test_case in TestCase.objects.filter(plan=self.plan):
            self.assertEqual(test_case.default_tester, expected_value) 
Example #19
Source File: test_serializer.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def test_serialize_queryset_with_empty_querset(self):
        cases = self.cases.filter(pk__lt=0)  # pylint: disable=no-member
        serializer = MockTestCaseSerializer(TestCase, cases)
        result = serializer.serialize_queryset()
        self.assertTrue(len(result) == 0) 
Example #20
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_connect_isolation_level(self):
        """
        The transaction level can be configured with
        DATABASES ['OPTIONS']['isolation_level'].
        """
        import psycopg2
        from psycopg2.extensions import (
            ISOLATION_LEVEL_READ_COMMITTED as read_committed,
            ISOLATION_LEVEL_SERIALIZABLE as serializable,
        )
        # Since this is a django.test.TestCase, a transaction is in progress
        # and the isolation level isn't reported as 0. This test assumes that
        # PostgreSQL is configured with the default isolation level.

        # Check the level on the psycopg2 connection, not the Django wrapper.
        default_level = read_committed if psycopg2.__version__ < '2.7' else None
        self.assertEqual(connection.connection.isolation_level, default_level)

        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS']['isolation_level'] = serializable
        try:
            # Start a transaction so the isolation level isn't reported as 0.
            new_connection.set_autocommit(False)
            # Check the level on the psycopg2 connection, not the Django wrapper.
            self.assertEqual(new_connection.connection.isolation_level, serializable)
        finally:
            new_connection.close() 
Example #21
Source File: test_views.py    From connect with MIT License 5 votes vote down vote up
def setUp(self):
        """Setup the SubscriptionUpdateViewTest TestCase"""
        self.subscription1 = Subscription.objects.create(
            user=self.user2, group=self.group)
        self.group2 = Group.objects.create(name='Group Two')
        self.subscription2 = Subscription.objects.create(
            user=self.user2, group=self.group2
        ) 
Example #22
Source File: test_data_objects.py    From loom with GNU Affero General Public License v3.0 5 votes vote down vote up
def TestDataObjectUpdateSerializer(TestCase):

    def testUpdateUploadStatus(self):
        file_data = fixtures.data_objects.file_data_object['value']
        data_object = DataObject.create_and_initialize_file_resource(**file_data)
        s = DataObjectSerializer(data_object,
                                 context=get_mock_context())
        s.save()

        s2 = DataObjectUpdateSerializer(data_object)
        s2.update(
            data_object, {'value': {'upload_status': 'error'}})
        self.assertEqual(s2.data['value']['upload_status'], 'error')


    def testUpdateProtectedValue(self):
        file_data = fixtures.data_objects.file_data_object['value']
        data_object = DataObject.create_and_initialize_file_resource(**file_data)
        s = DataObjectSerializer(data_object,
                                 context=get_mock_context())
        s.save()

        s2 = DataObjectUpdateSerializer(data_object)
        with self.assertRaises(ValidationError):
            s2.update(
                data_object, {'type': 'string'}) 
Example #23
Source File: test_views.py    From connect with MIT License 5 votes vote down vote up
def tearDown(self):
        """Teardown/Close Out the SubscriptionUpdateViewTest TestCase"""
        self.user.subscriptions.all().delete()
        self.user.delete()
        self.group.delete() 
Example #24
Source File: test_tasks.py    From connect with MIT License 5 votes vote down vote up
def setUp(self):
        """Setup the TestCreateRecipientNotifications TestCase"""
        self.thread = self.create_thread()
        self.message = self.thread.first_message 
Example #25
Source File: test_views.py    From connect with MIT License 5 votes vote down vote up
def setUp(self):
        """Setup the UserUpdateViewTest TestCase"""
        self.user = self.create_user(password='test')
        self.client.login(username=self.user.username, password='test') 
Example #26
Source File: test_utils_mixins.py    From connect with MIT License 5 votes vote down vote up
def setUp(self):
        """Setup the DateTimeRangeListMixinTest TestCase"""
        self.request_factory = RequestFactory() 
Example #27
Source File: test_utils_mixins.py    From connect with MIT License 5 votes vote down vote up
def setUp(self):
        """Setup the PaginateByMixinTest TestCase"""
        self.request_factory = RequestFactory() 
Example #28
Source File: test_utils_mixins.py    From connect with MIT License 5 votes vote down vote up
def setUp(self):
        """Setup the SortableListMixinTest TestCase"""
        self.request_factory = RequestFactory() 
Example #29
Source File: test_accept_terms.py    From connect with MIT License 5 votes vote down vote up
def setUp(self):
        """Setup the TestAcceptTermsAndConductMiddleware TestCase"""
        self.factory = RequestFactory()
        self.mw = AcceptTermsAndConductMiddleware() 
Example #30
Source File: test_impersonation.py    From connect with MIT License 5 votes vote down vote up
def setUp(self):
        """Setup the ImpersonationMiddlewareTest TestCase"""
        self.user = User.objects.create_user(
            username='impersonate@me.local', password='abc')
        self.admin = User.objects.create_user(
            username='admin@dj.local', password='abc')
        self.client.post(
            reverse('account_login'),
            {'login': 'admin@dj.local', 'password': 'abc'}
        )
        self.request_factory = RequestFactory()