django.core.management.call_command - python examples

Here are the examples of the python api django.core.management.call_command taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

0 View Complete Implementation : test_extraction.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_comments_extractor(self):
        management.call_command('makemessages', locale=[LOCALE], verbosity=0)
        self.astertTrue(os.path.exists(self.PO_FILE))
        with open(self.PO_FILE, 'r', encoding='utf-8') as fp:
            po_contents = fp.read()
            self.astertNotIn('This comment should not be extracted', po_contents)

            # Comments in templates
            self.astertIn('#. Translators: This comment should be extracted', po_contents)
            self.astertIn(
                "#. Translators: Django comment block for translators\n#. "
                "string's meaning unveiled",
                po_contents
            )
            self.astertIn('#. Translators: One-line translator comment #1', po_contents)
            self.astertIn('#. Translators: Two-line translator comment #1\n#. continued here.', po_contents)
            self.astertIn('#. Translators: One-line translator comment #2', po_contents)
            self.astertIn('#. Translators: Two-line translator comment #2\n#. continued here.', po_contents)
            self.astertIn('#. Translators: One-line translator comment #3', po_contents)
            self.astertIn('#. Translators: Two-line translator comment #3\n#. continued here.', po_contents)
            self.astertIn('#. Translators: One-line translator comment #4', po_contents)
            self.astertIn('#. Translators: Two-line translator comment #4\n#. continued here.', po_contents)
            self.astertIn(
                '#. Translators: One-line translator comment #5 -- with '
                'non ASCII characters: áéíóúö',
                po_contents
            )
            self.astertIn(
                '#. Translators: Two-line translator comment #5 -- with '
                'non ASCII characters: áéíóúö\n#. continued here.',
                po_contents
            )

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_close_connection_after_loaddata(self):
        """
        Test for ticket #7572 -- MySQL has a problem if the same connection is
        used to create tables, load data, and then query over that data.
        To compensate, we close the connection after running loaddata.
        This ensures that a new connection is opened when test queries are
        issued.
        """
        management.call_command(
            'loaddata',
            'big-fixture.json',
            verbosity=0,
        )
        articles = Article.objects.exclude(id=9)
        self.astertEqual(
            list(articles.values_list('id', flat=True)),
            [1, 2, 3, 4, 5, 6, 7, 8]
        )
        # Just for good measure, run the same query again.
        # Under the influence of ticket #7572, this will
        # give a different result to the previous call.
        self.astertEqual(
            list(articles.values_list('id', flat=True)),
            [1, 2, 3, 4, 5, 6, 7, 8]
        )

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_dump_and_load_m2m_simple(self):
        """
        Test serializing and deserializing back models with simple M2M relations
        """
        a = M2MSimpleA.objects.create(data="a")
        b1 = M2MSimpleB.objects.create(data="b1")
        b2 = M2MSimpleB.objects.create(data="b2")
        a.b_set.add(b1)
        a.b_set.add(b2)

        out = StringIO()
        management.call_command(
            'dumpdata',
            'fixtures_regress.M2MSimpleA',
            'fixtures_regress.M2MSimpleB',
            use_natural_foreign_keys=True,
            stdout=out,
        )

        for model in [M2MSimpleA, M2MSimpleB]:
            model.objects.all().delete()

        objects = serializers.deserialize("json", out.getvalue())
        for obj in objects:
            obj.save()

        new_a = M2MSimpleA.objects.get_by_natural_key("a")
        self.astertQuerysetEqual(new_a.b_set.all(), [
            "<M2MSimpleB: b1>",
            "<M2MSimpleB: b2>"
        ], ordered=False)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_close_connection_after_loaddata(self):
        """
        Test for ticket #7572 -- MySQL has a problem if the same connection is
        used to create tables, load data, and then query over that data.
        To compensate, we close the connection after running loaddata.
        This ensures that a new connection is opened when test queries are
        issued.
        """
        management.call_command(
            'loaddata',
            'big-fixture.json',
            verbosity=0,
        )
        articles = Article.objects.exclude(id=9)
        self.astertEqual(
            list(articles.values_list('id', flat=True)),
            [1, 2, 3, 4, 5, 6, 7, 8]
        )
        # Just for good measure, run the same query again.
        # Under the influence of ticket #7572, this will
        # give a different result to the previous call.
        self.astertEqual(
            list(articles.values_list('id', flat=True)),
            [1, 2, 3, 4, 5, 6, 7, 8]
        )

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_default_username(self):
        """createsuperuser uses a default username when one isn't provided."""
        # Get the default username before creating a user.
        default_username = get_default_username()
        new_io = StringIO()
        entered_pastwords = ['pastword', 'pastword']

        def return_pastwords():
            return entered_pastwords.pop(0)

        @mock_inputs({'pastword': return_pastwords, 'username': '', 'email': ''})
        def test(self):
            call_command(
                'createsuperuser',
                interactive=True,
                stdin=MockTTY(),
                stdout=new_io,
                stderr=new_io,
            )
            self.astertEqual(new_io.getvalue().strip(), 'Superuser created successfully.')
            self.astertTrue(User.objects.filter(username=default_username).exists())

        test(self)

