Exemplo n.º 1
0
    def _fixture_setup(self):
        if not connections_support_transactions():
            return super(TestCase, self)._fixture_setup()

        assert not self.reset_sequences, 'reset_sequences cannot be used on TestCase instances'

        # If the test case has a multi_db=True flag, setup all databases.
        # Otherwise, just use default.
        db_names = connections if getattr(self, 'multi_db', False) else [DEFAULT_DB_ALIAS]

        for db_name in db_names:
            transaction.enter_transaction_management(using=db_name)
            transaction.managed(True, using=db_name)
        disable_transaction_methods()

        from djangocg.contrib.sites.models import Site
        Site.objects.clear_cache()

        for db in db_names:
            if hasattr(self, 'fixtures'):
                call_command('loaddata', *self.fixtures,
                             **{
                                'verbosity': 0,
                                'commit': False,
                                'database': db,
                                'skip_validation': True,
                             })
Exemplo n.º 2
0
    def test_createsuperuser_nolocale(self):
        """
        Check that createsuperuser does not break when no locale is set. See
        ticket #16017.
        """

        old_getdefaultlocale = locale.getdefaultlocale
        old_getpass = createsuperuser.getpass
        try:
            # Temporarily remove locale information
            locale.getdefaultlocale = lambda: (None, None)

            # Temporarily replace getpass to allow interactive code to be used
            # non-interactively
            class mock_getpass: pass
            mock_getpass.getpass = staticmethod(lambda p=None: "nopasswd")
            createsuperuser.getpass = mock_getpass

            # Call the command in this new environment
            new_io = StringIO()
            call_command("createsuperuser", interactive=True, username="******", email="*****@*****.**", stdout=new_io)

        except TypeError as e:
            self.fail("createsuperuser fails if the OS provides no information about the current locale")

        finally:
            # Re-apply locale and getpass information
            createsuperuser.getpass = old_getpass
            locale.getdefaultlocale = old_getdefaultlocale

        # If we were successful, a user should have been created
        u = User.objects.get(username="******")
        self.assertEqual(u.email, '*****@*****.**')
Exemplo n.º 3
0
 def test_no_location_disabled(self):
     os.chdir(self.test_dir)
     management.call_command('makemessages', locale=LOCALE, verbosity=0, no_location=False)
     self.assertTrue(os.path.exists(self.PO_FILE))
     with open(self.PO_FILE, 'r') as fp:
         po_contents = fp.read()
         self.assertTrue('#: templates/test.html:55' in po_contents)
Exemplo n.º 4
0
 def test_no_wrap_disabled(self):
     os.chdir(self.test_dir)
     management.call_command('makemessages', locale=LOCALE, verbosity=0, no_wrap=False)
     self.assertTrue(os.path.exists(self.PO_FILE))
     with open(self.PO_FILE, 'r') as fp:
         po_contents = fp.read()
         self.assertMsgId('""\n"This literal should also be included wrapped or not wrapped depending on the "\n"use of the --no-wrap option."', po_contents, use_quotes=False)
Exemplo n.º 5
0
 def test_copy_plural_forms(self):
     os.chdir(self.test_dir)
     management.call_command('makemessages', locale=LOCALE, verbosity=0)
     self.assertTrue(os.path.exists(self.PO_FILE))
     with open(self.PO_FILE, 'r') as fp:
         po_contents = fp.read()
         self.assertTrue('Plural-Forms: nplurals=2; plural=(n != 1)' in po_contents)
