示例#1
0
 def test_makemigrations_merge_dont_output_dependency_operations(self):
     """
     Makes sure that makemigrations --merge does not output any operations
     from apps that don't belong to a given app.
     """
     # Monkeypatch interactive questioner to auto accept
     with mock.patch('django.db.migrations.questioner.input', mock.Mock(return_value='N')):
         out = six.StringIO()
         with mock.patch('django.core.management.color.supports_color', lambda *args: False):
             call_command(
                 "makemigrations", "conflicting_app_with_dependencies",
                 merge=True, interactive=True, stdout=out
             )
         val = out.getvalue().lower()
         self.assertIn('merging conflicting_app_with_dependencies\n', val)
         self.assertIn(
             '  branch 0002_conflicting_second\n'
             '    - create model something\n',
             val
         )
         self.assertIn(
             '  branch 0002_second\n'
             '    - delete model tribble\n'
             '    - remove field silly_field from author\n'
             '    - add field rating to author\n'
             '    - create model book\n',
             val
         )
示例#2
0
    def test_handle_failure(self):
        self.assertFalse(self.queued_sms.error)
        self.vertex_backend.handle_response(self.queued_sms, 200, TEST_INCORRECT_NUMBER_RESPONSE)
        self.assertEqual(self.queued_sms.system_error_message, SMS.ERROR_INVALID_DESTINATION_NUMBER)
        self.assertTrue(self.queued_sms.error)

        with mock.patch('corehq.messaging.smsbackends.vertex.models.notify_exception') as exception_notifier:
            self.queued_sms.error = False
            self.vertex_backend.handle_response(self.queued_sms, 200, TEST_NON_CODE_MESSAGES)
            self.assertEqual(self.queued_sms.system_error_message, SMS.ERROR_TOO_MANY_UNSUCCESSFUL_ATTEMPTS)
            self.assertTrue(self.queued_sms.error)
            exception_notifier.assert_called_once_with(
                None,
                "Error with the Vertex SMS Backend: " + TEST_NON_CODE_MESSAGES
            )

        with mock.patch('corehq.messaging.smsbackends.vertex.models.notify_exception') as exception_notifier:
            self.queued_sms.error = False
            self.vertex_backend.handle_response(self.queued_sms, 200, TEST_FAILURE_RESPONSE)
            self.assertEqual(self.queued_sms.system_error_message, SMS.ERROR_TOO_MANY_UNSUCCESSFUL_ATTEMPTS)
            self.assertTrue(self.queued_sms.error)
            exception_notifier.assert_called_once_with(
                None,
                "Error with the Vertex SMS Backend: " + TEST_FAILURE_RESPONSE
            )

        with self.assertRaisesMessage(
                VertexBackendException,
                "Unrecognized response from Vertex gateway with {response_status_code} "
                "status code, response {response_text}".format(
                    response_status_code=200,
                    response_text=RANDOM_ERROR_MESSAGE)
        ):
            self.vertex_backend.handle_response(self.queued_sms, 200, RANDOM_ERROR_MESSAGE)
示例#3
0
文件: tests.py 项目: jibaku/django
 def test_serialization(self):
     tested_connections = db.ConnectionHandler({"default": {"ENGINE": "django.db.backends.dummy"}})
     with mock.patch("django.db.backends.dummy.base.DatabaseWrapper.creation_class") as mocked_db_creation:
         with mock.patch("django.test.utils.connections", new=tested_connections):
             self.runner_instance.setup_databases()
     mocked_db_creation.return_value.create_test_db.assert_called_once_with(
         verbosity=0, autoclobber=False, serialize=True, keepdb=False
     )
示例#4
0
    def test_correct_extraction_psycopg2_version(self):
        from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper
        version_path = 'django.db.backends.postgresql_psycopg2.base.Database.__version__'

        with mock.patch(version_path, '2.6.9'):
            self.assertEqual(DatabaseWrapper.psycopg2_version.__get__(self), (2, 6, 9))

        with mock.patch(version_path, '2.5.dev0'):
            self.assertEqual(DatabaseWrapper.psycopg2_version.__get__(self), (2, 5))
示例#5
0
    def test_correct_extraction_psycopg2_version(self):
        from django.db.backends.postgresql.base import psycopg2_version
        version_path = 'django.db.backends.postgresql.base.Database.__version__'

        with mock.patch(version_path, '2.6.9'):
            self.assertEqual(psycopg2_version(), (2, 6, 9))

        with mock.patch(version_path, '2.5.dev0'):
            self.assertEqual(psycopg2_version(), (2, 5))
示例#6
0
 def test_mysql_supports_transactions(self):
     """
     All storage engines except MyISAM support transactions.
     """
     with mock.patch('django.db.connection.features._mysql_storage_engine', 'InnoDB'):
         self.assertTrue(connection.features.supports_transactions)
     del connection.features.supports_transactions
     with mock.patch('django.db.connection.features._mysql_storage_engine', 'MyISAM'):
         self.assertFalse(connection.features.supports_transactions)
     del connection.features.supports_transactions
示例#7
0
文件: tests.py 项目: 01-/django
 def test_serialization(self):
     tested_connections = db.ConnectionHandler({
         'default': {
             'ENGINE': 'django.db.backends.dummy',
         },
     })
     with mock.patch('django.db.backends.dummy.base.DatabaseCreation') as mocked_db_creation:
         with mock.patch('django.test.runner.connections', new=tested_connections):
             self.runner_instance.setup_databases()
     mocked_db_creation.return_value.create_test_db.assert_called_once_with(
         verbosity=0, autoclobber=False, serialize=True, keepdb=False
     )
