Exemplo n.º 1
0
 def test_create_model4(self):
     """
     Test multiple routers.
     """
     with override_settings(DATABASE_ROUTERS=[AgnosticRouter(), AgnosticRouter()]):
         self._test_create_model("test_mltdb_crmo4", should_run=True)
     with override_settings(DATABASE_ROUTERS=[MigrateNothingRouter(), MigrateEverythingRouter()]):
         self._test_create_model("test_mltdb_crmo4", should_run=False)
     with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter(), MigrateNothingRouter()]):
         self._test_create_model("test_mltdb_crmo4", should_run=True)
Exemplo n.º 2
0
 def test_media_static_dirs_ignored(self):
     """
     Regression test for #23583.
     """
     with override_settings(STATIC_ROOT=os.path.join(self.test_dir, 'static/'),
                            MEDIA_ROOT=os.path.join(self.test_dir, 'media_root/')):
         _, po_contents = self._run_makemessages(domain='djangojs')
         self.assertMsgId("Static content inside app should be included.", po_contents)
         self.assertNotMsgId("Content from STATIC_ROOT should not be included", po_contents)
Exemplo n.º 3
0
 def test_load_module_file(self):
     with override_settings(
             MIGRATION_MODULES={
                 "migrations": "migrations.faulty_migrations.file"
             }):
         loader = MigrationLoader(connection)
         self.assertIn(
             "migrations", loader.unmigrated_apps,
             "App with migrations module file not in unmigrated apps.")
Exemplo n.º 4
0
 def test_load_empty_dir(self):
     with override_settings(
             MIGRATION_MODULES={
                 "migrations": "migrations.faulty_migrations.namespace"
             }):
         loader = MigrationLoader(connection)
         self.assertIn(
             "migrations", loader.unmigrated_apps,
             "App missing __init__.py in migrations module not in unmigrated apps."
         )
Exemplo n.º 5
0
    def test_cursor_executemany_with_pyformat_iterator(self):
        args = iter({'root': i, 'square': i ** 2} for i in range(-3, 2))
        self.create_squares(args, 'pyformat', multiple=True)
        self.assertEqual(Square.objects.count(), 5)

        args = iter({'root': i, 'square': i ** 2} for i in range(3, 7))
        with override_settings(DEBUG=True):
            # same test for DebugCursorWrapper
            self.create_squares(args, 'pyformat', multiple=True)
        self.assertEqual(Square.objects.count(), 9)
Exemplo n.º 6
0
    def test_cursor_executemany_with_iterator(self):
        # Test executemany accepts iterators #10320
        args = iter((i, i ** 2) for i in range(-3, 2))
        self.create_squares_with_executemany(args)
        self.assertEqual(Square.objects.count(), 5)

        args = iter((i, i ** 2) for i in range(3, 7))
        with override_settings(DEBUG=True):
            # same test for DebugCursorWrapper
            self.create_squares_with_executemany(args)
        self.assertEqual(Square.objects.count(), 9)
Exemplo n.º 7
0
 def test_large_batch_mixed_efficiency(self):
     """
     Test inserting a large batch with objects having primary key set
     mixed together with objects without PK set.
     """
     with override_settings(DEBUG=True):
         connection.queries_log.clear()
         TwoFields.objects.bulk_create([
             TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1)
             for i in range(100000, 101000)
         ])
         self.assertLess(len(connection.queries), 10)
Exemplo n.º 8
0
    def test_naturalday_uses_localtime(self):
        # Regression for #18504
        # This is 2012-03-08HT19:30:00-06:00 in America/Chicago
        dt = datetime.datetime(2012, 3, 9, 1, 30, tzinfo=utc)

        orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
        try:
            with override_settings(TIME_ZONE="America/Chicago", USE_TZ=True):
                with translation.override('en'):
                    self.humanize_tester([dt], ['yesterday'], 'naturalday')
        finally:
            humanize.datetime = orig_humanize_datetime
Exemplo n.º 9
0
    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', 'djmodels.po')
            app_de_locale = os.path.join(
                self.test_dir, 'app_with_locale', 'locale', 'de', 'LC_MESSAGES', 'djmodels.po')
            self.assertTrue(os.path.exists(project_de_locale))
            self.assertTrue(os.path.exists(app_de_locale))

            with open(project_de_locale, 'r') as fp:
                po_contents = fp.read()
                self.assertMsgId('This app has no locale directory', po_contents)
                self.assertMsgId('This is a project-level string', po_contents)
            with open(app_de_locale, 'r') as fp:
                po_contents = fp.read()
                self.assertMsgId('This app has a locale directory', po_contents)
Exemplo n.º 10
0
    def _test_run_sql(self, app_label, should_run, hints=None):
        with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter()]):
            project_state = self.set_up_test_model(app_label)

        sql = """
        INSERT INTO {0}_pony (pink, weight) VALUES (1, 3.55);
        INSERT INTO {0}_pony (pink, weight) VALUES (3, 5.0);
        """.format(app_label)

        operation = migrations.RunSQL(sql, hints=hints or {})
        # Test the state alteration does nothing
        new_state = project_state.clone()
        operation.state_forwards(app_label, new_state)
        self.assertEqual(new_state, project_state)
        # Test the database alteration
        self.assertEqual(project_state.apps.get_model(app_label, "Pony").objects.count(), 0)
        with connection.schema_editor() as editor:
            operation.database_forwards(app_label, editor, project_state, new_state)
        Pony = project_state.apps.get_model(app_label, "Pony")
        if should_run:
            self.assertEqual(Pony.objects.count(), 2)
        else:
            self.assertEqual(Pony.objects.count(), 0)
