def test_complex_aggregations_require_kwarg(self):
     with six.assertRaisesRegex(self, TypeError, 'Complex annotations require an alias'):
         Author.objects.annotate(Sum(F('age') + F('friends__age')))
     with six.assertRaisesRegex(self, TypeError, 'Complex aggregates require an alias'):
         Author.objects.aggregate(Sum('age') / Count('age'))
     with six.assertRaisesRegex(self, TypeError, 'Complex aggregates require an alias'):
         Author.objects.aggregate(Sum(1))
Example #2
0
    def test_formset_validation(self):

        class FakeFormSet(object):
            pass

        class ValidationTestInline(TabularInline):
            model = ValidationTestInlineModel
            formset = FakeFormSet

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestInline.formset' does not inherit from BaseModelFormSet.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class RealModelFormSet(BaseModelFormSet):
            pass

        class ValidationTestInline(TabularInline):
            model = ValidationTestInlineModel
            formset = RealModelFormSet

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        ValidationTestModelAdmin.validate(ValidationTestModel)
Example #3
0
 def test_does_not_exist(self):
     # Django raises an Article.DoesNotExist exception for get() if the
     # parameters don't match any object.
     six.assertRaisesRegex(
         self,
         ObjectDoesNotExist,
         "Article matching query does not exist.",
         Article.objects.get,
         id__exact=2000,
     )
     # To avoid dict-ordering related errors check only one lookup
     # in single assert.
     self.assertRaises(
         ObjectDoesNotExist,
         Article.objects.get,
         pub_date__year=2005,
         pub_date__month=8,
     )
     six.assertRaisesRegex(
         self,
         ObjectDoesNotExist,
         "Article matching query does not exist.",
         Article.objects.get,
         pub_date__week_day=6,
     )
    def test_site_profile_not_available(self):
        user = User.objects.create(username='******')

        # calling get_profile without AUTH_PROFILE_MODULE set
        del settings.AUTH_PROFILE_MODULE
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            with six.assertRaisesRegex(self, SiteProfileNotAvailable,
                    "You need to set AUTH_PROFILE_MODULE in your project"):
                user.get_profile()

        # Bad syntax in AUTH_PROFILE_MODULE:
        settings.AUTH_PROFILE_MODULE = 'foobar'
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            with six.assertRaisesRegex(self, SiteProfileNotAvailable,
                    "app_label and model_name should be separated by a dot"):
                user.get_profile()

        # module that doesn't exist
        settings.AUTH_PROFILE_MODULE = 'foo.bar'
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            with six.assertRaisesRegex(self, SiteProfileNotAvailable,
                    "Unable to load the profile model"):
                user.get_profile()
Example #5
0
    def test_dumpdata_with_pks(self):
        management.call_command("loaddata", "fixture1.json", verbosity=0)
        management.call_command("loaddata", "fixture2.json", verbosity=0)
        self._dumpdata_assert(
            ["fixtures.Article"],
            '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
            primary_keys="2,3",
        )

        self._dumpdata_assert(
            ["fixtures.Article"],
            '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}]',
            primary_keys="2",
        )

        with six.assertRaisesRegex(self, management.CommandError, "You can only use --pks option with one model"):
            self._dumpdata_assert(
                ["fixtures"],
                '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
                primary_keys="2,3",
            )

        with six.assertRaisesRegex(self, management.CommandError, "You can only use --pks option with one model"):
            self._dumpdata_assert(
                "",
                '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
                primary_keys="2,3",
            )

        with six.assertRaisesRegex(self, management.CommandError, "You can only use --pks option with one model"):
            self._dumpdata_assert(
                ["fixtures.Article", "fixtures.category"],
                '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
                primary_keys="2,3",
            )
    def test_reuse_rollback_rollback(self):
        atomic = transaction.atomic()
        with six.assertRaisesRegex(self, Exception, "Oops"):
            with atomic:
                Reporter.objects.create(last_name="Tintin")
                with six.assertRaisesRegex(self, Exception, "Oops"):
                    with atomic:
                        Reporter.objects.create(first_name="Haddock")
                    raise Exception("Oops, that's his last name")
                raise Exception("Oops, that's his first name")
        self.assertQuerysetEqual(Reporter.objects.all(), [])
        self.assertAtomicSignalCalls(
            # Enter atomic transaction block.
            enter_block_atomic_signal_call_sequence(True) +

            # Create Reporter.
            create_model_atomic_signal_call_sequence() +

            # Enter nested atomic transaction block.
            enter_block_atomic_signal_call_sequence(False) +

            # Create Reporter.
            create_model_atomic_signal_call_sequence() +

            # Leave nested atomic transaction block with caught eexception.
            leave_block_atomic_signal_call_sequence(False, True) +

            # Leave atomic transaction block with exception.
            leave_block_atomic_signal_call_sequence(True, False)
        )
Example #7
0
    def test_multivaluedict(self):
        d = MultiValueDict({'name': ['Adrian', 'Simon'],
                            'position': ['Developer']})

        self.assertEqual(d['name'], 'Simon')
        self.assertEqual(d.get('name'), 'Simon')
        self.assertEqual(d.getlist('name'), ['Adrian', 'Simon'])
        self.assertEqual(sorted(list(six.iteritems(d))),
                          [('name', 'Simon'), ('position', 'Developer')])

        self.assertEqual(sorted(list(six.iterlists(d))),
                          [('name', ['Adrian', 'Simon']),
                           ('position', ['Developer'])])

        six.assertRaisesRegex(self, MultiValueDictKeyError, 'lastname',
            d.__getitem__, 'lastname')

        self.assertEqual(d.get('lastname'), None)
        self.assertEqual(d.get('lastname', 'nonexistent'), 'nonexistent')
        self.assertEqual(d.getlist('lastname'), [])
        self.assertEqual(d.getlist('doesnotexist', ['Adrian', 'Simon']),
                         ['Adrian', 'Simon'])

        d.setlist('lastname', ['Holovaty', 'Willison'])
        self.assertEqual(d.getlist('lastname'), ['Holovaty', 'Willison'])
        self.assertEqual(sorted(list(six.itervalues(d))),
                         ['Developer', 'Simon', 'Willison'])
Example #8
0
    def test_multivaluedict(self):
        d = MultiValueDict({"name": ["Adrian", "Simon"], "position": ["Developer"]})

        self.assertEqual(d["name"], "Simon")
        self.assertEqual(d.get("name"), "Simon")
        self.assertEqual(d.getlist("name"), ["Adrian", "Simon"])
        self.assertEqual(sorted(list(six.iteritems(d))), [("name", "Simon"), ("position", "Developer")])

        self.assertEqual(sorted(list(six.iterlists(d))), [("name", ["Adrian", "Simon"]), ("position", ["Developer"])])

        # MultiValueDictKeyError: "Key 'lastname' not found in
        # <MultiValueDict: {'position': ['Developer'],
        #                   'name': ['Adrian', 'Simon']}>"
        six.assertRaisesRegex(
            self, MultiValueDictKeyError, r'"Key \'lastname\' not found in <MultiValueDict', d.__getitem__, "lastname"
        )

        self.assertEqual(d.get("lastname"), None)
        self.assertEqual(d.get("lastname", "nonexistent"), "nonexistent")
        self.assertEqual(d.getlist("lastname"), [])
        self.assertEqual(d.getlist("doesnotexist", ["Adrian", "Simon"]), ["Adrian", "Simon"])

        d.setlist("lastname", ["Holovaty", "Willison"])
        self.assertEqual(d.getlist("lastname"), ["Holovaty", "Willison"])
        self.assertEqual(sorted(list(six.itervalues(d))), ["Developer", "Simon", "Willison"])