示例#8
0
 def test_mysql_supports_transactions(self):
     """
     All storage engines except MyISAM support transactions.
     """
     with mock.patch('django.db.connection.features._mysql_storage_engine',
                     'InnoDB'):
         self.assertTrue(connection.features.supports_transactions)
     del connection.features.supports_transactions
     with mock.patch('django.db.connection.features._mysql_storage_engine',
                     'MyISAM'):
         self.assertFalse(connection.features.supports_transactions)
     del connection.features.supports_transactions
示例#9
0
 def test_serialization(self):
     tested_connections = db.ConnectionHandler({
         'default': {
             'ENGINE': 'django.db.backends.dummy',
         },
     })
     with mock.patch('django.db.backends.dummy.base.DatabaseCreation') as mocked_db_creation:
         with mock.patch('django.test.runner.connections', new=tested_connections):
             self.runner_instance.setup_databases()
     mocked_db_creation.return_value.create_test_db.assert_called_once_with(
         0, autoclobber=False, serialize=True, keepdb=False
     )
示例#10
0
文件: tests.py 项目: Runur/django-1
 def test_serialized_off(self):
     tested_connections = db.ConnectionHandler({
         'default': {
             'ENGINE': 'django.db.backends.dummy',
             'TEST': {'SERIALIZE': False},
         },
     })
     with mock.patch('django.db.backends.dummy.base.DatabaseWrapper.creation_class') as mocked_db_creation:
         with mock.patch('django.test.utils.connections', new=tested_connections):
             self.runner_instance.setup_databases()
     mocked_db_creation.return_value.create_test_db.assert_called_once_with(
         verbosity=0, autoclobber=False, serialize=False, keepdb=False
     )
示例#11
0
文件: tests.py 项目: jibaku/django
    def test_setup_aliased_databases(self):
        tested_connections = db.ConnectionHandler(
            {
                "default": {"ENGINE": "django.db.backends.dummy", "NAME": "dbname"},
                "other": {"ENGINE": "django.db.backends.dummy", "NAME": "dbname"},
            }
        )

        with mock.patch("django.db.backends.dummy.base.DatabaseWrapper.creation_class") as mocked_db_creation:
            with mock.patch("django.test.utils.connections", new=tested_connections):
                old_config = self.runner_instance.setup_databases()
                self.runner_instance.teardown_databases(old_config)
        mocked_db_creation.return_value.destroy_test_db.assert_called_once_with("dbname", 0, False)
示例#12
0
 def test_get_queryset(self):
     """
     Checks whether images in the query set are sorted by position
     """
     qs = mock.MagicMock()  # mock object returned by parent's method
     # create order_by method
     qs.order_by = mock.MagicMock(return_value='bar')
     # patch parent class to return the mock
     with mock.patch(
         'django.contrib.contenttypes.admin'
         '.GenericInlineModelAdmin.get_queryset',
         return_value=qs
     ) as get_queryset:
         # call method being tested with the mock ImageAdminInline
         result = admin.ImageAdminInline.get_queryset(
             self.inline_admin,
             'request'
         )
         # check whether the parent's method has been called
         # with the same argument
         get_queryset.assert_called_with('request')
     # check whether the order_by method has been called
     # with the 'position' str as an argument
     qs.order_by.assert_called_with('position')
     # check whether the method returns the result of the 'order_by'
     self.assertEqual(result, 'bar')
示例#13
0
 def test_makemigrations_unspecified_app_with_conflict_merge(self):
     """
     Makes sure that makemigrations does not create a merge for an
     unspecified app even if it has conflicting migrations.
     """
     # Monkeypatch interactive questioner to auto accept
     with mock.patch('django.db.migrations.questioner.input',
                     mock.Mock(return_value='y')):
         out = six.StringIO()
         try:
             with self.temporary_migration_module(
                     app_label="migrated_app") as migration_dir:
                 call_command("makemigrations",
                              "migrated_app",
                              merge=True,
                              interactive=True,
                              stdout=out)
                 merge_file = os.path.join(migration_dir, '0003_merge.py')
                 self.assertFalse(os.path.exists(merge_file))
             self.assertIn("No conflicts detected to merge.",
                           out.getvalue())
         except CommandError:
             self.fail(
                 "Makemigrations fails resolving conflicts in an unspecified app"
             )
示例#14
0
文件: tests.py 项目: 317070/django
    def test_nodb_connection(self):
        """
        Test that the _nodb_connection property fallbacks to the default connection
        database when access to the 'postgres' database is not granted.
        """
        def mocked_connect(self):
            if self.settings_dict['NAME'] is None:
                raise DatabaseError()
            return ''

        nodb_conn = connection._nodb_connection
        self.assertIsNone(nodb_conn.settings_dict['NAME'])

        # Now assume the 'postgres' db isn't available
        del connection._nodb_connection
        with warnings.catch_warnings(record=True) as w:
            with mock.patch('django.db.backends.base.base.BaseDatabaseWrapper.connect',
                            side_effect=mocked_connect, autospec=True):
                nodb_conn = connection._nodb_connection
        del connection._nodb_connection
        self.assertIsNotNone(nodb_conn.settings_dict['NAME'])
        self.assertEqual(nodb_conn.settings_dict['NAME'], settings.DATABASES[DEFAULT_DB_ALIAS]['NAME'])
        # Check a RuntimeWarning nas been emitted
        self.assertEqual(len(w), 1)
        self.assertEqual(w[0].message.__class__, RuntimeWarning)