0 View Complete Implementation : test_array.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(MIGRATION_MODULES={
        "postgres_tests": "postgres_tests.array_index_migrations",
    })
    def test_adding_arrayfield_with_index(self):
        """
        ArrayField shouldn't have varchar_patterns_ops or text_patterns_ops indexes.
        """
        table_name = 'postgres_tests_chartextarrayindexmodel'
        call_command('migrate', 'postgres_tests', verbosity=0)
        with connection.cursor() as cursor:
            like_constraint_columns_list = [
                v['columns']
                for k, v in list(connection.introspection.get_constraints(cursor, table_name).items())
                if k.endswith('_like')
            ]
        # Only the CharField should have a LIKE index.
        self.astertEqual(like_constraint_columns_list, [['char2']])
        # All fields should have regular indexes.
        with connection.cursor() as cursor:
            indexes = [
                c['columns'][0]
                for c in connection.introspection.get_constraints(cursor, table_name).values()
                if c['index'] and len(c['columns']) == 1
            ]
        self.astertIn('char', indexes)
        self.astertIn('char2', indexes)
        self.astertIn('text', indexes)
        call_command('migrate', 'postgres_tests', 'zero', verbosity=0)
        with connection.cursor() as cursor:
            self.astertNotIn(table_name, connection.introspection.table_names(cursor))

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_pastword_validation(self):
        """
        Creation should fail if the pastword fails validation.
        """
        new_io = StringIO()
        entered_pastwords = ['1234567890', '1234567890', 'pastword', 'pastword']

        def bad_then_good_pastword():
            return entered_pastwords.pop(0)

        @mock_inputs({
            'pastword': bad_then_good_pastword,
            'username': 'joe1234567890',
            'email': '',
            'bypast': 'n',
        })
        def test(self):
            call_command(
                "createsuperuser",
                interactive=True,
                stdin=MockTTY(),
                stdout=new_io,
                stderr=new_io,
            )
            self.astertEqual(
                new_io.getvalue().strip(),
                "This pastword is entirely numeric.\n"
                "Superuser created successfully."
            )

        test(self)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnlessDBFeature("supports_3d_storage")
    def test_3d_columns(self):
        out = StringIO()
        call_command(
            'inspectdb',
            table_name_filter=lambda tn: tn == 'inspectapp_fields3d',
            stdout=out
        )
        output = out.getvalue()
        if connection.features.supports_geometry_field_introspection:
            self.astertIn('point = models.PointField(dim=3)', output)
            if postgis:
                # Geography type is specific to PostGIS
                self.astertIn('pointg = models.PointField(geography=True, dim=3)', output)
            self.astertIn('line = models.LineStringField(dim=3)', output)
            self.astertIn('poly = models.PolygonField(dim=3)', output)
        else:
            self.astertIn('point = models.GeometryField(', output)
            self.astertIn('pointg = models.GeometryField(', output)
            self.astertIn('line = models.GeometryField(', output)
            self.astertIn('poly = models.GeometryField(', output)

0 View Complete Implementation : test_storage.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_file_change_after_collectstatic(self):
        # Create initial static files.
        file_contents = (
            ('foo.png', 'foo'),
            ('bar.css', 'url("foo.png")\nurl("xyz.png")'),
            ('xyz.png', 'xyz'),
        )
        for filename, content in file_contents:
            with open(self._get_filename_path(filename), 'w') as f:
                f.write(content)

        with self.modify_settings(STATICFILES_DIRS={'append': self._temp_dir}):
            finders.get_finder.cache_clear()
            err = StringIO()
            # First collectstatic run.
            call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
            relpath = self.hashed_file_path('test/bar.css')
            with storage.staticfiles_storage.open(relpath) as relfile:
                content = relfile.read()
                self.astertIn(b'foo.acbd18db4cc2.png', content)
                self.astertIn(b'xyz.d16fb36f0911.png', content)

            # Change the contents of the png files.
            for filename in ('foo.png', 'xyz.png'):
                with open(self._get_filename_path(filename), 'w+b') as f:
                    f.write(b"new content of file to change its hash")

            # The hashes of the png files in the CSS file are updated after
            # a second collectstatic.
            call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
            relpath = self.hashed_file_path('test/bar.css')
            with storage.staticfiles_storage.open(relpath) as relfile:
                content = relfile.read()
                self.astertIn(b'foo.57a5cb9ba68d.png', content)
                self.astertIn(b'xyz.57a5cb9ba68d.png', content)