Example #9
0
    def test_date_hierarchy_validation(self):

        class ValidationTestModelAdmin(ModelAdmin):
            date_hierarchy = 'non_existent_field'

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.date_hierarchy' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestModel'.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestModelAdmin(ModelAdmin):
            date_hierarchy = 'name'

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.date_hierarchy is neither an instance of DateField nor DateTimeField.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestModelAdmin(ModelAdmin):
            date_hierarchy = 'pub_date'

        ValidationTestModelAdmin.validate(ValidationTestModel)
Example #10
0
    def test_duplicated_permissions(self):
        """
        Test that we show proper error message if we are trying to create
        duplicate permissions.
        """
        # check duplicated default permission
        models.Permission._meta.permissions = [
           ('change_permission', 'Can edit permission (duplicate)')]
        six.assertRaisesRegex(self, CommandError,
            "The permission codename 'change_permission' clashes with a "
            "builtin permission for model 'auth.Permission'.",
            create_permissions, models, [], verbosity=0)

        # check duplicated custom permissions
        models.Permission._meta.permissions = [
            ('my_custom_permission', 'Some permission'),
            ('other_one', 'Some other permission'),
            ('my_custom_permission', 'Some permission with duplicate permission code'),
        ]
        six.assertRaisesRegex(self, CommandError,
            "The permission codename 'my_custom_permission' is duplicated for model "
            "'auth.Permission'.",
            create_permissions, models, [], verbosity=0)

        # should not raise anything
        models.Permission._meta.permissions = [
            ('my_custom_permission', 'Some permission'),
            ('other_one', 'Some other permission'),
        ]
        create_permissions(models, [], verbosity=0)
Example #11
0
    def test_fields_validation(self):

        class ValidationTestInline(TabularInline):
            model = ValidationTestInlineModel
            fields = 10

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestInline.fields' must be a list or tuple.",
            validate,
            ValidationTestModelAdmin,
            ValidationTestModel,
        )

        class ValidationTestInline(TabularInline):
            model = ValidationTestInlineModel
            fields = ("non_existent_field",)

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestInline.fields' refers to field 'non_existent_field' that is missing from the form.",
            validate,
            ValidationTestModelAdmin,
            ValidationTestModel,
        )
Example #12
0
    def test_fk_name_validation(self):

        class ValidationTestInline(TabularInline):
            model = ValidationTestInlineModel
            fk_name = "non_existent_field"

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestInline.fk_name' refers to field 'non_existent_field' that is missing from model 'modeladmin.ValidationTestInlineModel'.",
            validate,
            ValidationTestModelAdmin,
            ValidationTestModel,
        )

        class ValidationTestInline(TabularInline):
            model = ValidationTestInlineModel
            fk_name = "parent"

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        validate(ValidationTestModelAdmin, ValidationTestModel)
Example #13
0
    def test_extra_validation(self):

        class ValidationTestInline(TabularInline):
            model = ValidationTestInlineModel
            extra = "hello"

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestInline.extra' should be a integer.",
            validate,
            ValidationTestModelAdmin,
            ValidationTestModel,
        )

        class ValidationTestInline(TabularInline):
            model = ValidationTestInlineModel
            extra = 2

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        validate(ValidationTestModelAdmin, ValidationTestModel)
Example #14
0
    def test_max_num_validation(self):

        class ValidationTestInline(TabularInline):
            model = ValidationTestInlineModel
            max_num = "hello"

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestInline.max_num' should be an integer or None \(default\).",
            validate,
            ValidationTestModelAdmin,
            ValidationTestModel,
        )

        class ValidationTestInline(TabularInline):
            model = ValidationTestInlineModel
            max_num = 2

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        validate(ValidationTestModelAdmin, ValidationTestModel)
Example #15
0
 def test_broken(self):
     # Regression test for #19362.
     a = BrokenArticle.objects.create(
         headline='Girl wins €12.500 in lottery',
         pub_date=datetime.datetime(2005, 7, 28)
     )
     six.assertRaisesRegex(self, RuntimeError, "Did you apply "
         "@python_2_unicode_compatible without defining __str__\?", str, a)
Example #16
0
    def test_verbose_name_length(self):
        permission_content_type = ContentType.objects.get_by_natural_key('auth', 'permission')
        models.Permission.objects.filter(content_type=permission_content_type).delete()
        models.Permission._meta.verbose_name = "some ridiculously long verbose name that is out of control"

        six.assertRaisesRegex(self, exceptions.ValidationError,
            "The verbose_name of permission is longer than 39 characters",
            create_permissions, models, [], verbosity=0)
Example #17
0
    def test_internal_related_name_not_in_error_msg(self):
        # The secret internal related names for self-referential many-to-many
        # fields shouldn't appear in the list when an error is made.

        six.assertRaisesRegex(self, FieldError,
            "Choices are: id, name, references, related, selfreferchild, selfreferchildsibling$",
            lambda: SelfRefer.objects.filter(porcupine='fred')
        )
Example #18
0
 def test_disabled_serving(self):
     six.assertRaisesRegex(
         self,
         ImproperlyConfigured,
         "The staticfiles view " "can only be used in debug mode ",
         self._response,
         "test.txt",
     )
Example #19
0
 def test_simplelistfilter_without_parameter(self):
     """
     Any SimpleListFilter must define a parameter_name.
     """
     modeladmin = DecadeFilterBookAdminWithoutParameter(Book, site)
     request = self.request_factory.get('/', {})
     six.assertRaisesRegex(self, ImproperlyConfigured,
         "The list filter 'DecadeListFilterWithoutParameter' does not specify a 'parameter_name'.",
         self.get_changelist, request, Book, modeladmin)
Example #20
0
File: tests.py Project: 10sr/hue
 def test_non_foreign_key_field(self):
     """
     If the field specified in fk_name is not a ForeignKey, we should get an
     exception.
     """
     six.assertRaisesRegex(self, Exception,
         "<class 'inline_formsets.models.Child'> has no field named 'test'",
         inlineformset_factory, Parent, Child, fk_name='test'
     )
Example #21
0
 def test_dates_fails_when_given_invalid_field_argument(self):
     six.assertRaisesRegex(
         self,
         FieldDoesNotExist,
         "Article has no field named 'invalid_field'",
         Article.objects.dates,
         "invalid_field",
         "year",
     )
Example #22
0
 def test_nested_rollback_rollback(self):
     with six.assertRaisesRegex(self, Exception, "Oops"), transaction.atomic():
         Reporter.objects.create(last_name="Tintin")
         with six.assertRaisesRegex(self, Exception, "Oops"):
             with transaction.atomic():
                 Reporter.objects.create(first_name="Haddock")
             raise Exception("Oops, that's his last name")
         raise Exception("Oops, that's his first name")
     self.assertQuerysetEqual(Reporter.objects.all(), [])
Example #23
0
 def test_listfilter_without_title(self):
     """
     Any filter must define a title.
     """
     modeladmin = DecadeFilterBookAdminWithoutTitle(Book, site)
     request = self.request_factory.get('/', {})
     six.assertRaisesRegex(self, ImproperlyConfigured,
         "The list filter 'DecadeListFilterWithoutTitle' does not specify a 'title'.",
         self.get_changelist, request, Book, modeladmin)