示例#15
0
    def test_localdate(self):
        naive = datetime.datetime(2015, 1, 1, 0, 0, 1)
        if PY36:
            self.assertEqual(timezone.localdate(naive),
                             datetime.date(2015, 1, 1))
            self.assertEqual(timezone.localdate(naive, timezone=EAT),
                             datetime.date(2015, 1, 1))
        else:
            with self.assertRaisesMessage(
                    ValueError,
                    'astimezone() cannot be applied to a naive datetime'):
                timezone.localdate(naive)
            with self.assertRaisesMessage(
                    ValueError,
                    'astimezone() cannot be applied to a naive datetime'):
                timezone.localdate(naive, timezone=EAT)

        aware = datetime.datetime(2015, 1, 1, 0, 0, 1, tzinfo=ICT)
        self.assertEqual(timezone.localdate(aware, timezone=EAT),
                         datetime.date(2014, 12, 31))
        with timezone.override(EAT):
            self.assertEqual(timezone.localdate(aware),
                             datetime.date(2014, 12, 31))

        with mock.patch('django.utils.timezone.now', return_value=aware):
            self.assertEqual(timezone.localdate(timezone=EAT),
                             datetime.date(2014, 12, 31))
            with timezone.override(EAT):
                self.assertEqual(timezone.localdate(),
                                 datetime.date(2014, 12, 31))
示例#16
0
文件: tests.py 项目: YahooG/python
    def test_nodb_connection(self):
        """
        The _nodb_connection property fallbacks to the default connection
        database when access to the 'postgres' database is not granted.
        """
        def mocked_connect(self):
            if self.settings_dict['NAME'] is None:
                raise DatabaseError()
            return ''

        nodb_conn = connection._nodb_connection
        self.assertIsNone(nodb_conn.settings_dict['NAME'])

        # Now assume the 'postgres' db isn't available
        with warnings.catch_warnings(record=True) as w:
            with mock.patch(
                    'django.db.backends.base.base.BaseDatabaseWrapper.connect',
                    side_effect=mocked_connect,
                    autospec=True):
                warnings.simplefilter('always', RuntimeWarning)
                nodb_conn = connection._nodb_connection
        self.assertIsNotNone(nodb_conn.settings_dict['NAME'])
        self.assertEqual(nodb_conn.settings_dict['NAME'],
                         connection.settings_dict['NAME'])
        # Check a RuntimeWarning has been emitted
        self.assertEqual(len(w), 1)
        self.assertEqual(w[0].message.__class__, RuntimeWarning)
示例#17
0
 def test_deserialize_force_insert(self):
     """Tests that deserialized content can be saved with force_insert as a parameter."""
     serial_str = serializers.serialize(self.serializer_name, [self.a1])
     deserial_obj = list(serializers.deserialize(self.serializer_name, serial_str))[0]
     with mock.patch('django.db.models.Model') as mock_model:
         deserial_obj.save(force_insert=False)
         mock_model.save_base.assert_called_with(deserial_obj.object, raw=True, using=None, force_insert=False)
示例#18
0
    def test_entity_str(self):
        with mock.patch("common.models.BaseModel.save"):
            self.test_object.save()

        actual = self.test_object.__str__()
        expected = "This Object"
        self.assertEqual(expected, actual)
示例#19
0
    def test_readable_plural_name_default_s(self):
        with mock.patch("common.models.BaseModel.save"):
            self.test_object.save()

        actual = self.test_object.readable_plural_name
        expected = "This Objects"
        self.assertEqual(expected, actual)
示例#20
0
 def test_makemigrations_interactive_by_default(self):
     """
     Makes sure that the user is prompted to merge by default if there are
     conflicts and merge is True. Answer negative to differentiate it from
     behavior when --noinput is specified.
     """
     # Monkeypatch interactive questioner to auto reject
     out = six.StringIO()
     with mock.patch('django.db.migrations.questioner.input',
                     mock.Mock(return_value='N')):
         try:
             with self.temporary_migration_module(
                     module="migrations.test_migrations_conflict"
             ) as migration_dir:
                 call_command("makemigrations",
                              "migrations",
                              merge=True,
                              stdout=out)
                 merge_file = os.path.join(migration_dir, '0003_merge.py')
                 # This will fail if interactive is False by default
                 self.assertFalse(os.path.exists(merge_file))
         except CommandError:
             self.fail(
                 "Makemigrations failed while running interactive questioner"
             )
         self.assertNotIn("Created new merge migration", out.getvalue())
示例#21
0
    def test_schema_name_default(self):
        with mock.patch("common.models.BaseModel.save"):
            self.test_object.save()

        actual = self.test_object.schema_name
        expected = "this_object"
        self.assertEqual(expected, actual)
示例#22
0
    def test_transform_noop(self):
        """ Testing `transform` method (SRID match) """
        # transform() should no-op if source & dest SRIDs match,
        # regardless of whether GDAL is available.
        g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
        gt = g.tuple
        g.transform(4326)
        self.assertEqual(g.tuple, gt)
        self.assertEqual(g.srid, 4326)

        g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
        g1 = g.transform(4326, clone=True)
        self.assertEqual(g1.tuple, g.tuple)
        self.assertEqual(g1.srid, 4326)
        self.assertIsNot(g1, g, "Clone didn't happen")

        with mock.patch('django.contrib.gis.gdal.HAS_GDAL', False):
            g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
            gt = g.tuple
            g.transform(4326)
            self.assertEqual(g.tuple, gt)
            self.assertEqual(g.srid, 4326)

            g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
            g1 = g.transform(4326, clone=True)
            self.assertEqual(g1.tuple, g.tuple)
            self.assertEqual(g1.srid, 4326)
            self.assertIsNot(g1, g, "Clone didn't happen")