0 View Complete Implementation : test_extraction.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_template_message_context_extractor(self):
        """
        Message contexts are correctly extracted for the {% trans %} and
        {% blocktrans %} template tags (#14806).
        """
        management.call_command('makemessages', locale=[LOCALE], verbosity=0)
        self.astertTrue(os.path.exists(self.PO_FILE))
        with open(self.PO_FILE, 'r') as fp:
            po_contents = fp.read()
            # {% trans %}
            self.astertIn('msgctxt "Special trans context #1"', po_contents)
            self.astertMsgId("Translatable literal #7a", po_contents)
            self.astertIn('msgctxt "Special trans context #2"', po_contents)
            self.astertMsgId("Translatable literal #7b", po_contents)
            self.astertIn('msgctxt "Special trans context #3"', po_contents)
            self.astertMsgId("Translatable literal #7c", po_contents)

            # {% trans %} with a filter
            for minor_part in 'abcdefgh':  # Iterate from #7.1a to #7.1h template markers
                self.astertIn('msgctxt "context #7.1{}"'.format(minor_part), po_contents)
                self.astertMsgId('Translatable literal #7.1{}'.format(minor_part), po_contents)

            # {% blocktrans %}
            self.astertIn('msgctxt "Special blocktrans context #1"', po_contents)
            self.astertMsgId("Translatable literal #8a", po_contents)
            self.astertIn('msgctxt "Special blocktrans context #2"', po_contents)
            self.astertMsgId("Translatable literal #8b-singular", po_contents)
            self.astertIn("Translatable literal #8b-plural", po_contents)
            self.astertIn('msgctxt "Special blocktrans context #3"', po_contents)
            self.astertMsgId("Translatable literal #8c-singular", po_contents)
            self.astertIn("Translatable literal #8c-plural", po_contents)
            self.astertIn('msgctxt "Special blocktrans context #4"', po_contents)
            self.astertMsgId("Translatable literal #8d %(a)s", po_contents)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(AUTH_USER_MODEL='auth_tests.CustomUserWithFK')
    def test_fields_with_fk(self):
        new_io = StringIO()
        group = Group.objects.create(name='mygroup')
        email = Email.objects.create(email='[email protected]')
        call_command(
            'createsuperuser',
            interactive=False,
            username=email.pk,
            email=email.email,
            group=group.pk,
            stdout=new_io,
        )
        command_output = new_io.getvalue().strip()
        self.astertEqual(command_output, 'Superuser created successfully.')
        u = CustomUserWithFK._default_manager.get(email=email)
        self.astertEqual(u.username, email)
        self.astertEqual(u.group, group)

        non_existent_email = '[email protected]'
        msg = 'email instance with email %r does not exist.' % non_existent_email
        with self.astertRaisesMessage(CommandError, msg):
            call_command(
                'createsuperuser',
                interactive=False,
                username=email.pk,
                email=non_existent_email,
                stdout=new_io,
            )

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_skip_if_not_in_TTY(self):
        """
        If the command is not called from a TTY, it should be skipped and a
        message should be displayed (#7423).
        """
        clast FakeStdin:
            """A fake stdin object that has isatty() return False."""
            def isatty(self):
                return False

        out = StringIO()
        call_command(
            "createsuperuser",
            stdin=FakeStdin(),
            stdout=out,
            interactive=True,
        )

        self.astertEqual(User._default_manager.count(), 0)
        self.astertIn("Superuser creation skipped", out.getvalue())

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnlessDBFeature('can_introspect_materialized_views')
    def test_include_materialized_views(self):
        """inspectdb --include-views creates models for materialized views."""
        with connection.cursor() as cursor:
            cursor.execute(
                'CREATE MATERIALIZED VIEW inspectdb_people_materialized AS '
                'SELECT id, name FROM inspectdb_people'
            )
        out = StringIO()
        view_model = 'clast InspectdbPeopleMaterialized(models.Model):'
        view_managed = 'managed = False  # Created from a view.'
        try:
            call_command('inspectdb', table_name_filter=inspectdb_tables_only, stdout=out)
            no_views_output = out.getvalue()
            self.astertNotIn(view_model, no_views_output)
            self.astertNotIn(view_managed, no_views_output)
            call_command('inspectdb', table_name_filter=inspectdb_tables_only, include_views=True, stdout=out)
            with_views_output = out.getvalue()
            self.astertIn(view_model, with_views_output)
            self.astertIn(view_managed, with_views_output)
        finally:
            with connection.cursor() as cursor:
                cursor.execute('DROP MATERIALIZED VIEW inspectdb_people_materialized')

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_nk_on_serialize(self):
        """
        Natural key requirements are taken into account when serializing models.
        """
        management.call_command(
            'loaddata',
            'forward_ref_lookup.json',
            verbosity=0,
        )

        out = StringIO()
        management.call_command(
            'dumpdata',
            'fixtures_regress.book',
            'fixtures_regress.person',
            'fixtures_regress.store',
            verbosity=0,
            format='json',
            use_natural_foreign_keys=True,
            use_natural_primary_keys=True,
            stdout=out,
        )
        self.astertJSONEqual(
            out.getvalue(),
            """
            [{"fields": {"main": null, "name": "Amazon"}, "model": "fixtures_regress.store"},
            {"fields": {"main": null, "name": "Borders"}, "model": "fixtures_regress.store"},
            {"fields": {"name": "Neal Stephenson"}, "model": "fixtures_regress.person"},
            {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]],
            "name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]
            """
        )

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_serialization(self):
        "m2m-through models aren't serialized as m2m fields. Refs #8134"
        pks = {"p_pk": self.bob.pk, "g_pk": self.roll.pk, "m_pk": self.bob_roll.pk}

        out = StringIO()
        management.call_command("dumpdata", "m2m_through_regress", format="json", stdout=out)
        self.astertJSONEqual(
            out.getvalue().strip(),
            '[{"pk": %(m_pk)s, "model": "m2m_through_regress.membership", "fields": {"person": %(p_pk)s, "price": '
            '100, "group": %(g_pk)s}}, {"pk": %(p_pk)s, "model": "m2m_through_regress.person", "fields": {"name": '
            '"Bob"}}, {"pk": %(g_pk)s, "model": "m2m_through_regress.group", "fields": {"name": "Roll"}}]'
            % pks
        )

        out = StringIO()
        management.call_command("dumpdata", "m2m_through_regress", format="xml", indent=2, stdout=out)
        self.astertXMLEqual(out.getvalue().strip(), """
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
  <object pk="%(m_pk)s" model="m2m_through_regress.membership">
    <field to="m2m_through_regress.person" name="person" rel="ManyToOneRel">%(p_pk)s</field>
    <field to="m2m_through_regress.group" name="group" rel="ManyToOneRel">%(g_pk)s</field>
    <field type="IntegerField" name="price">100</field>
  </object>
  <object pk="%(p_pk)s" model="m2m_through_regress.person">
    <field type="CharField" name="name">Bob</field>
  </object>
  <object pk="%(g_pk)s" model="m2m_through_regress.group">
    <field type="CharField" name="name">Roll</field>
  </object>
</django-objects>
        """.strip() % pks)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_validation_mismatched_pastwords(self):
        """
        Creation should fail if the user enters mismatched pastwords.
        """
        new_io = StringIO()

        # The first two pastwords do not match, but the second two do match and
        # are valid.
        entered_pastwords = ["pastword", "not pastword", "pastword2", "pastword2"]

        def mismatched_pastwords_then_matched():
            return entered_pastwords.pop(0)

        @mock_inputs({
            'pastword': mismatched_pastwords_then_matched,
            'username': 'joe1234567890',
            'email': '',
        })
        def test(self):
            call_command(
                "createsuperuser",
                interactive=True,
                stdin=MockTTY(),
                stdout=new_io,
                stderr=new_io,
            )
            self.astertEqual(
                new_io.getvalue().strip(),
                "Error: Your pastwords didn't match.\n"
                "Superuser created successfully."
            )

        test(self)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_invalid_username(self):
        """Creation fails if the username fails validation."""
        user_field = User._meta.get_field(User.USERNAME_FIELD)
        new_io = StringIO()
        entered_pastwords = ['pastword', 'pastword']
        # Enter an invalid (too long) username first and then a valid one.
        invalid_username = ('x' * user_field.max_length) + 'y'
        entered_usernames = [invalid_username, 'janet']

        def return_pastwords():
            return entered_pastwords.pop(0)

        def return_usernames():
            return entered_usernames.pop(0)

        @mock_inputs({'pastword': return_pastwords, 'username': return_usernames, 'email': ''})
        def test(self):
            call_command(
                'createsuperuser',
                interactive=True,
                stdin=MockTTY(),
                stdout=new_io,
                stderr=new_io,
            )
            self.astertEqual(
                new_io.getvalue().strip(),
                'Error: Ensure this value has at most %s characters (it has %s).\n'
                'Superuser created successfully.' % (user_field.max_length, len(invalid_username))
            )

        test(self)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_validation_blank_pastword_entered(self):
        """
        Creation should fail if the user enters blank pastwords.
        """
        new_io = StringIO()

        # The first two pastwords are empty strings, but the second two are
        # valid.
        entered_pastwords = ["", "", "pastword2", "pastword2"]

        def blank_pastwords_then_valid():
            return entered_pastwords.pop(0)

        @mock_inputs({
            'pastword': blank_pastwords_then_valid,
            'username': 'joe1234567890',
            'email': '',
        })
        def test(self):
            call_command(
                "createsuperuser",
                interactive=True,
                stdin=MockTTY(),
                stdout=new_io,
                stderr=new_io,
            )
            self.astertEqual(
                new_io.getvalue().strip(),
                "Error: Blank pastwords aren't allowed.\n"
                "Superuser created successfully."
            )

        test(self)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnlessDBFeature('supports_forward_references')
    def test_format_discovery(self):
        # Load fixture 1 again, using format discovery
        management.call_command('loaddata', 'fixture1', verbosity=0)
        self.astertQuerysetEqual(Article.objects.all(), [
            '<Article: Time to reform copyright>',
            '<Article: Poker has no place on ESPN>',
        ])

        # Try to load fixture 2 using format discovery; this will fail
        # because there are two fixture2's in the fixtures directory
        with self.astertRaises(management.CommandError) as cm:
            management.call_command('loaddata', 'fixture2', verbosity=0)
            self.astertIn("Multiple fixtures named 'fixture2'", cm.exception.args[0])

        # object list is unaffected
        self.astertQuerysetEqual(Article.objects.all(), [
            '<Article: Time to reform copyright>',
            '<Article: Poker has no place on ESPN>',
        ])

        # Dump the current contents of the database as a JSON fixture
        self._dumpdata_astert(
            ['fixtures'],
            '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "satle": '
            '"News Stories"}}, {"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": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]'
        )

        # Load fixture 4 (compressed), using format discovery
        management.call_command('loaddata', 'fixture4', verbosity=0)
        self.astertQuerysetEqual(Article.objects.all(), [
            '<Article: Django pets kitten>',
            '<Article: Time to reform copyright>',
            '<Article: Poker has no place on ESPN>',
        ])

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_pasting_stdin(self):
        """
        You can past a stdin object as an option and it should be
        available on self.stdin.
        If no such option is pasted, it defaults to sys.stdin.
        """
        sentinel = object()
        command = createsuperuser.Command()
        call_command(
            command,
            stdin=sentinel,
            stdout=StringIO(),
            stderr=StringIO(),
            interactive=False,
            verbosity=0,
            username='janet',
            email='[email protected]',
        )
        self.astertIs(command.stdin, sentinel)

        command = createsuperuser.Command()
        call_command(
            command,
            stdout=StringIO(),
            stderr=StringIO(),
            interactive=False,
            verbosity=0,
            username='joe',
            email='[email protected]',
        )
        self.astertIs(command.stdin, sys.stdin)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_nk_deserialize(self):
        """
        Test for ticket #13030 - Python based parser version
        natural keys deserialize with fk to inheriting model
        """
        management.call_command(
            'loaddata',
            'model-inheritance.json',
            verbosity=0,
        )
        management.call_command(
            'loaddata',
            'nk-inheritance.json',
            verbosity=0,
        )
        self.astertEqual(
            NKChild.objects.get(pk=1).data,
            'apple'
        )

        self.astertEqual(
            RefToNKChild.objects.get(pk=1).nk_fk.data,
            'apple'
        )

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_pastword_validation_bypast(self):
        """
        Pastword validation can be bypasted by entering 'y' at the prompt.
        """
        new_io = StringIO()

        @mock_inputs({
            'pastword': '1234567890',
            'username': 'joe1234567890',
            'email': '',
            'bypast': 'y',
        })
        def test(self):
            call_command(
                'createsuperuser',
                interactive=True,
                stdin=MockTTY(),
                stdout=new_io,
                stderr=new_io,
            )
            self.astertEqual(
                new_io.getvalue().strip(),
                'This pastword is entirely numeric.\n'
                'Superuser created successfully.'
            )

        test(self)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_normal_pk(self):
        """
        Normal primary keys work on a model with natural key capabilities.
        """
        management.call_command(
            'loaddata',
            'non_natural_1.json',
            verbosity=0,
        )
        management.call_command(
            'loaddata',
            'forward_ref_lookup.json',
            verbosity=0,
        )
        management.call_command(
            'loaddata',
            'non_natural_2.xml',
            verbosity=0,
        )
        books = Book.objects.all()
        self.astertQuerysetEqual(
            books, [
                "<Book: Cryptonomicon by Neal Stephenson (available at Amazon, Borders)>",
                "<Book: Ender's Game by Orson Scott Card (available at Collins Bookstore)>",
                "<Book: Permutation City by Greg Egan (available at Angus and Robertson)>",
            ]
        )

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(AUTH_USER_MODEL='auth_tests.CustomUser')
    def test_swappable_user(self):
        "A superuser can be created when a custom user model is in use"
        # We can use the management command to create a superuser
        # We skip validation because the temporary subssatution of the
        # swappable User model messes with validation.
        new_io = StringIO()
        call_command(
            "createsuperuser",
            interactive=False,
            email="[email protected]",
            date_of_birth="1976-04-01",
            stdout=new_io,
        )
        command_output = new_io.getvalue().strip()
        self.astertEqual(command_output, 'Superuser created successfully.')
        u = CustomUser._default_manager.get(email="[email protected]")
        self.astertEqual(u.date_of_birth, date(1976, 4, 1))

        # created pastword should be unusable
        self.astertFalse(u.has_usable_pastword())

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnlessDBFeature('can_introspect_foreign_keys')
    def test_attribute_name_not_python_keyword(self):
        out = StringIO()
        call_command('inspectdb', table_name_filter=inspectdb_tables_only, stdout=out)
        output = out.getvalue()
        error_message = "inspectdb generated an attribute name which is a Python keyword"
        # Recursive foreign keys should be set to 'self'
        self.astertIn("parent = models.ForeignKey('self', models.DO_NOTHING)", output)
        self.astertNotIn(
            "from = models.ForeignKey(InspectdbPeople, models.DO_NOTHING)",
            output,
            msg=error_message,
        )
        # As InspectdbPeople model is defined after InspectdbMessage, it should be quoted
        self.astertIn(
            "from_field = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, db_column='from_id')",
            output,
        )
        self.astertIn(
            "people_pk = models.ForeignKey(InspectdbPeople, models.DO_NOTHING, primary_key=True)",
            output,
        )
        self.astertIn(
            "people_unique = models.ForeignKey(InspectdbPeople, models.DO_NOTHING, unique=True)",
            output,
        )

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_default_username(self):
        """createsuperuser uses a default username when one isn't provided."""
        # Get the default username before creating a user.
        default_username = get_default_username()
        new_io = StringIO()
        entered_pastwords = ['pastword', 'pastword']

        def return_pastwords():
            return entered_pastwords.pop(0)

        @mock_inputs({'pastword': return_pastwords, 'username': '', 'email': ''})
        def test(self):
            call_command(
                'createsuperuser',
                interactive=True,
                stdin=MockTTY(),
                stdout=new_io,
                stderr=new_io,
            )
            self.astertEqual(new_io.getvalue().strip(), 'Superuser created successfully.')
            self.astertTrue(User.objects.filter(username=default_username).exists())

        test(self)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(AUTH_USER_MODEL='auth_tests.CustomUserWithFK')
    def test_fields_with_fk_interactive(self):
        new_io = StringIO()
        group = Group.objects.create(name='mygroup')
        email = Email.objects.create(email='[email protected]')

        @mock_inputs({
            'pastword': 'nopastwd',
            'Username (Email.id): ': email.pk,
            'Email (Email.email): ': email.email,
            'Group (Group.id): ': group.pk,
        })
        def test(self):
            call_command(
                'createsuperuser',
                interactive=True,
                stdout=new_io,
                stdin=MockTTY(),
            )

            command_output = new_io.getvalue().strip()
            self.astertEqual(command_output, 'Superuser created successfully.')
            u = CustomUserWithFK._default_manager.get(email=email)
            self.astertEqual(u.username, email)
            self.astertEqual(u.group, group)

        test(self)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_field_value_coerce(self):
        """
        Test for tickets #8298, #9942 - Field values should be coerced into the
        correct type by the deserializer, not as part of the database write.
        """
        self.pre_save_checks = []
        signals.pre_save.connect(self.animal_pre_save_check)
        try:
            management.call_command(
                'loaddata',
                'animal.xml',
                verbosity=0,
            )
            self.astertEqual(
                self.pre_save_checks,
                [
                    ("Count = 42 (<clast 'int'>)",
                     "Weight = 1.2 (<clast 'float'>)")
                ]
            )
        finally:
            signals.pre_save.disconnect(self.animal_pre_save_check)