Exemplo n.º 11
0
    def _test_run_python(self, app_label, should_run, hints=None):
        with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter()]):
            project_state = self.set_up_test_model(app_label)

        # Create the operation
        def inner_method(models, schema_editor):
            Pony = models.get_model(app_label, "Pony")
            Pony.objects.create(pink=1, weight=3.55)
            Pony.objects.create(weight=5)

        operation = migrations.RunPython(inner_method, hints=hints or {})
        # Test the state alteration does nothing
        new_state = project_state.clone()
        operation.state_forwards(app_label, new_state)
        self.assertEqual(new_state, project_state)
        # Test the database alteration
        self.assertEqual(project_state.apps.get_model(app_label, "Pony").objects.count(), 0)
        with connection.schema_editor() as editor:
            operation.database_forwards(app_label, editor, project_state, new_state)
        Pony = project_state.apps.get_model(app_label, "Pony")
        if should_run:
            self.assertEqual(Pony.objects.count(), 2)
        else:
            self.assertEqual(Pony.objects.count(), 0)
Exemplo n.º 12
0
    def test_multiple_locales(self):
        with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
            call_command('compilemessages', locale=['hr', 'fr'], stdout=StringIO())

            self.assertTrue(os.path.exists(self.MO_FILE_HR))
            self.assertTrue(os.path.exists(self.MO_FILE_FR))
Exemplo n.º 13
0
 def test_fuzzy_compiling(self):
     with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
         call_command('compilemessages', locale=[self.LOCALE], fuzzy=True, stdout=StringIO())
         with translation.override(self.LOCALE):
             self.assertEqual(gettext('Lenin'), 'Ленин')
             self.assertEqual(gettext('Vodka'), 'Водка')
Exemplo n.º 14
0
 def test_load_import_error(self):
     with override_settings(
             MIGRATION_MODULES={"migrations": "import_error_package"}):
         with self.assertRaises(ImportError):
             MigrationLoader(connection)
Exemplo n.º 15
0
 def test_large_batch_efficiency(self):
     with override_settings(DEBUG=True):
         connection.queries_log.clear()
         TwoFields.objects.bulk_create(
             [TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)])
         self.assertLess(len(connection.queries), 10)
Exemplo n.º 16
0
 def test_get_default_timezone_utc(self):
     with override_settings(USE_TZ=True, TIME_ZONE='UTC'):
         self.assertIs(timezone.get_default_timezone(), timezone.utc)
Exemplo n.º 17
0
 def test_now(self):
     with override_settings(USE_TZ=True):
         self.assertTrue(timezone.is_aware(timezone.now()))
     with override_settings(USE_TZ=False):
         self.assertTrue(timezone.is_naive(timezone.now()))
Exemplo n.º 18
0
 def test_media_static_dirs_ignored(self):
     with override_settings(STATIC_ROOT=os.path.join(self.test_dir, 'static/'),
                            MEDIA_ROOT=os.path.join(self.test_dir, 'media_root/')):
         out, _ = self._run_makemessages()
         self.assertIn("ignoring directory static", out)
         self.assertIn("ignoring directory media_root", out)
Exemplo n.º 19
0
    def test_naturaltime(self):
        class naive(datetime.tzinfo):
            def utcoffset(self, dt):
                return None

        test_list = [
            now,
            now - datetime.timedelta(seconds=1),
            now - datetime.timedelta(seconds=30),
            now - datetime.timedelta(minutes=1, seconds=30),
            now - datetime.timedelta(minutes=2),
            now - datetime.timedelta(hours=1, minutes=30, seconds=30),
            now - datetime.timedelta(hours=23, minutes=50, seconds=50),
            now - datetime.timedelta(days=1),
            now - datetime.timedelta(days=500),
            now + datetime.timedelta(seconds=1),
            now + datetime.timedelta(seconds=30),
            now + datetime.timedelta(minutes=1, seconds=30),
            now + datetime.timedelta(minutes=2),
            now + datetime.timedelta(hours=1, minutes=30, seconds=30),
            now + datetime.timedelta(hours=23, minutes=50, seconds=50),
            now + datetime.timedelta(days=1),
            now + datetime.timedelta(days=2, hours=6),
            now + datetime.timedelta(days=500),
            now.replace(tzinfo=naive()),
            now.replace(tzinfo=utc),
        ]
        result_list = [
            'now',
            'a second ago',
            '30\xa0seconds ago',
            'a minute ago',
            '2\xa0minutes ago',
            'an hour ago',
            '23\xa0hours ago',
            '1\xa0day ago',
            '1\xa0year, 4\xa0months ago',
            'a second from now',
            '30\xa0seconds from now',
            'a minute from now',
            '2\xa0minutes from now',
            'an hour from now',
            '23\xa0hours from now',
            '1\xa0day from now',
            '2\xa0days, 6\xa0hours from now',
            '1\xa0year, 4\xa0months from now',
            'now',
            'now',
        ]
        # Because of the DST change, 2 days and 6 hours after the chosen
        # date in naive arithmetic is only 2 days and 5 hours after in
        # aware arithmetic.
        result_list_with_tz_support = result_list[:]
        assert result_list_with_tz_support[
            -4] == '2\xa0days, 6\xa0hours from now'
        result_list_with_tz_support[-4] == '2\xa0days, 5\xa0hours from now'

        orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
        try:
            with translation.override('en'):
                self.humanize_tester(test_list, result_list, 'naturaltime')
                with override_settings(USE_TZ=True):
                    self.humanize_tester(test_list,
                                         result_list_with_tz_support,
                                         'naturaltime')
        finally:
            humanize.datetime = orig_humanize_datetime