示例#23
0
 def test_makemigrations_interactive_accept(self):
     """
     Makes sure that makemigrations enters interactive mode and merges properly.
     """
     # Monkeypatch interactive questioner to auto accept
     with mock.patch('django.db.migrations.questioner.input',
                     mock.Mock(return_value='y')):
         out = six.StringIO()
         try:
             with self.temporary_migration_module(
                     module="migrations.test_migrations_conflict"
             ) as migration_dir:
                 call_command("makemigrations",
                              "migrations",
                              merge=True,
                              interactive=True,
                              stdout=out)
                 merge_file = os.path.join(migration_dir, '0003_merge.py')
                 self.assertTrue(os.path.exists(merge_file))
         except CommandError:
             self.fail(
                 "Makemigrations failed while running interactive questioner"
             )
         self.assertIn("Created new merge migration",
                       force_text(out.getvalue()))
示例#24
0
    def test_transform_noop(self):
        """ Testing `transform` method (SRID match) """
        # transform() should no-op if source & dest SRIDs match,
        # regardless of whether GDAL is available.
        g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
        gt = g.tuple
        g.transform(4326)
        self.assertEqual(g.tuple, gt)
        self.assertEqual(g.srid, 4326)

        g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
        g1 = g.transform(4326, clone=True)
        self.assertEqual(g1.tuple, g.tuple)
        self.assertEqual(g1.srid, 4326)
        self.assertIsNot(g1, g, "Clone didn't happen")

        with mock.patch('django.contrib.gis.gdal.HAS_GDAL', False):
            g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
            gt = g.tuple
            g.transform(4326)
            self.assertEqual(g.tuple, gt)
            self.assertEqual(g.srid, 4326)

            g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
            g1 = g.transform(4326, clone=True)
            self.assertEqual(g1.tuple, g.tuple)
            self.assertEqual(g1.srid, 4326)
            self.assertIsNot(g1, g, "Clone didn't happen")
示例#25
0
    def test_showmigrations_list(self):
        """
        Tests --list output of showmigrations command
        """
        out = six.StringIO()
        with mock.patch('django.core.management.color.supports_color', lambda *args: True):
            call_command("showmigrations", format='list', stdout=out, verbosity=0, no_color=False)
        self.assertEqual(
            '\x1b[1mmigrations\n\x1b[0m'
            ' [ ] 0001_initial\n'
            ' [ ] 0002_second\n',
            out.getvalue().lower()
        )

        call_command("migrate", "migrations", "0001", verbosity=0)

        out = six.StringIO()
        # Giving the explicit app_label tests for selective `show_list` in the command
        call_command("showmigrations", "migrations", format='list', stdout=out, verbosity=0, no_color=True)
        self.assertEqual(
            'migrations\n'
            ' [x] 0001_initial\n'
            ' [ ] 0002_second\n',
            out.getvalue().lower()
        )
        # Cleanup by unmigrating everything
        call_command("migrate", "migrations", "zero", verbosity=0)
示例#26
0
 def test_msgfmt_error_including_non_ascii(self):
     # po file contains invalid msgstr content (triggers non-ascii error content).
     mo_file = 'locale/ko/LC_MESSAGES/django.mo'
     self.addCleanup(self.rmfile, os.path.join(self.test_dir, mo_file))
     # Make sure the output of msgfmt is unaffected by the current locale.
     env = os.environ.copy()
     env.update({str('LANG'): str('C')})
     with mock.patch(
             'django.core.management.utils.Popen',
             lambda *args, **kwargs: Popen(*args, env=env, **kwargs)):
         if six.PY2:
             # Various assertRaises on PY2 don't support unicode error messages.
             try:
                 call_command('compilemessages', locale=['ko'], verbosity=0)
             except CommandError as err:
                 self.assertIn("' cannot start a field name",
                               six.text_type(err))
         else:
             cmd = MakeMessagesCommand()
             if cmd.gettext_version < (0, 18, 3):
                 raise unittest.SkipTest(
                     "python-brace-format is a recent gettext addition.")
             with self.assertRaisesMessage(CommandError,
                                           "' cannot start a field name"):
                 call_command('compilemessages', locale=['ko'], verbosity=0)
示例#27
0
 def test_get_formset(self):
     """
     Checks whether the formset has the 'preview_url_pattern'
     attribute containing the URL pattern
     """
     # the mock object returned by parent's method
     formset = mock.MagicMock()
     # patch parent class to return the mock
     with mock.patch(
         'django.contrib.contenttypes.admin'
         '.GenericInlineModelAdmin.get_formset',
         return_value=formset
         # patch the helper function to return known value
     ) as get_formset, mock.patch.object(
         utils,
         'get_admin_new_image_preview_url_pattern',
         return_value='url_pattern'
     ) as get_pattern:
         # call the method being tested with the mock ImageAdminInline
         result = admin.ImageAdminInline.get_formset(
             self.inline_admin,
             'request'
         )
         # check whether parent's method has been called
         # with the same argument
         get_formset.assert_called_with('request', None)
         # check whether the helper function has been called
         get_pattern.assert_called_with()
     # check whether the method returns the result of parent's method
     self.assertEqual(formset, result)
     # check whether the 'preview_url_pattern' of returned object
     # has the correct value
     self.assertEqual(formset.preview_url_pattern, 'url_pattern')