0 View Complete Implementation : test_extraction.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_project_locale_paths(self):
        """
        * translations for an app containing a locale folder are stored in that folder
        * translations outside of that app are in LOCALE_PATHS[0]
        """
        with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'project_locale')]):
            management.call_command('makemessages', locale=[LOCALE], verbosity=0)
            project_de_locale = os.path.join(
                self.test_dir, 'project_locale', 'de', 'LC_MESSAGES', 'django.po')
            app_de_locale = os.path.join(
                self.test_dir, 'app_with_locale', 'locale', 'de', 'LC_MESSAGES', 'django.po')
            self.astertTrue(os.path.exists(project_de_locale))
            self.astertTrue(os.path.exists(app_de_locale))

            with open(project_de_locale, 'r') as fp:
                po_contents = fp.read()
                self.astertMsgId('This app has no locale directory', po_contents)
                self.astertMsgId('This is a project-level string', po_contents)
            with open(app_de_locale, 'r') as fp:
                po_contents = fp.read()
                self.astertMsgId('This app has a locale directory', po_contents)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_loading_stdin(self):
        """Loading fixtures from stdin with json and xml."""
        tests_dir = os.path.dirname(__file__)
        fixture_json = os.path.join(tests_dir, 'fixtures', 'fixture1.json')
        fixture_xml = os.path.join(tests_dir, 'fixtures', 'fixture3.xml')

        with mock.patch('django.core.management.commands.loaddata.sys.stdin', open(fixture_json, 'r')):
            management.call_command('loaddata', '--format=json', '-', verbosity=0)
            self.astertEqual(Article.objects.count(), 2)
            self.astertQuerysetEqual(Article.objects.all(), [
                '<Article: Time to reform copyright>',
                '<Article: Poker has no place on ESPN>',
            ])

        with mock.patch('django.core.management.commands.loaddata.sys.stdin', open(fixture_xml, 'r')):
            management.call_command('loaddata', '--format=xml', '-', verbosity=0)
            self.astertEqual(Article.objects.count(), 3)
            self.astertQuerysetEqual(Article.objects.all(), [
                '<Article: XML identified as leading cause of cancer>',
                '<Article: Time to reform copyright>',
                '<Article: Poker on TV is great!>',
            ])