Example #24
0
 def test_dates_fails_when_given_invalid_kind_argument(self):
     six.assertRaisesRegex(
         self,
         AssertionError,
         "'kind' must be one of 'year', 'month' or 'day'.",
         Article.objects.dates,
         "pub_date",
         "bad_kind",
     )
Example #25
0
File: tests.py Project: 10sr/hue
 def test_exception_on_unspecified_foreign_key(self):
     """
     Child has two ForeignKeys to Parent, so if we don't specify which one
     to use for the inline formset, we should get an exception.
     """
     six.assertRaisesRegex(self, Exception,
         "<class 'inline_formsets.models.Child'> has more than 1 ForeignKey to <class 'inline_formsets.models.Parent'>",
         inlineformset_factory, Parent, Child
     )
Example #26
0
    def test_verbose_name_length(self):
        auth_app_config = apps.get_app_config('auth')

        permission_content_type = ContentType.objects.get_by_natural_key('auth', 'permission')
        Permission.objects.filter(content_type=permission_content_type).delete()
        Permission._meta.verbose_name = "some ridiculously long verbose name that is out of control" * 5

        six.assertRaisesRegex(self, exceptions.ValidationError,
            "The verbose_name of auth.permission is longer than 244 characters",
            create_permissions, auth_app_config, verbosity=0)
Example #27
0
 def test_view_loading(self):
     # A missing view (identified by an AttributeError) should raise
     # ViewDoesNotExist, ...
     six.assertRaisesRegex(self, ViewDoesNotExist, ".*View does not exist in.*",
         get_callable,
         'urlpatterns_reverse.views.i_should_not_exist')
     # ... but if the AttributeError is caused by something else don't
     # swallow it.
     self.assertRaises(AttributeError, get_callable,
         'urlpatterns_reverse.views_broken.i_am_broken')
Example #28
0
 def test_dates_fails_when_given_invalid_order_argument(self):
     six.assertRaisesRegex(
         self,
         AssertionError,
         "'order' must be either 'ASC' or 'DESC'.",
         Article.objects.dates,
         "pub_date",
         "year",
         order="bad order",
     )
Example #29
0
 def test_dates_fails_when_given_invalid_field_argument(self):
     six.assertRaisesRegex(
         self,
         FieldError,
         "Cannot resolve keyword u?'invalid_field' into field. Choices are: "
         "categories, comments, id, pub_date, title",
         Article.objects.dates,
         "invalid_field",
         "year",
     )
Example #30
0
 def test_cannot_create_instance_with_invalid_kwargs(self):
     six.assertRaisesRegex(
         self,
         TypeError,
         "'foo' is an invalid keyword argument for this function",
         Article,
         id=None,
         headline='Some headline',
         pub_date=datetime(2005, 7, 31),
         foo='bar',
     )
Example #31
0
 def test_compile_filter_error(self):
     # regression test for #19819
     msg = "Could not parse the remainder: '@bar' from 'foo@bar'"
     with six.assertRaisesRegex(self, TemplateSyntaxError, msg) as cm:
         Template("{% if 1 %}{{ foo@bar }}{% endif %}")
     self.assertEqual(cm.exception.django_template_source[1], (10, 23))
Example #32
0
 def test_select_templates_from_empty_list(self):
     six.assertRaisesRegex(self, TemplateDoesNotExist,
         'No template names provided$',
         loader.select_template, [])
Example #33
0
 def test_empty_list(self):
     six.assertRaisesRegex(self, TemplateDoesNotExist,
         'No template names provided$',
         loader.render_to_string, [])
Example #34
0
 def test_serialize(self):
     """
     Tests various different forms of the serializer.
     This does not care about formatting, just that the parsed result is
     correct, so we always exec() the result and check that.
     """
     # Basic values
     self.assertSerializedEqual(1)
     self.assertSerializedEqual(None)
     self.assertSerializedEqual(b"foobar")
     string, imports = MigrationWriter.serialize(b"foobar")
     self.assertEqual(string, "b'foobar'")
     self.assertSerializedEqual("föobár")
     string, imports = MigrationWriter.serialize("foobar")
     self.assertEqual(string, "'foobar'")
     self.assertSerializedEqual({1: 2})
     self.assertSerializedEqual(["a", 2, True, None])
     self.assertSerializedEqual(set([2, 3, "eighty"]))
     self.assertSerializedEqual({"lalalala": ["yeah", "no", "maybe"]})
     self.assertSerializedEqual(_('Hello'))
     # Functions
     with six.assertRaisesRegex(self, ValueError,
                                'Cannot serialize function: lambda'):
         self.assertSerializedEqual(lambda x: 42)
     self.assertSerializedEqual(models.SET_NULL)
     string, imports = MigrationWriter.serialize(models.SET(42))
     self.assertEqual(string, 'models.SET(42)')
     self.serialize_round_trip(models.SET(42))
     # Datetime stuff
     self.assertSerializedEqual(datetime.datetime.utcnow())
     self.assertSerializedEqual(datetime.datetime.utcnow)
     self.assertSerializedEqual(datetime.datetime.today())
     self.assertSerializedEqual(datetime.datetime.today)
     self.assertSerializedEqual(datetime.date.today())
     self.assertSerializedEqual(datetime.date.today)
     self.assertSerializedEqual(datetime.datetime.now().time())
     with self.assertRaises(ValueError):
         self.assertSerializedEqual(
             datetime.datetime(2012,
                               1,
                               1,
                               1,
                               1,
                               tzinfo=get_default_timezone()))
     safe_date = datetime_safe.date(2014, 3, 31)
     string, imports = MigrationWriter.serialize(safe_date)
     self.assertEqual(string, repr(datetime.date(2014, 3, 31)))
     self.assertEqual(imports, {'import datetime'})
     safe_datetime = datetime_safe.datetime(2014, 3, 31, 16, 4, 31)
     string, imports = MigrationWriter.serialize(safe_datetime)
     self.assertEqual(string,
                      repr(datetime.datetime(2014, 3, 31, 16, 4, 31)))
     self.assertEqual(imports, {'import datetime'})
     # Django fields
     self.assertSerializedFieldEqual(models.CharField(max_length=255))
     self.assertSerializedFieldEqual(models.TextField(null=True,
                                                      blank=True))
     # Setting references
     self.assertSerializedEqual(
         SettingsReference(settings.AUTH_USER_MODEL, "AUTH_USER_MODEL"))
     self.assertSerializedResultEqual(
         SettingsReference("someapp.model", "AUTH_USER_MODEL"), (
             "settings.AUTH_USER_MODEL",
             set(["from django.conf import settings"]),
         ))
     self.assertSerializedResultEqual(((x, x * x) for x in range(3)), (
         "((0, 0), (1, 1), (2, 4))",
         set(),
     ))
Example #35
0
 def test_annotated_aggregate_over_annotated_aggregate(self):
     with six.assertRaisesRegex(
             self, FieldError,
             "Cannot compute Sum\('id__max'\): 'id__max' is an aggregate"):
         Book.objects.annotate(Max('id')).annotate(Sum('id__max'))
Example #36
0
 def test_rollback(self):
     with six.assertRaisesRegex(self, Exception, "Oops"):
         with transaction.atomic():
             Reporter.objects.create(first_name="Haddock")
             raise Exception("Oops, that's his last name")
     self.assertQuerysetEqual(Reporter.objects.all(), [])