Exemplo n.º 6
0
    def test_template_message_context_extractor(self):
        """
        Ensure that message contexts are correctly extracted for the
        {% trans %} and {% blocktrans %} template tags.
        Refs #14806.
        """
        os.chdir(self.test_dir)
        management.call_command('makemessages', locale=LOCALE, verbosity=0)
        self.assertTrue(os.path.exists(self.PO_FILE))
        with open(self.PO_FILE, 'r') as fp:
            po_contents = fp.read()
            # {% trans %}
            self.assertTrue('msgctxt "Special trans context #1"' in po_contents)
            self.assertTrue("Translatable literal #7a" in po_contents)
            self.assertTrue('msgctxt "Special trans context #2"' in po_contents)
            self.assertTrue("Translatable literal #7b" in po_contents)
            self.assertTrue('msgctxt "Special trans context #3"' in po_contents)
            self.assertTrue("Translatable literal #7c" in po_contents)

            # {% blocktrans %}
            self.assertTrue('msgctxt "Special blocktrans context #1"' in po_contents)
            self.assertTrue("Translatable literal #8a" in po_contents)
            self.assertTrue('msgctxt "Special blocktrans context #2"' in po_contents)
            self.assertTrue("Translatable literal #8b-singular" in po_contents)
            self.assertTrue("Translatable literal #8b-plural" in po_contents)
            self.assertTrue('msgctxt "Special blocktrans context #3"' in po_contents)
            self.assertTrue("Translatable literal #8c-singular" in po_contents)
            self.assertTrue("Translatable literal #8c-plural" in po_contents)
            self.assertTrue('msgctxt "Special blocktrans context #4"' in po_contents)
            self.assertTrue("Translatable literal #8d" in po_contents)
Exemplo n.º 7
0
    def test_comments_extractor(self):
        os.chdir(self.test_dir)
        management.call_command('makemessages', locale=LOCALE, verbosity=0)
        self.assertTrue(os.path.exists(self.PO_FILE))
        with open(self.PO_FILE, 'r') as fp:
            po_contents = fp.read()
            self.assertTrue('#. Translators: This comment should be extracted' in po_contents)
            self.assertTrue('This comment should not be extracted' not in po_contents)
            # Comments in templates
            self.assertTrue('#. Translators: Django template comment for translators' in po_contents)
            self.assertTrue("#. Translators: Django comment block for translators\n#. string's meaning unveiled" in po_contents)

            self.assertTrue('#. Translators: One-line translator comment #1' in po_contents)
            self.assertTrue('#. Translators: Two-line translator comment #1\n#. continued here.' in po_contents)

            self.assertTrue('#. Translators: One-line translator comment #2' in po_contents)
            self.assertTrue('#. Translators: Two-line translator comment #2\n#. continued here.' in po_contents)

            self.assertTrue('#. Translators: One-line translator comment #3' in po_contents)
            self.assertTrue('#. Translators: Two-line translator comment #3\n#. continued here.' in po_contents)

            self.assertTrue('#. Translators: One-line translator comment #4' in po_contents)
            self.assertTrue('#. Translators: Two-line translator comment #4\n#. continued here.' in po_contents)

            self.assertTrue('#. Translators: One-line translator comment #5 -- with non ASCII characters: áéíóúö' in po_contents)
            self.assertTrue('#. Translators: Two-line translator comment #5 -- with non ASCII characters: áéíóúö\n#. continued here.' in po_contents)