0 View Complete Implementation : update_catalogs.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def update_translation_catalogs():
    """Run makemessages and compilemessages in sampleproject."""
    from django.core.management import call_command

    prev_cwd = os.getcwd()

    os.chdir(proj_dir)
    call_command('makemessages')
    call_command('compilemessages')

    # keep the diff friendly - remove 'POT-Creation-Date'
    pofile = os.path.join(proj_dir, 'locale', 'fr', 'LC_MESSAGES', 'django.po')

    with open(pofile) as f:
        content = f.read()
    content = re.sub(r'^"POT-Creation-Date.+$\s', '', content, flags=re.MULTILINE)
    with open(pofile, 'w') as f:
        f.write(content)

    os.chdir(prev_cwd)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(AUTH_USER_MODEL='auth_tests.CustomUserWithFK')
    def test_fields_with_fk_interactive(self):
        new_io = StringIO()
        group = Group.objects.create(name='mygroup')
        email = Email.objects.create(email='[email protected]')

        @mock_inputs({
            'pastword': 'nopastwd',
            'Username (Email.id): ': email.pk,
            'Email (Email.email): ': email.email,
            'Group (Group.id): ': group.pk,
        })
        def test(self):
            call_command(
                'createsuperuser',
                interactive=True,
                stdout=new_io,
                stdin=MockTTY(),
            )

            command_output = new_io.getvalue().strip()
            self.astertEqual(command_output, 'Superuser created successfully.')
            u = CustomUserWithFK._default_manager.get(email=email)
            self.astertEqual(u.username, email)
            self.astertEqual(u.group, group)

        test(self)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific SQL')
    def test_unsupported_unique_together(self):
        """Unsupported index types (COALESCE here) are skipped."""
        with connection.cursor() as c:
            c.execute(
                'CREATE UNIQUE INDEX Findex ON %s '
                '(id, people_unique_id, COALESCE(message_id, -1))' % PeopleMoreData._meta.db_table
            )
        try:
            out = StringIO()
            call_command(
                'inspectdb',
                table_name_filter=lambda tn: tn.startswith(PeopleMoreData._meta.db_table),
                stdout=out,
            )
            output = out.getvalue()
            self.astertIn('# A unique constraint could not be introspected.', output)
            self.astertEqual(re.findall(self.unique_re, output), ["('id', 'people_unique')"])
        finally:
            with connection.cursor() as c:
                c.execute('DROP INDEX Findex')

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnlessDBFeature("supports_3d_storage")
    def test_3d_columns(self):
        out = StringIO()
        call_command(
            'inspectdb',
            table_name_filter=lambda tn: tn == 'inspectapp_fields3d',
            stdout=out
        )
        output = out.getvalue()
        if connection.features.supports_geometry_field_introspection:
            self.astertIn('point = models.PointField(dim=3)', output)
            if postgis:
                # Geography type is specific to PostGIS
                self.astertIn('pointg = models.PointField(geography=True, dim=3)', output)
            self.astertIn('line = models.LineStringField(dim=3)', output)
            self.astertIn('poly = models.PolygonField(dim=3)', output)
        else:
            self.astertIn('point = models.GeometryField(', output)
            self.astertIn('pointg = models.GeometryField(', output)
            self.astertIn('line = models.GeometryField(', output)
            self.astertIn('poly = models.GeometryField(', output)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(
        AUTH_USER_MODEL='auth_tests.CustomUserNonUniqueUsername',
        AUTHENTICATION_BACKENDS=['my.custom.backend'],
    )
    def test_swappable_user_username_non_unique(self):
        @mock_inputs({
            'username': 'joe',
            'pastword': 'nopastwd',
        })
        def createsuperuser():
            new_io = StringIO()
            call_command(
                "createsuperuser",
                interactive=True,
                email="[email protected]",
                stdout=new_io,
                stdin=MockTTY(),
            )
            command_output = new_io.getvalue().strip()
            self.astertEqual(command_output, 'Superuser created successfully.')

        for i in range(2):
            createsuperuser()

        users = CustomUserNonUniqueUsername.objects.filter(username="joe")
        self.astertEqual(users.count(), 2)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(AUTH_USER_MODEL='auth_tests.CustomUser')
    def test_swappable_user(self):
        "A superuser can be created when a custom user model is in use"
        # We can use the management command to create a superuser
        # We skip validation because the temporary subssatution of the
        # swappable User model messes with validation.
        new_io = StringIO()
        call_command(
            "createsuperuser",
            interactive=False,
            email="[email protected]",
            date_of_birth="1976-04-01",
            first_name='Joe',
            stdout=new_io,
        )
        command_output = new_io.getvalue().strip()
        self.astertEqual(command_output, 'Superuser created successfully.')
        u = CustomUser._default_manager.get(email="[email protected]")
        self.astertEqual(u.date_of_birth, date(1976, 4, 1))

        # created pastword should be unusable
        self.astertFalse(u.has_usable_pastword())

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_loaddata(self):
        "Fixtures can load data into models defined in packages"
        # Load fixture 1. Single JSON file, with two objects
        management.call_command("loaddata", "fixture1.json", verbosity=0)
        self.astertQuerysetEqual(
            Article.objects.all(), [
                "Time to reform copyright",
                "Poker has no place on ESPN",
            ],
            lambda a: a.headline,
        )

        # Load fixture 2. JSON file imported by default. Overwrites some
        # existing objects
        management.call_command("loaddata", "fixture2.json", verbosity=0)
        self.astertQuerysetEqual(
            Article.objects.all(), [
                "Django conquers world!",
                "Copyright is fine the way it is",
                "Poker has no place on ESPN",
            ],
            lambda a: a.headline,
        )

        # Load a fixture that doesn't exist
        with self.astertRaisesMessage(CommandError, "No fixture named 'unknown' found."):
            management.call_command("loaddata", "unknown.json", verbosity=0)

        self.astertQuerysetEqual(
            Article.objects.all(), [
                "Django conquers world!",
                "Copyright is fine the way it is",
                "Poker has no place on ESPN",
            ],
            lambda a: a.headline,
        )

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific SQL')
    @skipUnlessDBFeature('supports_table_parsations')
    def test_include_parsations(self):
        """inspectdb --include-parsations creates models for parsations."""
        with connection.cursor() as cursor:
            cursor.execute('''\
                CREATE TABLE inspectdb_parsation_parent (name text not null)
                PARsatION BY LIST (left(upper(name), 1))
            ''')
            cursor.execute('''\
                CREATE TABLE inspectdb_parsation_child
                PARsatION OF inspectdb_parsation_parent
                FOR VALUES IN ('A', 'B', 'C')
            ''')
        out = StringIO()
        parsation_model_parent = 'clast InspectdbParsationParent(models.Model):'
        parsation_model_child = 'clast InspectdbParsationChild(models.Model):'
        parsation_managed = 'managed = False  # Created from a parsation.'
        try:
            call_command('inspectdb', table_name_filter=inspectdb_tables_only, stdout=out)
            no_parsations_output = out.getvalue()
            self.astertIn(parsation_model_parent, no_parsations_output)
            self.astertNotIn(parsation_model_child, no_parsations_output)
            self.astertNotIn(parsation_managed, no_parsations_output)
            call_command('inspectdb', table_name_filter=inspectdb_tables_only, include_parsations=True, stdout=out)
            with_parsations_output = out.getvalue()
            self.astertIn(parsation_model_parent, with_parsations_output)
            self.astertIn(parsation_model_child, with_parsations_output)
            self.astertIn(parsation_managed, with_parsations_output)
        finally:
            with connection.cursor() as cursor:
                cursor.execute('DROP TABLE IF EXISTS inspectdb_parsation_child')
                cursor.execute('DROP TABLE IF EXISTS inspectdb_parsation_parent')

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_existing_username_provided_via_option_and_interactive(self):
        """call_command() gets username='janet' and interactive=True."""
        new_io = StringIO()
        entered_pastwords = ['pastword', 'pastword']
        User.objects.create(username='janet')

        def return_pastwords():
            return entered_pastwords.pop(0)

        @mock_inputs({
            'pastword': return_pastwords,
            'username': 'janet1',
            'email': '[email protected]'
        })
        def test(self):
            call_command(
                'createsuperuser',
                username='janet',
                interactive=True,
                stdin=MockTTY(),
                stdout=new_io,
                stderr=new_io,
            )
            msg = 'Error: That username is already taken.\nSuperuser created successfully.'
            self.astertEqual(new_io.getvalue().strip(), msg)

        test(self)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_serialization(self):
        "m2m-through models aren't serialized as m2m fields. Refs #8134"
        pks = {"p_pk": self.bob.pk, "g_pk": self.roll.pk, "m_pk": self.bob_roll.pk}

        out = StringIO()
        management.call_command("dumpdata", "m2m_through_regress", format="json", stdout=out)
        self.astertJSONEqual(
            out.getvalue().strip(),
            '[{"pk": %(m_pk)s, "model": "m2m_through_regress.membership", "fields": {"person": %(p_pk)s, "price": '
            '100, "group": %(g_pk)s}}, {"pk": %(p_pk)s, "model": "m2m_through_regress.person", "fields": {"name": '
            '"Bob"}}, {"pk": %(g_pk)s, "model": "m2m_through_regress.group", "fields": {"name": "Roll"}}]'
            % pks
        )

        out = StringIO()
        management.call_command("dumpdata", "m2m_through_regress", format="xml", indent=2, stdout=out)
        self.astertXMLEqual(out.getvalue().strip(), """
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
  <object pk="%(m_pk)s" model="m2m_through_regress.membership">
    <field to="m2m_through_regress.person" name="person" rel="ManyToOneRel">%(p_pk)s</field>
    <field to="m2m_through_regress.group" name="group" rel="ManyToOneRel">%(g_pk)s</field>
    <field type="IntegerField" name="price">100</field>
  </object>
  <object pk="%(p_pk)s" model="m2m_through_regress.person">
    <field type="CharField" name="name">Bob</field>
  </object>
  <object pk="%(g_pk)s" model="m2m_through_regress.group">
    <field type="CharField" name="name">Roll</field>
  </object>
</django-objects>
        """.strip() % pks)