Example #37
0
 def test_missing_output_field_raises_error(self):
     with six.assertRaisesRegex(self, FieldError, 'Cannot resolve expression type, unknown output_field'):
         Book.objects.annotate(val=Max(2)).first()
Example #38
0
 def test_no_models(self):
     with six.assertRaisesRegex(
             self, ImproperlyConfigured,
             'App with label no_models is missing a models.py module.'):
         get_app('no_models')
Example #39
0
    def test_inclusion_tags(self):
        c = template.Context({'value': 42})

        t = template.Template('{% load inclusion %}{% inclusion_no_params %}')
        self.assertEqual(t.render(c),
                         'inclusion_no_params - Expected result\n')

        t = template.Template(
            '{% load inclusion %}{% inclusion_one_param 37 %}')
        self.assertEqual(t.render(c),
                         'inclusion_one_param - Expected result: 37\n')

        t = template.Template(
            '{% load inclusion %}{% inclusion_explicit_no_context 37 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_explicit_no_context - Expected result: 37\n')

        t = template.Template(
            '{% load inclusion %}{% inclusion_no_params_with_context %}')
        self.assertEqual(
            t.render(c),
            'inclusion_no_params_with_context - Expected result (context value: 42)\n'
        )

        t = template.Template(
            '{% load inclusion %}{% inclusion_params_and_context 37 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_params_and_context - Expected result (context value: 42): 37\n'
        )

        t = template.Template(
            '{% load inclusion %}{% inclusion_two_params 37 42 %}')
        self.assertEqual(t.render(c),
                         'inclusion_two_params - Expected result: 37, 42\n')

        t = template.Template(
            '{% load inclusion %}{% inclusion_one_default 37 %}')
        self.assertEqual(t.render(c),
                         'inclusion_one_default - Expected result: 37, hi\n')

        t = template.Template(
            '{% load inclusion %}{% inclusion_one_default 37 two="hello" %}')
        self.assertEqual(
            t.render(c),
            'inclusion_one_default - Expected result: 37, hello\n')

        t = template.Template(
            '{% load inclusion %}{% inclusion_one_default one=99 two="hello" %}'
        )
        self.assertEqual(
            t.render(c),
            'inclusion_one_default - Expected result: 99, hello\n')

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_one_default' received unexpected keyword argument 'three'",
            template.Template,
            '{% load inclusion %}{% inclusion_one_default 99 two="hello" three="foo" %}'
        )

        t = template.Template(
            '{% load inclusion %}{% inclusion_one_default 37 42 %}')
        self.assertEqual(t.render(c),
                         'inclusion_one_default - Expected result: 37, 42\n')

        t = template.Template(
            '{% load inclusion %}{% inclusion_unlimited_args 37 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_unlimited_args - Expected result: 37, hi\n')

        t = template.Template(
            '{% load inclusion %}{% inclusion_unlimited_args 37 42 56 89 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_unlimited_args - Expected result: 37, 42, 56, 89\n')

        t = template.Template(
            '{% load inclusion %}{% inclusion_only_unlimited_args %}')
        self.assertEqual(
            t.render(c), 'inclusion_only_unlimited_args - Expected result: \n')

        t = template.Template(
            '{% load inclusion %}{% inclusion_only_unlimited_args 37 42 56 89 %}'
        )
        self.assertEqual(
            t.render(c),
            'inclusion_only_unlimited_args - Expected result: 37, 42, 56, 89\n'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_two_params' received too many positional arguments",
            template.Template,
            '{% load inclusion %}{% inclusion_two_params 37 42 56 %}')

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_one_default' received too many positional arguments",
            template.Template,
            '{% load inclusion %}{% inclusion_one_default 37 42 56 %}')

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_one_default' did not receive value\(s\) for the argument\(s\): 'one'",
            template.Template,
            '{% load inclusion %}{% inclusion_one_default %}')

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_unlimited_args' did not receive value\(s\) for the argument\(s\): 'one'",
            template.Template,
            '{% load inclusion %}{% inclusion_unlimited_args %}')

        t = template.Template(
            '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}'
        )
        self.assertEqual(
            t.render(c),
            'inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4\n'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)",
            template.Template,
            '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
            template.Template,
            '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}'
        )
Example #40
0
 def test_no_locale_raises(self):
     os.chdir(self.test_dir)
     with six.assertRaisesRegex(
             self, management.CommandError,
             "Unable to find a locale path to store translations for file"):
         management.call_command('makemessages', locale=LOCALE, verbosity=0)
Example #41
0
 def test_none_not_allowed(self):
     # TaggedItem requires a content_type, initializing with None should
     # raise a ValueError.
     with six.assertRaisesRegex(self, ValueError,
       'Cannot assign None: "TaggedItem.content_type" does not allow null values'):
         TaggedItem(content_object=None)
Example #42
0
 def test_incorrect_field_expression(self):
     with six.assertRaisesRegex(self, FieldError, "Cannot resolve keyword u?'nope' into field.*"):
         list(Employee.objects.filter(firstname=F('nope')))
Example #43
0
 def test_validate_registry_keeps_intact(self):
     from .test_module import site
     with six.assertRaisesRegex(self, Exception, "Some random exception."):
         autodiscover_modules('another_bad_module', register_to=site)
     self.assertEqual(site._registry, {})
Example #44
0
    def test_simple_tags(self):
        c = template.Context({'value': 42})

        t = template.Template('{% load custom %}{% no_params %}')
        self.assertEqual(t.render(c), 'no_params - Expected result')

        t = template.Template('{% load custom %}{% one_param 37 %}')
        self.assertEqual(t.render(c), 'one_param - Expected result: 37')

        t = template.Template('{% load custom %}{% explicit_no_context 37 %}')
        self.assertEqual(t.render(c),
                         'explicit_no_context - Expected result: 37')

        t = template.Template('{% load custom %}{% no_params_with_context %}')
        self.assertEqual(
            t.render(c),
            'no_params_with_context - Expected result (context value: 42)')

        t = template.Template('{% load custom %}{% params_and_context 37 %}')
        self.assertEqual(
            t.render(c),
            'params_and_context - Expected result (context value: 42): 37')

        t = template.Template('{% load custom %}{% simple_two_params 37 42 %}')
        self.assertEqual(t.render(c),
                         'simple_two_params - Expected result: 37, 42')

        t = template.Template('{% load custom %}{% simple_one_default 37 %}')
        self.assertEqual(t.render(c),
                         'simple_one_default - Expected result: 37, hi')

        t = template.Template(
            '{% load custom %}{% simple_one_default 37 two="hello" %}')
        self.assertEqual(t.render(c),
                         'simple_one_default - Expected result: 37, hello')

        t = template.Template(
            '{% load custom %}{% simple_one_default one=99 two="hello" %}')
        self.assertEqual(t.render(c),
                         'simple_one_default - Expected result: 99, hello')

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'simple_one_default' received unexpected keyword argument 'three'",
            template.Template,
            '{% load custom %}{% simple_one_default 99 two="hello" three="foo" %}'
        )

        t = template.Template(
            '{% load custom %}{% simple_one_default 37 42 %}')
        self.assertEqual(t.render(c),
                         'simple_one_default - Expected result: 37, 42')

        t = template.Template(
            '{% load custom %}{% simple_unlimited_args 37 %}')
        self.assertEqual(t.render(c),
                         'simple_unlimited_args - Expected result: 37, hi')

        t = template.Template(
            '{% load custom %}{% simple_unlimited_args 37 42 56 89 %}')
        self.assertEqual(
            t.render(c),
            'simple_unlimited_args - Expected result: 37, 42, 56, 89')

        t = template.Template(
            '{% load custom %}{% simple_only_unlimited_args %}')
        self.assertEqual(t.render(c),
                         'simple_only_unlimited_args - Expected result: ')

        t = template.Template(
            '{% load custom %}{% simple_only_unlimited_args 37 42 56 89 %}')
        self.assertEqual(
            t.render(c),
            'simple_only_unlimited_args - Expected result: 37, 42, 56, 89')

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'simple_two_params' received too many positional arguments",
            template.Template,
            '{% load custom %}{% simple_two_params 37 42 56 %}')

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'simple_one_default' received too many positional arguments",
            template.Template,
            '{% load custom %}{% simple_one_default 37 42 56 %}')

        t = template.Template(
            '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}'
        )
        self.assertEqual(
            t.render(c),
            'simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'simple_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)",
            template.Template,
            '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'simple_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
            template.Template,
            '{% load custom %}{% simple_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}'
        )