示例#28
0
 def test_deserialize_force_insert(self):
     """Tests that deserialized content can be saved with force_insert as a parameter."""
     serial_str = serializers.serialize(self.serializer_name, [self.a1])
     deserial_obj = list(serializers.deserialize(self.serializer_name, serial_str))[0]
     with mock.patch('django.db.models.Model') as mock_model:
         deserial_obj.save(force_insert=False)
         mock_model.save_base.assert_called_with(deserial_obj.object, raw=True, using=None, force_insert=False)
示例#29
0
    def test_showmigrations_list(self):
        """
        Tests --list output of showmigrations command
        """
        out = six.StringIO()
        with mock.patch('django.core.management.color.supports_color',
                        lambda *args: True):
            call_command("showmigrations",
                         format='list',
                         stdout=out,
                         verbosity=0,
                         no_color=False)
        self.assertEqual(
            '\x1b[1mmigrations\n\x1b[0m'
            ' [ ] 0001_initial\n'
            ' [ ] 0002_second\n',
            out.getvalue().lower())

        call_command("migrate", "migrations", "0001", verbosity=0)

        out = six.StringIO()
        # Giving the explicit app_label tests for selective `show_list` in the command
        call_command("showmigrations",
                     "migrations",
                     format='list',
                     stdout=out,
                     verbosity=0,
                     no_color=True)
        self.assertEqual(
            'migrations\n'
            ' [x] 0001_initial\n'
            ' [ ] 0002_second\n',
            out.getvalue().lower())
        # Cleanup by unmigrating everything
        call_command("migrate", "migrations", "zero", verbosity=0)
示例#30
0
    def test_schema_name_input(self):
        self.test_object.schema_name = "custom_schema_name"
        with mock.patch("common.models.BaseModel.save"):
            self.test_object.save()

        actual = self.test_object.schema_name
        expected = "custom_schema_name"
        self.assertEqual(expected, actual)
示例#31
0
 def test_recovery(self):
     Task.objects.create(name=TEST_TASK_PATH)
     timeout = object()
     with override_settings(ROBUST_WORKER_FAILURE_TIMEOUT=timeout):
         original_sleep = time.sleep
         with mock.patch('time.sleep', side_effect=lambda _: original_sleep(1)) as sleep_mock:
             call_command('robust_worker', runner='robust.runners.Runner', limit=1)
             sleep_mock.assert_has_calls([mock.call(timeout)])
示例#32
0
文件: tests.py 项目: 01-/django
    def test_setup_aliased_databases(self):
        tested_connections = db.ConnectionHandler({
            'default': {
                'ENGINE': 'django.db.backends.dummy',
                'NAME': 'dbname',
            },
            'other': {
                'ENGINE': 'django.db.backends.dummy',
                'NAME': 'dbname',
            }
        })

        with mock.patch('django.db.backends.dummy.base.DatabaseCreation') as mocked_db_creation:
            with mock.patch('django.test.runner.connections', new=tested_connections):
                old_config = self.runner_instance.setup_databases()
                self.runner_instance.teardown_databases(old_config)
        mocked_db_creation.return_value.destroy_test_db.assert_called_once_with('dbname', 0, False)
示例#33
0
 def test_save_sort_value(self):
     """Test BaseModel.save method"""
     test_object = self.test.datum_type2
     with mock.patch("django.db.models.base.Model.save"):
         test_object.save()
     actual = test_object.sort
     expected = 10101
     self.assertEqual(expected, actual)
示例#34
0
 def test_warning_when_overwriting_files_in_staticdir(self):
     stdout = StringIO()
     self.run_collectstatic()
     with mock.patch('builtins.input', side_effect=self.mock_input(stdout)):
         call_command('collectstatic', interactive=True, stdout=stdout)
     output = force_text(stdout.getvalue())
     self.assertIn(self.overwrite_warning_msg, output)
     self.assertNotIn(self.delete_warning_msg, output)
示例#35
0
文件: tests.py 项目: cloudera/hue
 def test_allowed_hosts(self):
     for type_ in (list, tuple):
         allowed_hosts = type_('*')
         with mock.patch('django.test.utils._TestState') as x:
             del x.saved_data
             with self.settings(ALLOWED_HOSTS=allowed_hosts):
                 setup_test_environment()
                 self.assertEqual(settings.ALLOWED_HOSTS, ['*', 'testserver'])
示例#36
0
    def test_calls_error_log_on_error(self):
        response = mock.Mock()
        response.raise_for_status.side_effect = ValueError

        with mock.patch('requests.post', return_value=response):
            with mock.patch.object(self.handler, 'log_error') as log_error:
                self.handler.send({})
                log_error.assert_called()
示例#37
0
    def test_readable_plural_name_input(self):
        self.test_object.readable_plural_name = "custom plural names"
        with mock.patch("common.models.BaseModel.save"):
            self.test_object.save()

        actual = self.test_object.readable_plural_name
        expected = "custom plural names"
        self.assertEqual(expected, actual)
示例#38
0
    def test_calls_success_log_on_success(self):
        response = mock.Mock()
        response.json.return_value = {'status': 'ok'}

        with mock.patch('requests.post', return_value=response):
            with mock.patch.object(self.handler, 'log_success') as log_success:
                self.handler.send({})
                log_success.assert_called()
示例#39
0
    def test_calls_fail_log_on_fail(self):
        response = mock.Mock()
        response.raise_for_status.side_effect = requests.RequestException

        with mock.patch('requests.post', return_value=response):
            with mock.patch.object(self.handler, 'log_fail') as log_fail:
                self.handler.send({})
                log_fail.assert_called()