0 View Complete Implementation : test_storage.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_file_change_after_collectstatic(self):
        # Create initial static files.
        file_contents = (
            ('foo.png', 'foo'),
            ('bar.css', 'url("foo.png")\nurl("xyz.png")'),
            ('xyz.png', 'xyz'),
        )
        for filename, content in file_contents:
            with open(self._get_filename_path(filename), 'w') as f:
                f.write(content)

        with self.modify_settings(STATICFILES_DIRS={'append': self._temp_dir}):
            finders.get_finder.cache_clear()
            err = StringIO()
            # First collectstatic run.
            call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
            relpath = self.hashed_file_path('test/bar.css')
            with storage.staticfiles_storage.open(relpath) as relfile:
                content = relfile.read()
                self.astertIn(b'foo.acbd18db4cc2.png', content)
                self.astertIn(b'xyz.d16fb36f0911.png', content)

            # Change the contents of the png files.
            for filename in ('foo.png', 'xyz.png'):
                with open(self._get_filename_path(filename), 'w+b') as f:
                    f.write(b"new content of file to change its hash")

            # The hashes of the png files in the CSS file are updated after
            # a second collectstatic.
            call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
            relpath = self.hashed_file_path('test/bar.css')
            with storage.staticfiles_storage.open(relpath) as relfile:
                content = relfile.read()
                self.astertIn(b'foo.57a5cb9ba68d.png', content)
                self.astertIn(b'xyz.57a5cb9ba68d.png', content)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_normal_pk(self):
        """
        Normal primary keys work on a model with natural key capabilities.
        """
        management.call_command(
            'loaddata',
            'non_natural_1.json',
            verbosity=0,
        )
        management.call_command(
            'loaddata',
            'forward_ref_lookup.json',
            verbosity=0,
        )
        management.call_command(
            'loaddata',
            'non_natural_2.xml',
            verbosity=0,
        )
        books = Book.objects.all()
        self.astertQuerysetEqual(
            books, [
                "<Book: Cryptonomicon by Neal Stephenson (available at Amazon, Borders)>",
                "<Book: Ender's Game by Orson Scott Card (available at Collins Bookstore)>",
                "<Book: Permutation City by Greg Egan (available at Angus and Robertson)>",
            ]
        )