Example #45
0
    def test_object_creation(self):
        # Create an Article.
        a = Article(
            id=None,
            headline='Area man programs in Python',
            pub_date=datetime(2005, 7, 28),
        )

        # Save it into the database. You have to call save() explicitly.
        a.save()

        # You can initialize a model instance using positional arguments,
        # which should match the field order as defined in the model.
        a2 = Article(None, 'Second article', datetime(2005, 7, 29))
        a2.save()

        self.assertNotEqual(a2.id, a.id)
        self.assertEqual(a2.headline, 'Second article')
        self.assertEqual(a2.pub_date, datetime(2005, 7, 29, 0, 0))

        # ...or, you can use keyword arguments.
        a3 = Article(
            id=None,
            headline='Third article',
            pub_date=datetime(2005, 7, 30),
        )
        a3.save()

        self.assertNotEqual(a3.id, a.id)
        self.assertNotEqual(a3.id, a2.id)
        self.assertEqual(a3.headline, 'Third article')
        self.assertEqual(a3.pub_date, datetime(2005, 7, 30, 0, 0))

        # You can also mix and match position and keyword arguments, but
        # be sure not to duplicate field information.
        a4 = Article(None, 'Fourth article', pub_date=datetime(2005, 7, 31))
        a4.save()
        self.assertEqual(a4.headline, 'Fourth article')

        # Don't use invalid keyword arguments.
        six.assertRaisesRegex(
            self,
            TypeError,
            "'foo' is an invalid keyword argument for this function",
            Article,
            id=None,
            headline='Invalid',
            pub_date=datetime(2005, 7, 31),
            foo='bar',
        )

        # You can leave off the value for an AutoField when creating an
        # object, because it'll get filled in automatically when you save().
        a5 = Article(headline='Article 6', pub_date=datetime(2005, 7, 31))
        a5.save()
        self.assertEqual(a5.headline, 'Article 6')

        # If you leave off a field with "default" set, Django will use
        # the default.
        a6 = Article(pub_date=datetime(2005, 7, 31))
        a6.save()
        self.assertEqual(a6.headline, 'Default headline')

        # For DateTimeFields, Django saves as much precision (in seconds)
        # as you give it.
        a7 = Article(
            headline='Article 7',
            pub_date=datetime(2005, 7, 31, 12, 30),
        )
        a7.save()
        self.assertEqual(
            Article.objects.get(id__exact=a7.id).pub_date,
            datetime(2005, 7, 31, 12, 30))

        a8 = Article(
            headline='Article 8',
            pub_date=datetime(2005, 7, 31, 12, 30, 45),
        )
        a8.save()
        self.assertEqual(
            Article.objects.get(id__exact=a8.id).pub_date,
            datetime(2005, 7, 31, 12, 30, 45))

        # Saving an object again doesn't create a new object -- it just saves
        # the old one.
        current_id = a8.id
        a8.save()
        self.assertEqual(a8.id, current_id)
        a8.headline = 'Updated article 8'
        a8.save()
        self.assertEqual(a8.id, current_id)

        # Check that != and == operators behave as expecte on instances
        self.assertTrue(a7 != a8)
        self.assertFalse(a7 == a8)
        self.assertEqual(a8, Article.objects.get(id__exact=a8.id))

        self.assertTrue(
            Article.objects.get(id__exact=a8.id) != Article.objects.get(
                id__exact=a7.id))
        self.assertFalse(
            Article.objects.get(id__exact=a8.id) == Article.objects.get(
                id__exact=a7.id))

        # You can use 'in' to test for membership...
        self.assertTrue(a8 in Article.objects.all())

        # ... but there will often be more efficient ways if that is all you need:
        self.assertTrue(Article.objects.filter(id=a8.id).exists())

        # datetimes() returns a list of available dates of the given scope for
        # the given field.
        self.assertQuerysetEqual(Article.objects.datetimes('pub_date', 'year'),
                                 ["datetime.datetime(2005, 1, 1, 0, 0)"])
        self.assertQuerysetEqual(
            Article.objects.datetimes('pub_date', 'month'),
            ["datetime.datetime(2005, 7, 1, 0, 0)"])
        self.assertQuerysetEqual(Article.objects.datetimes('pub_date', 'day'),
                                 [
                                     "datetime.datetime(2005, 7, 28, 0, 0)",
                                     "datetime.datetime(2005, 7, 29, 0, 0)",
                                     "datetime.datetime(2005, 7, 30, 0, 0)",
                                     "datetime.datetime(2005, 7, 31, 0, 0)"
                                 ])
        self.assertQuerysetEqual(
            Article.objects.datetimes('pub_date', 'day', order='ASC'), [
                "datetime.datetime(2005, 7, 28, 0, 0)",
                "datetime.datetime(2005, 7, 29, 0, 0)",
                "datetime.datetime(2005, 7, 30, 0, 0)",
                "datetime.datetime(2005, 7, 31, 0, 0)"
            ])
        self.assertQuerysetEqual(
            Article.objects.datetimes('pub_date', 'day', order='DESC'), [
                "datetime.datetime(2005, 7, 31, 0, 0)",
                "datetime.datetime(2005, 7, 30, 0, 0)",
                "datetime.datetime(2005, 7, 29, 0, 0)",
                "datetime.datetime(2005, 7, 28, 0, 0)"
            ])

        # datetimes() requires valid arguments.
        self.assertRaises(
            TypeError,
            Article.objects.dates,
        )

        six.assertRaisesRegex(
            self,
            FieldDoesNotExist,
            "Article has no field named 'invalid_field'",
            Article.objects.dates,
            "invalid_field",
            "year",
        )

        six.assertRaisesRegex(
            self,
            AssertionError,
            "'kind' must be one of 'year', 'month' or 'day'.",
            Article.objects.dates,
            "pub_date",
            "bad_kind",
        )

        six.assertRaisesRegex(
            self,
            AssertionError,
            "'order' must be either 'ASC' or 'DESC'.",
            Article.objects.dates,
            "pub_date",
            "year",
            order="bad order",
        )

        # Use iterator() with datetimes() to return a generator that lazily
        # requests each result one at a time, to save memory.
        dates = []
        for article in Article.objects.datetimes('pub_date',
                                                 'day',
                                                 order='DESC').iterator():
            dates.append(article)
        self.assertEqual(dates, [
            datetime(2005, 7, 31, 0, 0),
            datetime(2005, 7, 30, 0, 0),
            datetime(2005, 7, 29, 0, 0),
            datetime(2005, 7, 28, 0, 0)
        ])

        # You can combine queries with & and |.
        s1 = Article.objects.filter(id__exact=a.id)
        s2 = Article.objects.filter(id__exact=a2.id)
        self.assertQuerysetEqual(s1 | s2, [
            "<Article: Area man programs in Python>",
            "<Article: Second article>"
        ])
        self.assertQuerysetEqual(s1 & s2, [])

        # You can get the number of objects like this:
        self.assertEqual(len(Article.objects.filter(id__exact=a.id)), 1)

        # You can get items using index and slice notation.
        self.assertEqual(Article.objects.all()[0], a)
        self.assertQuerysetEqual(
            Article.objects.all()[1:3],
            ["<Article: Second article>", "<Article: Third article>"])

        s3 = Article.objects.filter(id__exact=a3.id)
        self.assertQuerysetEqual((s1 | s2 | s3)[::2], [
            "<Article: Area man programs in Python>",
            "<Article: Third article>"
        ])

        # Slicing works with longs (Python 2 only -- Python 3 doesn't have longs).
        if not six.PY3:
            self.assertEqual(Article.objects.all()[long(0)], a)
            self.assertQuerysetEqual(
                Article.objects.all()[long(1):long(3)],
                ["<Article: Second article>", "<Article: Third article>"])
            self.assertQuerysetEqual((s1 | s2 | s3)[::long(2)], [
                "<Article: Area man programs in Python>",
                "<Article: Third article>"
            ])

            # And can be mixed with ints.
            self.assertQuerysetEqual(
                Article.objects.all()[1:long(3)],
                ["<Article: Second article>", "<Article: Third article>"])

        # Slices (without step) are lazy:
        self.assertQuerysetEqual(Article.objects.all()[0:5].filter(), [
            "<Article: Area man programs in Python>",
            "<Article: Second article>", "<Article: Third article>",
            "<Article: Article 6>", "<Article: Default headline>"
        ])

        # Slicing again works:
        self.assertQuerysetEqual(Article.objects.all()[0:5][0:2], [
            "<Article: Area man programs in Python>",
            "<Article: Second article>"
        ])
        self.assertQuerysetEqual(Article.objects.all()[0:5][:2], [
            "<Article: Area man programs in Python>",
            "<Article: Second article>"
        ])
        self.assertQuerysetEqual(Article.objects.all()[0:5][4:],
                                 ["<Article: Default headline>"])
        self.assertQuerysetEqual(Article.objects.all()[0:5][5:], [])

        # Some more tests!
        self.assertQuerysetEqual(
            Article.objects.all()[2:][0:2],
            ["<Article: Third article>", "<Article: Article 6>"])
        self.assertQuerysetEqual(
            Article.objects.all()[2:][:2],
            ["<Article: Third article>", "<Article: Article 6>"])
        self.assertQuerysetEqual(Article.objects.all()[2:][2:3],
                                 ["<Article: Default headline>"])

        # Using an offset without a limit is also possible.
        self.assertQuerysetEqual(Article.objects.all()[5:], [
            "<Article: Fourth article>", "<Article: Article 7>",
            "<Article: Updated article 8>"
        ])

        # Also, once you have sliced you can't filter, re-order or combine
        six.assertRaisesRegex(
            self,
            AssertionError,
            "Cannot filter a query once a slice has been taken.",
            Article.objects.all()[0:5].filter,
            id=a.id,
        )

        six.assertRaisesRegex(
            self,
            AssertionError,
            "Cannot reorder a query once a slice has been taken.",
            Article.objects.all()[0:5].order_by,
            'id',
        )

        try:
            Article.objects.all()[0:1] & Article.objects.all()[4:5]
            self.fail('Should raise an AssertionError')
        except AssertionError as e:
            self.assertEqual(
                str(e), "Cannot combine queries once a slice has been taken.")
        except Exception as e:
            self.fail('Should raise an AssertionError, not %s' % e)

        # Negative slices are not supported, due to database constraints.
        # (hint: inverting your ordering might do what you need).
        try:
            Article.objects.all()[-1]
            self.fail('Should raise an AssertionError')
        except AssertionError as e:
            self.assertEqual(str(e), "Negative indexing is not supported.")
        except Exception as e:
            self.fail('Should raise an AssertionError, not %s' % e)

        error = None
        try:
            Article.objects.all()[0:-5]
        except Exception as e:
            error = e
        self.assertIsInstance(error, AssertionError)
        self.assertEqual(str(error), "Negative indexing is not supported.")

        # An Article instance doesn't have access to the "objects" attribute.
        # That's only available on the class.
        six.assertRaisesRegex(
            self,
            AttributeError,
            "Manager isn't accessible via Article instances",
            getattr,
            a7,
            "objects",
        )

        # Bulk delete test: How many objects before and after the delete?
        self.assertQuerysetEqual(Article.objects.all(), [
            "<Article: Area man programs in Python>",
            "<Article: Second article>", "<Article: Third article>",
            "<Article: Article 6>", "<Article: Default headline>",
            "<Article: Fourth article>", "<Article: Article 7>",
            "<Article: Updated article 8>"
        ])
        Article.objects.filter(id__lte=a4.id).delete()
        self.assertQuerysetEqual(Article.objects.all(), [
            "<Article: Article 6>", "<Article: Default headline>",
            "<Article: Article 7>", "<Article: Updated article 8>"
        ])