Exemplo n.º 8
0
 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,
         commit=False
     )
     articles = Article.objects.exclude(id=9)
     self.assertEqual(
         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.assertEqual(
         list(articles.values_list('id', flat=True)),
         [1, 2, 3, 4, 5, 6, 7, 8]
     )
Exemplo n.º 9
0
 def _get_file(self, filepath):
     out = six.StringIO()
     call_command('findstatic', filepath, all=False, verbosity=0, stdout=out)
     out.seek(0)
     lines = [l.strip() for l in out.readlines()]
     with codecs.open(smart_text(lines[1].strip()), "r", "utf-8") as f:
         return f.read()
Exemplo n.º 10
0
    def test_nk_on_serialize(self):
        """
        Check that natural key requirements are taken into account
        when serializing models
        """
        management.call_command(
            'loaddata',
            'forward_ref_lookup.json',
            verbosity=0,
            commit=False
            )

        stdout = StringIO()
        management.call_command(
            'dumpdata',
            'fixtures_regress.book',
            'fixtures_regress.person',
            'fixtures_regress.store',
            verbosity=0,
            format='json',
            use_natural_keys=True,
            stdout=stdout,
        )
        self.assertEqual(
            stdout.getvalue(),
            """[{"pk": 2, "model": "fixtures_regress.store", "fields": {"main": null, "name": "Amazon"}}, {"pk": 3, "model": "fixtures_regress.store", "fields": {"main": null, "name": "Borders"}}, {"pk": 4, "model": "fixtures_regress.person", "fields": {"name": "Neal Stephenson"}}, {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]], "name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]"""
        )
Exemplo n.º 11
0
 def test_extraction_warning(self):
     os.chdir(self.test_dir)
     shutil.copyfile('./code.sample', './code_sample.py')
     stdout = StringIO()
     management.call_command('makemessages', locale=LOCALE, stdout=stdout)
     os.remove('./code_sample.py')
     self.assertIn("code_sample.py:4", stdout.getvalue())
Exemplo n.º 12
0
    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,
            commit=False
        )
        management.call_command(
            'loaddata',
            'nk-inheritance.json',
            verbosity=0,
            commit=False
        )
        self.assertEqual(
            NKChild.objects.get(pk=1).data,
            'apple'
        )

        self.assertEqual(
            RefToNKChild.objects.get(pk=1).nk_fk.data,
            'apple'
        )
Exemplo n.º 13
0
    def test_output_formats(self):
        # Load back in fixture 1, we need the articles from it
        management.call_command("loaddata", "fixture1", verbosity=0, commit=False)

        # Try to load fixture 6 using format discovery
        management.call_command("loaddata", "fixture6", verbosity=0, commit=False)
        self.assertQuerysetEqual(
            Tag.objects.all(),
            [
                '<Tag: <Article: Time to reform copyright> tagged "copyright">',
                '<Tag: <Article: Time to reform copyright> tagged "law">',
            ],
        )

        # Dump the current contents of the database as a JSON fixture
        self._dumpdata_assert(
            ["fixtures"],
            '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "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"}}, {"pk": 1, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": 3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "law", "tagged_id": 3}}, {"pk": 1, "model": "fixtures.person", "fields": {"name": "Django Reinhardt"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}, {"pk": 3, "model": "fixtures.person", "fields": {"name": "Prince"}}, {"pk": 10, "model": "fixtures.book", "fields": {"name": "Achieving self-awareness of Python programs", "authors": []}}]',
            natural_keys=True,
        )

        # Dump the current contents of the database as an XML fixture
        self._dumpdata_assert(
            ["fixtures"],
            """<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0"><object pk="1" model="fixtures.category"><field type="CharField" name="title">News Stories</field><field type="TextField" name="description">Latest news stories</field></object><object pk="2" model="fixtures.article"><field type="CharField" name="headline">Poker has no place on ESPN</field><field type="DateTimeField" name="pub_date">2006-06-16T12:00:00</field></object><object pk="3" model="fixtures.article"><field type="CharField" name="headline">Time to reform copyright</field><field type="DateTimeField" name="pub_date">2006-06-16T13:00:00</field></object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">law</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">Prince</field></object><object pk="10" model="fixtures.book"><field type="CharField" name="name">Achieving self-awareness of Python programs</field><field to="fixtures.person" name="authors" rel="ManyToManyRel"></field></object></django-objects>""",
            format="xml",
            natural_keys=True,
        )
Exemplo n.º 14
0
    def handle(self, *fixture_labels, **options):
        from djangocg.core.management import call_command
        from djangocg.db import connection

        verbosity = int(options.get('verbosity'))
        interactive = options.get('interactive')
        addrport = options.get('addrport')

        # Create a test database.
        db_name = connection.creation.create_test_db(verbosity=verbosity, autoclobber=not interactive)

        # Import the fixture data into the test database.
        call_command('loaddata', *fixture_labels, **{'verbosity': verbosity})

        # Run the development server. Turn off auto-reloading because it causes
        # a strange error -- it causes this handle() method to be called
        # multiple times.
        shutdown_message = '\nServer stopped.\nNote that the test database, %r, has not been deleted. You can explore it on your own.' % db_name
        use_threading = connection.features.test_db_allows_multiple_connections
        call_command('runserver',
            addrport=addrport,
            shutdown_message=shutdown_message,
            use_reloader=False,
            use_ipv6=options['use_ipv6'],
            use_threading=use_threading
        )