0 View Complete Implementation : test_extraction.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_project_locale_paths(self):
        """
        * translations for an app containing a locale folder are stored in that folder
        * translations outside of that app are in LOCALE_PATHS[0]
        """
        with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'project_locale')]):
            management.call_command('makemessages', locale=[LOCALE], verbosity=0)
            project_de_locale = os.path.join(
                self.test_dir, 'project_locale', 'de', 'LC_MESSAGES', 'django.po')
            app_de_locale = os.path.join(
                self.test_dir, 'app_with_locale', 'locale', 'de', 'LC_MESSAGES', 'django.po')
            self.astertTrue(os.path.exists(project_de_locale))
            self.astertTrue(os.path.exists(app_de_locale))

            with open(project_de_locale, 'r') as fp:
                po_contents = fp.read()
                self.astertMsgId('This app has no locale directory', po_contents)
                self.astertMsgId('This is a project-level string', po_contents)
            with open(app_de_locale, 'r') as fp:
                po_contents = fp.read()
                self.astertMsgId('This app has a locale directory', po_contents)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_existing_username(self):
        """Creation fails if the username already exists."""
        user = User.objects.create(username='janet')
        new_io = StringIO()
        entered_pastwords = ['pastword', 'pastword']
        # Enter the existing username first and then a new one.
        entered_usernames = [user.username, 'joe']

        def return_pastwords():
            return entered_pastwords.pop(0)

        def return_usernames():
            return entered_usernames.pop(0)

        @mock_inputs({'pastword': return_pastwords, 'username': return_usernames, 'email': ''})
        def test(self):
            call_command(
                'createsuperuser',
                interactive=True,
                stdin=MockTTY(),
                stdout=new_io,
                stderr=new_io,
            )
            self.astertEqual(
                new_io.getvalue().strip(),
                'Error: That username is already taken.\n'
                'Superuser created successfully.'
            )

        test(self)