Example #46
0
    def test_lookup(self):
        # No articles are in the system yet.
        self.assertQuerysetEqual(Article.objects.all(), [])

        # Create an Article.
        a = Article(
            id=None,
            headline='Area man programs in Python',
            pub_date=datetime(2005, 7, 28),
        )

        # Save it into the database. You have to call save() explicitly.
        a.save()

        # Now it has an ID.
        self.assertTrue(a.id != None)

        # Models have a pk property that is an alias for the primary key
        # attribute (by default, the 'id' attribute).
        self.assertEqual(a.pk, a.id)

        # Access database columns via Python attributes.
        self.assertEqual(a.headline, 'Area man programs in Python')
        self.assertEqual(a.pub_date, datetime(2005, 7, 28, 0, 0))

        # Change values by changing the attributes, then calling save().
        a.headline = 'Area woman programs in Python'
        a.save()

        # Article.objects.all() returns all the articles in the database.
        self.assertQuerysetEqual(Article.objects.all(),
                                 ['<Article: Area woman programs in Python>'])

        # Django provides a rich database lookup API.
        self.assertEqual(Article.objects.get(id__exact=a.id), a)
        self.assertEqual(
            Article.objects.get(headline__startswith='Area woman'), a)
        self.assertEqual(Article.objects.get(pub_date__year=2005), a)
        self.assertEqual(
            Article.objects.get(pub_date__year=2005, pub_date__month=7), a)
        self.assertEqual(
            Article.objects.get(pub_date__year=2005,
                                pub_date__month=7,
                                pub_date__day=28), a)
        self.assertEqual(Article.objects.get(pub_date__week_day=5), a)

        # The "__exact" lookup type can be omitted, as a shortcut.
        self.assertEqual(Article.objects.get(id=a.id), a)
        self.assertEqual(
            Article.objects.get(headline='Area woman programs in Python'), a)

        self.assertQuerysetEqual(
            Article.objects.filter(pub_date__year=2005),
            ['<Article: Area woman programs in Python>'],
        )
        self.assertQuerysetEqual(
            Article.objects.filter(pub_date__year=2004),
            [],
        )
        self.assertQuerysetEqual(
            Article.objects.filter(pub_date__year=2005, pub_date__month=7),
            ['<Article: Area woman programs in Python>'],
        )

        self.assertQuerysetEqual(
            Article.objects.filter(pub_date__week_day=5),
            ['<Article: Area woman programs in Python>'],
        )
        self.assertQuerysetEqual(
            Article.objects.filter(pub_date__week_day=6),
            [],
        )

        # Django raises an Article.DoesNotExist exception for get() if the
        # parameters don't match any object.
        six.assertRaisesRegex(
            self,
            ObjectDoesNotExist,
            "Article matching query does not exist.",
            Article.objects.get,
            id__exact=2000,
        )
        # To avoid dict-ordering related errors check only one lookup
        # in single assert.
        self.assertRaises(
            ObjectDoesNotExist,
            Article.objects.get,
            pub_date__year=2005,
            pub_date__month=8,
        )

        six.assertRaisesRegex(
            self,
            ObjectDoesNotExist,
            "Article matching query does not exist.",
            Article.objects.get,
            pub_date__week_day=6,
        )

        # Lookup by a primary key is the most common case, so Django
        # provides a shortcut for primary-key exact lookups.
        # The following is identical to articles.get(id=a.id).
        self.assertEqual(Article.objects.get(pk=a.id), a)

        # pk can be used as a shortcut for the primary key name in any query.
        self.assertQuerysetEqual(Article.objects.filter(pk__in=[a.id]),
                                 ["<Article: Area woman programs in Python>"])

        # Model instances of the same type and same ID are considered equal.
        a = Article.objects.get(pk=a.id)
        b = Article.objects.get(pk=a.id)
        self.assertEqual(a, b)

        # Create a very similar object
        a = Article(
            id=None,
            headline='Area man programs in Python',
            pub_date=datetime(2005, 7, 28),
        )
        a.save()

        self.assertEqual(Article.objects.count(), 2)

        # Django raises an Article.MultipleObjectsReturned exception if the
        # lookup matches more than one object
        six.assertRaisesRegex(
            self,
            MultipleObjectsReturned,
            "get\(\) returned more than one Article -- it returned 2!",
            Article.objects.get,
            headline__startswith='Area',
        )

        six.assertRaisesRegex(
            self,
            MultipleObjectsReturned,
            "get\(\) returned more than one Article -- it returned 2!",
            Article.objects.get,
            pub_date__year=2005,
        )

        six.assertRaisesRegex(
            self,
            MultipleObjectsReturned,
            "get\(\) returned more than one Article -- it returned 2!",
            Article.objects.get,
            pub_date__year=2005,
            pub_date__month=7,
        )