示例#40
0
    def test_readable_plural_name_default(self):
        test_object = self.test.element_datum_type1
        with mock.patch("common.models.BaseModel.save"):
            test_object.save()

        actual = test_object.readable_plural_name
        expected = "Test Datum Type1s - Names"
        self.assertEqual(expected, actual)
示例#41
0
    def test_schema_name_default(self):
        test_object = self.test.element_datum_type1
        with mock.patch("common.models.BaseModel.save"):
            test_object.save()

        actual = test_object.schema_name
        expected = "test_datum_type1_name"
        self.assertEqual(expected, actual)
示例#42
0
    def test_setup_aliased_databases(self):
        tested_connections = db.ConnectionHandler({
            'default': {
                'ENGINE': 'django.db.backends.dummy',
                'NAME': 'dbname',
            },
            'other': {
                'ENGINE': 'django.db.backends.dummy',
                'NAME': 'dbname',
            }
        })

        with mock.patch('django.db.backends.dummy.base.DatabaseCreation') as mocked_db_creation:
            with mock.patch('django.test.runner.connections', new=tested_connections):
                old_config = self.runner_instance.setup_databases()
                self.runner_instance.teardown_databases(old_config)
        mocked_db_creation.return_value.destroy_test_db.assert_called_once_with('dbname', 0, False)
示例#43
0
文件: tests.py 项目: jibaku/django
 def test_setup_aliased_default_database(self):
     """
     Test that setup_datebases() doesn't fail when 'default' is aliased
     """
     tested_connections = db.ConnectionHandler({"default": {"NAME": "dummy"}, "aliased": {"NAME": "dummy"}})
     with mock.patch("django.test.utils.connections", new=tested_connections):
         runner_instance = DiscoverRunner(verbosity=0)
         old_config = runner_instance.setup_databases()
         runner_instance.teardown_databases(old_config)
示例#44
0
文件: tests.py 项目: runt18/django
    def test_distance_projected(self):
        """
        Test the `Distance` function on projected coordinate systems.
        """
        # The point for La Grange, TX
        lagrange = GEOSGeometry("POINT(-96.876369 29.905320)", 4326)
        # Reference distances in feet and in meters. Got these values from
        # using the provided raw SQL statements.
        #  SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 32140))
        #  FROM distapp_southtexascity;
        m_distances = [
            147075.069813,
            139630.198056,
            140888.552826,
            138809.684197,
            158309.246259,
            212183.594374,
            70870.188967,
            165337.758878,
            139196.085105,
        ]
        #  SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 2278))
        #  FROM distapp_southtexascityft;
        # Oracle 11 thinks this is not a projected coordinate system, so it's
        # not tested.
        ft_distances = [
            482528.79154625,
            458103.408123001,
            462231.860397575,
            455411.438904354,
            519386.252102563,
            696139.009211594,
            232513.278304279,
            542445.630586414,
            456679.155883207,
        ]

        for has_gdal in [False, True]:
            with mock.patch("django.contrib.gis.gdal.HAS_GDAL", has_gdal):
                # Testing using different variations of parameters and using models
                # with different projected coordinate systems.
                dist1 = SouthTexasCity.objects.annotate(distance=Distance("point", lagrange)).order_by("id")
                if oracle:
                    dist_qs = [dist1]
                else:
                    dist2 = SouthTexasCityFt.objects.annotate(distance=Distance("point", lagrange)).order_by("id")
                    dist_qs = [dist1, dist2]

                # Original query done on PostGIS, have to adjust AlmostEqual tolerance
                # for Oracle.
                tol = 2 if oracle else 5

                # Ensuring expected distances are returned for each distance queryset.
                for qs in dist_qs:
                    for i, c in enumerate(qs):
                        self.assertAlmostEqual(m_distances[i], c.distance.m, tol)
                        self.assertAlmostEqual(ft_distances[i], c.distance.survey_ft, tol)
示例#45
0
 def test_allowed_hosts(self):
     for type_ in (list, tuple):
         allowed_hosts = type_('*')
         with mock.patch('django.test.utils._TestState') as x:
             del x.saved_data
             with self.settings(ALLOWED_HOSTS=allowed_hosts):
                 setup_test_environment()
                 self.assertEqual(settings.ALLOWED_HOSTS,
                                  ['*', 'testserver'])