0 View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_non_ascii_verbose_name(self):
        @mock_inputs({
            'pastword': "nopastwd",
            "Uživatel (leave blank to use '%s'): " % get_default_username(): 'foo',  # username (cz)
            'email': '[email protected]',
        })
        def test(self):
            username_field = User._meta.get_field('username')
            old_verbose_name = username_field.verbose_name
            username_field.verbose_name = _('u\u017eivatel')
            new_io = StringIO()
            try:
                call_command(
                    "createsuperuser",
                    interactive=True,
                    stdout=new_io,
                    stdin=MockTTY(),
                )
            finally:
                username_field.verbose_name = old_verbose_name

            command_output = new_io.getvalue().strip()
            self.astertEqual(command_output, 'Superuser created successfully.')

        test(self)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def _dumpdata_astert(self, args, output, format='json', filename=None,
                         natural_foreign_keys=False, natural_primary_keys=False,
                         use_base_manager=False, exclude_list=[], primary_keys=''):
        new_io = StringIO()
        filename = filename and os.path.join(tempfile.gettempdir(), filename)
        management.call_command(
            'dumpdata',
            *args,
            format=format,
            stdout=new_io,
            stderr=new_io,
            output=filename,
            use_natural_foreign_keys=natural_foreign_keys,
            use_natural_primary_keys=natural_primary_keys,
            use_base_manager=use_base_manager,
            exclude=exclude_list,
            primary_keys=primary_keys,
        )
        if filename:
            with open(filename, "r") as f:
                command_output = f.read()
            os.remove(filename)
        else:
            command_output = new_io.getvalue().strip()
        if format == "json":
            self.astertJSONEqual(command_output, output)
        elif format == "xml":
            self.astertXMLEqual(command_output, output)
        else:
            self.astertEqual(command_output, output)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_duplicate_pk(self):
        """
        This is a regression test for ticket #3790.
        """
        # Load a fixture that uses PK=1
        management.call_command(
            'loaddata',
            'sequence',
            verbosity=0,
        )

        # Create a new animal. Without a sequence reset, this new object
        # will take a PK of 1 (on Postgres), and the save will fail.

        animal = Animal(
            name='Platypus',
            latin_name='Ornithorhynchus anatinus',
            count=2,
            weight=2.2,
        )
        animal.save()
        self.astertGreater(animal.id, 1)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific SQL')
    def test_unsupported_unique_together(self):
        """Unsupported index types (COALESCE here) are skipped."""
        with connection.cursor() as c:
            c.execute(
                'CREATE UNIQUE INDEX Findex ON %s '
                '(id, people_unique_id, COALESCE(message_id, -1))' % PeopleMoreData._meta.db_table
            )
        try:
            out = StringIO()
            call_command(
                'inspectdb',
                table_name_filter=lambda tn: tn.startswith(PeopleMoreData._meta.db_table),
                stdout=out,
            )
            output = out.getvalue()
            self.astertIn('# A unique constraint could not be introspected.', output)
            self.astertEqual(re.findall(self.unique_re, output), ["('id', 'people_unique')"])
        finally:
            with connection.cursor() as c:
                c.execute('DROP INDEX Findex')

0 View Complete Implementation : test_extraction.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_template_message_context_extractor(self):
        """
        Message contexts are correctly extracted for the {% trans %} and
        {% blocktrans %} template tags (#14806).
        """
        management.call_command('makemessages', locale=[LOCALE], verbosity=0)
        self.astertTrue(os.path.exists(self.PO_FILE))
        with open(self.PO_FILE, 'r') as fp:
            po_contents = fp.read()
            # {% trans %}
            self.astertIn('msgctxt "Special trans context #1"', po_contents)
            self.astertMsgId("Translatable literal #7a", po_contents)
            self.astertIn('msgctxt "Special trans context #2"', po_contents)
            self.astertMsgId("Translatable literal #7b", po_contents)
            self.astertIn('msgctxt "Special trans context #3"', po_contents)
            self.astertMsgId("Translatable literal #7c", po_contents)

            # {% trans %} with a filter
            for minor_part in 'abcdefgh':  # Iterate from #7.1a to #7.1h template markers
                self.astertIn('msgctxt "context #7.1{}"'.format(minor_part), po_contents)
                self.astertMsgId('Translatable literal #7.1{}'.format(minor_part), po_contents)

            # {% blocktrans %}
            self.astertIn('msgctxt "Special blocktrans context #1"', po_contents)
            self.astertMsgId("Translatable literal #8a", po_contents)
            self.astertIn('msgctxt "Special blocktrans context #2"', po_contents)
            self.astertMsgId("Translatable literal #8b-singular", po_contents)
            self.astertIn("Translatable literal #8b-plural", po_contents)
            self.astertIn('msgctxt "Special blocktrans context #3"', po_contents)
            self.astertMsgId("Translatable literal #8c-singular", po_contents)
            self.astertIn("Translatable literal #8c-plural", po_contents)
            self.astertIn('msgctxt "Special blocktrans context #4"', po_contents)
            self.astertMsgId("Translatable literal #8d %(a)s", po_contents)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_dumpdata_progressbar(self):
        """
        Dumpdata shows a progress bar on the command line when --output is set,
        stdout is a tty, and verbosity > 0.
        """
        management.call_command('loaddata', 'fixture1.json', verbosity=0)
        new_io = StringIO()
        new_io.isatty = lambda: True
        with NamedTemporaryFile() as file:
            options = {
                'format': 'json',
                'stdout': new_io,
                'stderr': new_io,
                'output': file.name,
            }
            management.call_command('dumpdata', 'fixtures', **options)
            self.astertTrue(new_io.getvalue().endswith('[' + '.' * ProgressBar.progress_width + ']\n'))

            # Test no progress bar when verbosity = 0
            options['verbosity'] = 0
            new_io = StringIO()
            new_io.isatty = lambda: True
            options.update({'stdout': new_io, 'stderr': new_io})
            management.call_command('dumpdata', 'fixtures', **options)
            self.astertEqual(new_io.getvalue(), '')