Example #47
0
    def test_list_filter_validation(self):

        class ValidationTestModelAdmin(ModelAdmin):
            list_filter = 10

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.list_filter' must be a list or tuple.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestModelAdmin(ModelAdmin):
            list_filter = ('non_existent_field',)

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.list_filter\[0\]' refers to 'non_existent_field' which does not refer to a Field.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class RandomClass(object):
            pass

        class ValidationTestModelAdmin(ModelAdmin):
            list_filter = (RandomClass,)

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.list_filter\[0\]' is 'RandomClass' which is not a descendant of ListFilter.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestModelAdmin(ModelAdmin):
            list_filter = (('is_active', RandomClass),)

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.list_filter\[0\]\[1\]' is 'RandomClass' which is not of type FieldListFilter.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class AwesomeFilter(SimpleListFilter):
            def get_title(self):
                return 'awesomeness'
            def get_choices(self, request):
                return (('bit', 'A bit awesome'), ('very', 'Very awesome'), )
            def get_queryset(self, cl, qs):
                return qs

        class ValidationTestModelAdmin(ModelAdmin):
            list_filter = (('is_active', AwesomeFilter),)

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.list_filter\[0\]\[1\]' is 'AwesomeFilter' which is not of type FieldListFilter.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestModelAdmin(ModelAdmin):
            list_filter = (BooleanFieldListFilter,)

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.list_filter\[0\]' is 'BooleanFieldListFilter' which is of type FieldListFilter but is not associated with a field name.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        # Valid declarations below -----------

        class ValidationTestModelAdmin(ModelAdmin):
            list_filter = ('is_active', AwesomeFilter, ('is_active', BooleanFieldListFilter), 'no')

        ValidationTestModelAdmin.validate(ValidationTestModel)
Example #48
0
    def test_inlines_validation(self):

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = 10

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.inlines' must be a list or tuple.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestInline(object):
            pass

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.inlines\[0\]' does not inherit from BaseModelAdmin.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestInline(TabularInline):
            pass

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'model' is a required attribute of 'ValidationTestModelAdmin.inlines\[0\]'.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class SomethingBad(object):
            pass

        class ValidationTestInline(TabularInline):
            model = SomethingBad

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.inlines\[0\].model' does not inherit from models.Model.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestInline(TabularInline):
            model = ValidationTestInlineModel

        class ValidationTestModelAdmin(ModelAdmin):
            inlines = [ValidationTestInline]

        ValidationTestModelAdmin.validate(ValidationTestModel)
Example #49
0
 def test_duplicate_names(self):
     with six.assertRaisesRegex(self, ImproperlyConfigured, "Application names aren't unique"):
         with self.settings(INSTALLED_APPS=['apps.apps.RelabeledAppsConfig', 'apps']):
             pass
Example #50
0
 def test_nonaggregate_aggregation_throws(self):
     with six.assertRaisesRegex(self, TypeError, 'fail is not an aggregate expression'):
         Book.objects.aggregate(fail=F('price'))
Example #51
0
 def test_filter_wrong_annotation(self):
     with six.assertRaisesRegex(self, FieldError,
                                "Cannot resolve keyword .*"):
         list(
             Book.objects.annotate(sum_rating=Sum('rating')).filter(
                 sum_rating=F('nope')))
Example #52
0
 def testGetMissingCommentApp(self):
     with six.assertRaisesRegex(self, ImproperlyConfigured, 'missing_app'):
         _ = django_comments.get_comment_app()
Example #53
0
 def test_get_invalid_storage_module(self):
     """
     get_storage_class raises an error if the requested import don't exist.
     """
     with six.assertRaisesRegex(self, ImportError, "No module named '?storage'?"):
         get_storage_class('storage.NonExistingStorage')