示例#46
0
 def test_migrate_fake_initial(self):
     """
     #24184 - Tests that --fake-initial only works if all tables created in
     the initial migration of an app exists
     """
     # Make sure no tables are created
     self.assertTableNotExists("migrations_author")
     self.assertTableNotExists("migrations_tribble")
     # Run the migrations to 0001 only
     call_command("migrate", "migrations", "0001", verbosity=0)
     # Make sure the right tables exist
     self.assertTableExists("migrations_author")
     self.assertTableExists("migrations_tribble")
     # Fake a roll-back
     call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
     # Make sure the tables still exist
     self.assertTableExists("migrations_author")
     self.assertTableExists("migrations_tribble")
     # Try to run initial migration
     with self.assertRaises(DatabaseError):
         call_command("migrate", "migrations", "0001", verbosity=0)
     # Run initial migration with an explicit --fake-initial
     out = six.StringIO()
     with mock.patch('django.core.management.color.supports_color', lambda *args: False):
         call_command("migrate", "migrations", "0001", fake_initial=True, stdout=out, verbosity=1)
     self.assertIn(
         "migrations.0001_initial... faked",
         out.getvalue().lower()
     )
     # Run migrations all the way
     call_command("migrate", verbosity=0)
     # Make sure the right tables exist
     self.assertTableExists("migrations_author")
     self.assertTableNotExists("migrations_tribble")
     self.assertTableExists("migrations_book")
     # Fake a roll-back
     call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
     # Make sure the tables still exist
     self.assertTableExists("migrations_author")
     self.assertTableNotExists("migrations_tribble")
     self.assertTableExists("migrations_book")
     # Try to run initial migration
     with self.assertRaises(DatabaseError):
         call_command("migrate", "migrations", verbosity=0)
     # Run initial migration with an explicit --fake-initial
     with self.assertRaises(DatabaseError):
         # Fails because "migrations_tribble" does not exist but needs to in
         # order to make --fake-initial work.
         call_command("migrate", "migrations", fake_initial=True, verbosity=0)
     # Fake a apply
     call_command("migrate", "migrations", fake=True, verbosity=0)
     # Unmigrate everything
     call_command("migrate", "migrations", "zero", verbosity=0)
     # Make sure it's all gone
     self.assertTableNotExists("migrations_author")
     self.assertTableNotExists("migrations_tribble")
     self.assertTableNotExists("migrations_book")
 def test_warning_when_overwriting_files_in_staticdir(self):
     stdout = six.StringIO()
     self.run_collectstatic()
     with mock.patch('django.contrib.staticfiles.management.commands.collectstatic.input',
                     side_effect=self.mock_input(stdout)):
         call_command('collectstatic', interactive=True, stdout=stdout)
     output = force_text(stdout.getvalue())
     self.assertIn(self.overwrite_warning_msg, output)
     self.assertNotIn(self.delete_warning_msg, output)
示例#48
0
    def test_makes_post_request_with_data(self):
        response = mock.Mock()
        response.json.return_value = {'status': 'ok', 'phone': 'any phone'}

        with mock.patch('requests.post', return_value=response) as post_mock:
            data = {'test_key': 'test_value'}
            self.handler.send(data)

            post_mock.assert_called_with(self.handler.get_url(), data=data)
示例#49
0
文件: tests.py 项目: jibaku/django
 def test_destroy_test_db_restores_db_name(self):
     tested_connections = db.ConnectionHandler(
         {"default": {"ENGINE": settings.DATABASES[db.DEFAULT_DB_ALIAS]["ENGINE"], "NAME": "xxx_test_database"}}
     )
     # Using the real current name as old_name to not mess with the test suite.
     old_name = settings.DATABASES[db.DEFAULT_DB_ALIAS]["NAME"]
     with mock.patch("django.db.connections", new=tested_connections):
         tested_connections["default"].creation.destroy_test_db(old_name, verbosity=0, keepdb=True)
         self.assertEqual(tested_connections["default"].settings_dict["NAME"], old_name)
示例#50
0
文件: tests.py 项目: jibaku/django
 def test_setup_databases(self):
     """
     Test that setup_databases() doesn't fail with dummy database backend.
     """
     tested_connections = db.ConnectionHandler({})
     with mock.patch("django.test.utils.connections", new=tested_connections):
         runner_instance = DiscoverRunner(verbosity=0)
         old_config = runner_instance.setup_databases()
         runner_instance.teardown_databases(old_config)
示例#51
0
 def test_migrate_fake_initial(self):
     """
     #24184 - Tests that --fake-initial only works if all tables created in
     the initial migration of an app exists
     """
     # Make sure no tables are created
     self.assertTableNotExists("migrations_author")
     self.assertTableNotExists("migrations_tribble")
     # Run the migrations to 0001 only
     call_command("migrate", "migrations", "0001", verbosity=0)
     # Make sure the right tables exist
     self.assertTableExists("migrations_author")
     self.assertTableExists("migrations_tribble")
     # Fake a roll-back
     call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
     # Make sure the tables still exist
     self.assertTableExists("migrations_author")
     self.assertTableExists("migrations_tribble")
     # Try to run initial migration
     with self.assertRaises(DatabaseError):
         call_command("migrate", "migrations", "0001", verbosity=0)
     # Run initial migration with an explicit --fake-initial
     out = six.StringIO()
     with mock.patch('django.core.management.color.supports_color', lambda *args: False):
         call_command("migrate", "migrations", "0001", fake_initial=True, stdout=out, verbosity=1)
     self.assertIn(
         "migrations.0001_initial... faked",
         out.getvalue().lower()
     )
     # Run migrations all the way
     call_command("migrate", verbosity=0)
     # Make sure the right tables exist
     self.assertTableExists("migrations_author")
     self.assertTableNotExists("migrations_tribble")
     self.assertTableExists("migrations_book")
     # Fake a roll-back
     call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
     # Make sure the tables still exist
     self.assertTableExists("migrations_author")
     self.assertTableNotExists("migrations_tribble")
     self.assertTableExists("migrations_book")
     # Try to run initial migration
     with self.assertRaises(DatabaseError):
         call_command("migrate", "migrations", verbosity=0)
     # Run initial migration with an explicit --fake-initial
     with self.assertRaises(DatabaseError):
         # Fails because "migrations_tribble" does not exist but needs to in
         # order to make --fake-initial work.
         call_command("migrate", "migrations", fake_initial=True, verbosity=0)
     # Fake a apply
     call_command("migrate", "migrations", fake=True, verbosity=0)
     # Unmigrate everything
     call_command("migrate", "migrations", "zero", verbosity=0)
     # Make sure it's all gone
     self.assertTableNotExists("migrations_author")
     self.assertTableNotExists("migrations_tribble")
     self.assertTableNotExists("migrations_book")