Exemplo n.º 15
0
    def test_unmatched_identifier_loading(self):
        # Try to load db fixture 3. This won't load because the database identifier doesn't match
        management.call_command("loaddata", "db_fixture_3", verbosity=0, commit=False)
        self.assertQuerysetEqual(Article.objects.all(), [])

        management.call_command("loaddata", "db_fixture_3", verbosity=0, using="default", commit=False)
        self.assertQuerysetEqual(Article.objects.all(), [])
Exemplo n.º 16
0
 def _fixture_teardown(self):
     # If the test case has a multi_db=True flag, flush all databases.
     # Otherwise, just flush default.
     databases = connections if getattr(self, 'multi_db', False) else [DEFAULT_DB_ALIAS]
     for db in databases:
         call_command('flush', verbosity=0, interactive=False, database=db,
                      skip_validation=True, reset_sequences=False)
Exemplo n.º 17
0
    def test_serialization(self):
        "m2m-through models aren't serialized as m2m fields. Refs #8134"

        p = Person.objects.create(name="Bob")
        g = Group.objects.create(name="Roll")
        m =Membership.objects.create(person=p, group=g)

        pks = {"p_pk": p.pk, "g_pk": g.pk, "m_pk": m.pk}

        out = StringIO()
        management.call_command("dumpdata", "m2m_through_regress", format="json", stdout=out)
        self.assertEqual(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.assertEqual(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)
Exemplo n.º 18
0
 def test_loading_using(self):
     # Load db fixtures 1 and 2. These will load using the 'default' database identifier explicitly
     management.call_command("loaddata", "db_fixture_1", verbosity=0, using="default", commit=False)
     management.call_command("loaddata", "db_fixture_2", verbosity=0, using="default", commit=False)
     self.assertQuerysetEqual(
         Article.objects.all(),
         ["<Article: Who needs more than one database?>", "<Article: Who needs to use compressed data?>"],
     )
Exemplo n.º 19
0
 def test_templatize_blocktrans_tag(self):
     # ticket #11966
     os.chdir(self.test_dir)
     management.call_command('makemessages', locale=LOCALE, verbosity=0)
     self.assertTrue(os.path.exists(self.PO_FILE))
     with open(self.PO_FILE, 'r') as fp:
         po_contents = fp.read()
         self.assertMsgId('I think that 100%% is more that 50%% of anything.', po_contents)
         self.assertMsgId('I think that 100%% is more that 50%% of %(obj)s.', po_contents)
         self.assertMsgId("Blocktrans extraction shouldn't double escape this: %%, a=%(a)s", po_contents)
Exemplo n.º 20
0
    def test_syncdb(self):
        with transaction.commit_manually():
            Book.objects.all().delete()

            management.call_command(
                'syncdb',
                verbosity=0,
                load_initial_data=False
            )
            self.assertQuerysetEqual(Book.objects.all(), [])
            transaction.rollback()
Exemplo n.º 21
0
 def ticket_11101(self):
     management.call_command(
         'loaddata',
         'thingy.json',
         verbosity=0,
         commit=False
     )
     self.assertEqual(Thingy.objects.count(), 1)
     transaction.rollback()
     self.assertEqual(Thingy.objects.count(), 0)
     transaction.commit()
Exemplo n.º 22
0
 def test_all_files(self):
     """
     Test that findstatic returns all candidate files if run without --first.
     """
     out = six.StringIO()
     call_command('findstatic', 'test/file.txt', verbosity=0, stdout=out)
     out.seek(0)
     lines = [l.strip() for l in out.readlines()]
     self.assertEqual(len(lines), 3)  # three because there is also the "Found <file> here" line
     self.assertIn('project', lines[1])
     self.assertIn('apps', lines[2])
Exemplo n.º 23
0
 def test_loaddata_not_existant_fixture_file(self):
     stdout_output = StringIO()
     management.call_command(
         'loaddata',
         'this_fixture_doesnt_exist',
         verbosity=2,
         commit=False,
         stdout=stdout_output,
     )
     self.assertTrue("No xml fixture 'this_fixture_doesnt_exist' in" in
         stdout_output.getvalue())
Exemplo n.º 24
0
 def test_unimportable_serializer(self):
     """
     Test that failing serializer import raises the proper error
     """
     with self.assertRaisesRegexp(ImportError,
             "No module named unexistent.path"):
         management.call_command(
             'loaddata',
             'bad_fixture1.unkn',
             verbosity=0,
             commit=False,
         )
Exemplo n.º 25
0
 def test_loaddata_raises_error_when_fixture_has_invalid_foreign_key(self):
     """
     Regression for #3615 - Ensure data with nonexistent child key references raises error
     """
     with self.assertRaisesRegexp(IntegrityError,
             "Problem installing fixture"):
         management.call_command(
             'loaddata',
             'forward_ref_bad_data.json',
             verbosity=0,
             commit=False,
         )
Exemplo n.º 26
0
 def test_loaddata_works_when_fixture_has_forward_refs(self):
     """
     Regression for #3615 - Forward references cause fixtures not to load in MySQL (InnoDB)
     """
     management.call_command(
         'loaddata',
         'forward_ref.json',
         verbosity=0,
         commit=False
     )
     self.assertEqual(Book.objects.all()[0].id, 1)
     self.assertEqual(Person.objects.all()[0].id, 4)
Exemplo n.º 27
0
 def test_loaddata_no_fixture_specified(self):
     """
     Regression for #7043 - Error is quickly reported when no fixtures is provided in the command line.
     """
     with self.assertRaisesRegexp(management.CommandError,
             "No database fixture specified. Please provide the path of "
             "at least one fixture in the command line."):
         management.call_command(
             'loaddata',
             verbosity=0,
             commit=False,
         )
Exemplo n.º 28
0
 def test_extraction_error(self):
     os.chdir(self.test_dir)
     shutil.copyfile('./templates/template_with_error.tpl', './templates/template_with_error.html')
     self.assertRaises(SyntaxError, management.call_command, 'makemessages', locale=LOCALE, verbosity=0)
     with self.assertRaises(SyntaxError) as context_manager:
         management.call_command('makemessages', locale=LOCALE, verbosity=0)
     self.assertRegexpMatches(str(context_manager.exception),
             r'Translation blocks must not include other block tags: blocktrans \(file templates[/\\]template_with_error\.html, line 3\)'
         )
     os.remove('./templates/template_with_error.html')
     # Check that the temporary file was cleaned up
     self.assertFalse(os.path.exists('./templates/template_with_error.html.py'))
Exemplo n.º 29
0
 def test_error_message(self):
     """
     (Regression for #9011 - error message is correct)
     """
     with self.assertRaisesRegexp(management.CommandError,
             "^No fixture data found for 'bad_fixture2'. \(File format may be invalid.\)$"):
         management.call_command(
             'loaddata',
             'bad_fixture2',
             'animal',
             verbosity=0,
             commit=False,
         )
Exemplo n.º 30
0
 def test_loaddata_error_message(self):
     """
     Verifies that loading a fixture which contains an invalid object
     outputs an error message which contains the pk of the object
     that triggered the error.
     """
     # MySQL needs a little prodding to reject invalid data.
     # This won't affect other tests because the database connection
     # is closed at the end of each test.
     if connection.vendor == "mysql":
         connection.cursor().execute("SET sql_mode = 'TRADITIONAL'")
     with self.assertRaisesRegexp(IntegrityError, "Could not load fixtures.Article\(pk=1\): .*$"):
         management.call_command("loaddata", "invalid.json", verbosity=0, commit=False)