Example #54
0
    def test_fieldsets_validation(self):

        class ValidationTestModelAdmin(ModelAdmin):
            fieldsets = 10

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.fieldsets' must be a list or tuple.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestModelAdmin(ModelAdmin):
            fieldsets = ({},)

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.fieldsets\[0\]' must be a list or tuple.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestModelAdmin(ModelAdmin):
            fieldsets = ((),)

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.fieldsets\[0\]' does not have exactly two elements.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestModelAdmin(ModelAdmin):
            fieldsets = (("General", ()),)

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'ValidationTestModelAdmin.fieldsets\[0\]\[1\]' must be a dictionary.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestModelAdmin(ModelAdmin):
            fieldsets = (("General", {}),)

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "'fields' key is required in ValidationTestModelAdmin.fieldsets\[0\]\[1\] field options dict.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestModelAdmin(ModelAdmin):
            fieldsets = (("General", {"fields": ("name",)}),)

        ValidationTestModelAdmin.validate(ValidationTestModel)

        class ValidationTestModelAdmin(ModelAdmin):
            fieldsets = (("General", {"fields": ("name",)}),)
            fields = ["name",]

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "Both fieldsets and fields are specified in ValidationTestModelAdmin.",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestModelAdmin(ModelAdmin):
            fieldsets = [(None, {'fields': ['name', 'name']})]

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "There are duplicate field\(s\) in ValidationTestModelAdmin.fieldsets",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )

        class ValidationTestModelAdmin(ModelAdmin):
            fields = ["name", "name"]

        six.assertRaisesRegex(self,
            ImproperlyConfigured,
            "There are duplicate field\(s\) in ValidationTestModelAdmin.fields",
            ValidationTestModelAdmin.validate,
            ValidationTestModel,
        )
Example #55
0
    def test_assignment_tags(self):
        c = template.Context({'value': 42})

        t = template.Template(
            '{% load custom %}{% assignment_no_params as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_no_params - Expected result')

        t = template.Template(
            '{% load custom %}{% assignment_one_param 37 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_one_param - Expected result: 37')

        t = template.Template(
            '{% load custom %}{% assignment_explicit_no_context 37 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_explicit_no_context - Expected result: 37'
        )

        t = template.Template(
            '{% load custom %}{% assignment_no_params_with_context as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_no_params_with_context - Expected result (context value: 42)'
        )

        t = template.Template(
            '{% load custom %}{% assignment_params_and_context 37 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_params_and_context - Expected result (context value: 42): 37'
        )

        t = template.Template(
            '{% load custom %}{% assignment_two_params 37 42 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_two_params - Expected result: 37, 42')

        t = template.Template(
            '{% load custom %}{% assignment_one_default 37 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_one_default - Expected result: 37, hi')

        t = template.Template(
            '{% load custom %}{% assignment_one_default 37 two="hello" as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_one_default - Expected result: 37, hello'
        )

        t = template.Template(
            '{% load custom %}{% assignment_one_default one=99 two="hello" as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_one_default - Expected result: 99, hello'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'assignment_one_default' received unexpected keyword argument 'three'",
            template.Template,
            '{% load custom %}{% assignment_one_default 99 two="hello" three="foo" as var %}'
        )

        t = template.Template(
            '{% load custom %}{% assignment_one_default 37 42 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_one_default - Expected result: 37, 42')

        t = template.Template(
            '{% load custom %}{% assignment_unlimited_args 37 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_unlimited_args - Expected result: 37, hi'
        )

        t = template.Template(
            '{% load custom %}{% assignment_unlimited_args 37 42 56 89 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_unlimited_args - Expected result: 37, 42, 56, 89'
        )

        t = template.Template(
            '{% load custom %}{% assignment_only_unlimited_args as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_only_unlimited_args - Expected result: '
        )

        t = template.Template(
            '{% load custom %}{% assignment_only_unlimited_args 37 42 56 89 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_only_unlimited_args - Expected result: 37, 42, 56, 89'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'",
            template.Template,
            '{% load custom %}{% assignment_one_param 37 %}The result is: {{ var }}'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'",
            template.Template,
            '{% load custom %}{% assignment_one_param 37 as %}The result is: {{ var }}'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'",
            template.Template,
            '{% load custom %}{% assignment_one_param 37 ass var %}The result is: {{ var }}'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'assignment_two_params' received too many positional arguments",
            template.Template,
            '{% load custom %}{% assignment_two_params 37 42 56 as var %}The result is: {{ var }}'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'assignment_one_default' received too many positional arguments",
            template.Template,
            '{% load custom %}{% assignment_one_default 37 42 56 as var %}The result is: {{ var }}'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'assignment_one_default' did not receive value\(s\) for the argument\(s\): 'one'",
            template.Template,
            '{% load custom %}{% assignment_one_default as var %}The result is: {{ var }}'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'assignment_unlimited_args' did not receive value\(s\) for the argument\(s\): 'one'",
            template.Template,
            '{% load custom %}{% assignment_unlimited_args as var %}The result is: {{ var }}'
        )

        t = template.Template(
            '{% load custom %}{% assignment_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'assignment_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)",
            template.Template,
            '{% load custom %}{% assignment_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 as var %}The result is: {{ var }}'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'assignment_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
            template.Template,
            '{% load custom %}{% assignment_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" as var %}The result is: {{ var }}'
        )
Example #56
0
 def test_without_gdal(self):
     # Without coordinate transformation, the serialization should succeed:
     serializers.serialize('geojson', City.objects.all())
     with six.assertRaisesRegex(self, serializers.base.SerializationError, '.*GDAL is not installed'):
         # Coordinate transformations need GDAL
         serializers.serialize('geojson', City.objects.all(), srid=2847)
Example #57
0
 def test_dumpdata_pyyaml_error_message(self):
     """Calling dumpdata produces an error when yaml package missing"""
     with six.assertRaisesRegex(self, management.CommandError,
                                YAML_IMPORT_ERROR_MESSAGE):
         management.call_command('dumpdata', format='yaml')
Example #58
0
    def test_serialize_class_based_validators(self):
        """
        Ticket #22943: Test serialization of class-based validators, including
        compiled regexes.
        """
        validator = RegexValidator(message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string, "django.core.validators.RegexValidator(message='hello')")
        self.serialize_round_trip(validator)

        # Test with a compiled regex.
        validator = RegexValidator(regex=re.compile(r'^\w+$', re.U))
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string,
            "django.core.validators.RegexValidator(regex=re.compile('^\\\\w+$', 32))"
        )
        self.serialize_round_trip(validator)

        # Test a string regex with flag
        validator = RegexValidator(r'^[0-9]+$', flags=re.U)
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string,
            "django.core.validators.RegexValidator('^[0-9]+$', flags=32)")
        self.serialize_round_trip(validator)

        # Test message and code
        validator = RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string,
            "django.core.validators.RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')"
        )
        self.serialize_round_trip(validator)

        # Test with a subclass.
        validator = EmailValidator(message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string, "django.core.validators.EmailValidator(message='hello')")
        self.serialize_round_trip(validator)

        validator = deconstructible(
            path="migrations.test_writer.EmailValidator")(EmailValidator)(
                message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string, "migrations.test_writer.EmailValidator(message='hello')")

        validator = deconstructible(
            path="custom.EmailValidator")(EmailValidator)(message="hello")
        with six.assertRaisesRegex(self, ImportError,
                                   "No module named '?custom'?"):
            MigrationWriter.serialize(validator)

        validator = deconstructible(
            path="django.core.validators.EmailValidator2")(EmailValidator)(
                message="hello")
        with self.assertRaisesMessage(
                ValueError,
                "Could not find object EmailValidator2 in django.core.validators."
        ):
            MigrationWriter.serialize(validator)
Example #59
0
 def test_autodiscover_modules_several_one_bad_module(self):
     with six.assertRaisesRegex(
             self, ImportError,
             "No module named '?a_package_name_that_does_not_exist'?"):
         autodiscover_modules('good_module', 'bad_module')
Example #60
0
 def test_disabled_serving(self):
     six.assertRaisesRegex(self, ImproperlyConfigured, 'The staticfiles view '
         'can only be used in debug mode ', self._response, 'test.txt')