示例#52
0
    def test_entity_name_input(self):
        test_object = self.test.element_datum_type1
        test_object.entity_name = "custom_entity_name"
        with mock.patch("common.models.BaseModel.save"):
            test_object.save()

        actual = test_object.entity_name
        expected = "custom_entity_name"
        self.assertEqual(expected, actual)
示例#53
0
    def test_readable_plural_name_input(self):
        test_object = self.test.element_datum_type1
        test_object.readable_plural_name = "Custom Readable Plural Name"
        with mock.patch("common.models.BaseModel.save"):
            test_object.save()

        actual = test_object.readable_plural_name
        expected = "Custom Readable Plural Name"
        self.assertEqual(expected, actual)
示例#54
0
 def test_setup_databases(self):
     """
     Test that setup_databases() doesn't fail with dummy database backend.
     """
     tested_connections = db.ConnectionHandler({})
     with mock.patch('django.test.runner.connections', new=tested_connections):
         runner_instance = DiscoverRunner(verbosity=0)
         old_config = runner_instance.setup_databases()
         runner_instance.teardown_databases(old_config)
示例#55
0
    def test_handle_failure(self):
        self.assertFalse(self.queued_sms.error)
        self.vertex_backend.handle_response(self.queued_sms, 200,
                                            TEST_INCORRECT_NUMBER_RESPONSE)
        self.assertEqual(self.queued_sms.system_error_message,
                         SMS.ERROR_INVALID_DESTINATION_NUMBER)
        self.assertTrue(self.queued_sms.error)

        with mock.patch(
                'corehq.messaging.smsbackends.vertex.models.notify_exception'
        ) as exception_notifier:
            self.queued_sms.error = False
            self.vertex_backend.handle_response(self.queued_sms, 200,
                                                TEST_NON_CODE_MESSAGES)
            self.assertEqual(self.queued_sms.system_error_message,
                             SMS.ERROR_TOO_MANY_UNSUCCESSFUL_ATTEMPTS)
            self.assertTrue(self.queued_sms.error)
            exception_notifier.assert_called_once_with(
                None,
                "Error with the Vertex SMS Backend: " + TEST_NON_CODE_MESSAGES)

        with mock.patch(
                'corehq.messaging.smsbackends.vertex.models.notify_exception'
        ) as exception_notifier:
            self.queued_sms.error = False
            self.vertex_backend.handle_response(self.queued_sms, 200,
                                                TEST_FAILURE_RESPONSE)
            self.assertEqual(self.queued_sms.system_error_message,
                             SMS.ERROR_TOO_MANY_UNSUCCESSFUL_ATTEMPTS)
            self.assertTrue(self.queued_sms.error)
            exception_notifier.assert_called_once_with(
                None,
                "Error with the Vertex SMS Backend: " + TEST_FAILURE_RESPONSE)

        with self.assertRaisesMessage(
                VertexBackendException,
                "Unrecognized response from Vertex gateway with {response_status_code} "
                "status code, response {response_text}".format(
                    response_status_code=200,
                    response_text=RANDOM_ERROR_MESSAGE)):
            self.vertex_backend.handle_response(self.queued_sms, 200,
                                                RANDOM_ERROR_MESSAGE)
示例#56
0
 def test_for_update_after_from(self):
     features_class = connections['default'].features.__class__
     attribute_to_patch = "%s.%s.for_update_after_from" % (
         features_class.__module__, features_class.__name__)
     with mock.patch(attribute_to_patch, return_value=True):
         with transaction.atomic():
             self.assertIn(
                 'FOR UPDATE WHERE',
                 str(
                     Person.objects.filter(
                         name='foo').select_for_update().query))
示例#57
0
 def test_user_double_save(self):
     """
     Calling user.save() twice should trigger password_changed() once.
     """
     user = User.objects.create_user(username='******', password='******')
     user.set_password('bar')
     with mock.patch('django.contrib.auth.password_validation.password_changed') as pw_changed:
         user.save()
         self.assertEqual(pw_changed.call_count, 1)
         user.save()
         self.assertEqual(pw_changed.call_count, 1)
示例#58
0
 def test_interactive_true_without_dependent_objects(self):
     """
     interactive mode of remove_stale_contenttypes (the default) should
     delete stale contenttypes even if there aren't any dependent objects.
     """
     with mock.patch(
             'django.contrib.contenttypes.management.commands.remove_stale_contenttypes.input',
             return_value='yes'):
         with captured_stdout() as stdout:
             call_command('remove_stale_contenttypes', verbosity=2)
     self.assertIn("Deleting stale content type", stdout.getvalue())
     self.assertEqual(ContentType.objects.count(), self.before_count)
示例#59
0
 def test_destroy_test_db_restores_db_name(self):
     tested_connections = db.ConnectionHandler({
         'default': {
             'ENGINE': settings.DATABASES[db.DEFAULT_DB_ALIAS]["ENGINE"],
             'NAME': 'xxx_test_database',
         },
     })
     # Using the real current name as old_name to not mess with the test suite.
     old_name = settings.DATABASES[db.DEFAULT_DB_ALIAS]["NAME"]
     with mock.patch('django.db.connections', new=tested_connections):
         tested_connections['default'].creation.destroy_test_db(old_name, verbosity=0, keepdb=True)
         self.assertEqual(tested_connections['default'].settings_dict["NAME"], old_name)