django.test.utils.override_settings

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

200 Examples 7

Example 1

Project: GAE-Bulk-Mailer
Source File: tests.py
View license
    @skipIf(settings.TIME_ZONE != "America/Chicago" and pytz is None,
            "this test requires pytz when a non-default time zone is set")
    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):
                self.humanize_tester([dt], ['yesterday'], 'naturalday')
        finally:
            humanize.datetime = orig_humanize_datetime

Example 2

Project: GAE-Bulk-Mailer
Source File: testcases.py
View license
    def settings(self, **kwargs):
        """
        A context manager that temporarily sets a setting and reverts
        back to the original value when exiting the context.
        """
        return override_settings(**kwargs)

Example 3

Project: django-celery-email
Source File: tests.py
View license
    def test_sending_mass_email_chunked(self):
        emails = [
            ('mass %i' % i, 'message', '[email protected]', ['[email protected]'])
            for i in range(11)]
        with override_settings(CELERY_EMAIL_CHUNK_SIZE=4):
            [result1, result2, result3] = mail.send_mass_mail(emails)
            self.assertEqual(result1.get(), 4)
            self.assertEqual(result2.get(), 4)
            self.assertEqual(result3.get(), 3)
            self.assertEqual(len(mail.outbox), 11)
            self.assertEqual(mail.outbox[0].subject, 'mass 0')
            self.assertEqual(mail.outbox[1].subject, 'mass 1')

Example 4

Project: djangae
Source File: decorators.py
View license
def without_security_middleware(func):
    """ Decorator for disabling djangae.contrib.security.middleware.AppEngineSecurityMiddleware.
    """
    # This is sometimes useful in tests because if you patch something which is patched by the
    # middleware then usually the test patch is applied first, THEN the middleware runs (usually
    # as the result of a self.client.get/post call), thus applying a decorator to the patched
    # function.  The decorator's nested function stores a reference to the original (patched)
    # function, and so when the patch in the test is undone it is actually still being used because
    # the decorator in the middleware is still referencing it.  This decorator is for
    # use in tests where you are patching one of the things which is patched in the middleware,
    # thus allowing you to avoid the afore-described issue.
    middleware = list(settings.MIDDLEWARE_CLASSES[:])
    middleware.remove('djangae.contrib.security.middleware.AppEngineSecurityMiddleware')
    @wraps(func)
    def _wrapped(*args, **kwargs):
        with override_settings(MIDDLEWARE_CLASSES=middleware):
            return func(*args, **kwargs)
    return _wrapped

Example 5

Project: pretix
Source File: test_middlewares.py
View license
@pytest.mark.django_db
def test_cookie_domain_on_main_domain(env, client):
    with override_settings(SESSION_COOKIE_DOMAIN='example.com'):
        r = client.get('/mrmcd/2015/', HTTP_HOST='example.com')
        assert r.status_code == 200
        assert r.client.cookies['pretix_csrftoken']['domain'] == 'example.com'
        assert r.client.cookies['pretix_session']['domain'] == 'example.com'

Example 6

Project: rapidsms
Source File: utils.py
View license
    def _check_get_handlers(self, *args):
        with override_settings(**self.settings):
            with mock.patch('rapidsms.contrib.handlers.utils.warn') as warn:
                handlers = get_handlers()
        self.assertEqual(set(handlers), set(args))
        # If RAPIDSMS_HANDLERS is not defined, a deprecation warning is issued
        self.assertEqual(warn.called, 'RAPIDSMS_HANDLERS' not in self.settings)

Example 7

Project: rapidsms
Source File: tests.py
View license
    def test_send_async_catches_error(self):
        """send_async should capture sending exceptions properly."""
        backends = {'backend': {'ENGINE': harness.RaisesBackend}}
        with override_settings(INSTALLED_BACKENDS=backends):
            try:
                send_async("backend", "1234", "hello", ["1112223333"], {})
            except:
                self.fail("Sending exceptions should be caught within task")

Example 8

Project: rapidsms
Source File: tests.py
View license
    def test_all_transmissions_set_to_E_if_backend_sending_error(self):
        error_backend = RaisesBackend(self.get_router(), 'error_backend')
        self.backends['error_backend'] = {'ENGINE': RaisesBackend}
        dbm, t1, t2 = self.create_trans(s1='Q', s2='Q', backend=error_backend.model)
        both_transmisssion_sets = list(t1.values_list('id', flat=True)) + list(t2.values_list('id', flat=True))
        with override_settings(INSTALLED_BACKENDS=self.backends):
            with self.assertRaises(MessageSendingError):
                send_transmissions(error_backend.model.pk, dbm.pk, both_transmisssion_sets)
        errored = Transmission.objects.filter(status='E')
        # all of the transmissions should have a status of 'E' now
        self.assertEqual(4, errored.count())

Example 9

Project: rapidsms
Source File: tests.py
View license
    def test_only_failed_transmissions_set_to_E(self):
        # FailedIdentitiesBackend will fail any messages to an identity with a '1' in it.
        # create_trans creates 4 identities, only one of which has a '1' in it, so we expect
        # one failure.
        error_backend = FailedIdentitiesBackend(self.get_router(), 'error_backend')
        self.backends['error_backend'] = {'ENGINE': FailedIdentitiesBackend}
        dbm, t1, t2 = self.create_trans(s1='Q', s2='Q', backend=error_backend.model)
        both_transmisssion_sets = list(t1.values_list('id', flat=True)) + list(t2.values_list('id', flat=True))
        with override_settings(INSTALLED_BACKENDS=self.backends):
            with self.assertRaises(MessageSendingError):
                send_transmissions(error_backend.model.pk, dbm.pk, both_transmisssion_sets)
        errored = Transmission.objects.filter(status='E')
        # only 1 of the transmissions should have a status of 'E' now
        self.assertEqual(1, errored.count())

Example 10

Project: rapidsms
Source File: test_api.py
View license
    def test_get_router(self):
        """Test exceptions for bad input given to get_router()"""
        bad_module_router = 'rapidsms.tests.router.bad_module.MockRouter'
        bad_class_router = 'rapidsms.tests.router.test_base.BadClassName'
        good_mock_router = 'rapidsms.router.test_api.MockRouter'
        with override_settings(RAPIDSMS_ROUTER=bad_module_router):
                self.assertRaises(ImproperlyConfigured, get_router)
        with override_settings(RAPIDSMS_ROUTER=bad_class_router):
                self.assertRaises(ImproperlyConfigured, get_router)
        with override_settings(RAPIDSMS_ROUTER=good_mock_router):
                self.assertTrue(isinstance(get_router(), MockRouter))

Example 11

Project: rapidsms
Source File: tests.py
View license
    def test_contact_settings_langauge(self):
        """settings.LANGUAGE_CODE should not override Contact preference."""
        en_conn = self.create_lang_connection('1000000000', 'en')
        with override_settings(LANGUAGE_CODE='es'):
            self.receive('lang-hello', en_conn)
            self.assertEqual(self.outbound[0].text, 'hello')

Example 12

Project: django-twilio
Source File: decorators.py
View license
    def test_override_forgery_protection_off_debug_off(self):
        with override_settings(DJANGO_TWILIO_FORGERY_PROTECTION=False, DEBUG=False):
            request = self.factory.post(
                self.str_uri,
                HTTP_X_TWILIO_SIGNATURE='fake_signature',
            )
            self.assertEquals(str_view(request).status_code, 200)

Example 13

Project: django-twilio
Source File: decorators.py
View license
    def test_override_forgery_protection_off_debug_off_class_view(self):
        with override_settings(DJANGO_TWILIO_FORGERY_PROTECTION=False, DEBUG=False):
            request = self.factory.post(
                self.str_class_uri,
                HTTP_X_TWILIO_SIGNATURE='fake_signature',
            )
            self.assertEquals(StrView.as_view()(request).status_code, 200)

Example 14

Project: django-twilio
Source File: decorators.py
View license
    def test_override_forgery_protection_off_debug_on(self):
        with override_settings(DJANGO_TWILIO_FORGERY_PROTECTION=False, DEBUG=True):
            request = self.factory.post(
                self.str_uri,
                HTTP_X_TWILIO_SIGNATURE='fake_signature',
            )
            self.assertEquals(str_view(request).status_code, 200)

Example 15

Project: django-twilio
Source File: decorators.py
View license
    def test_override_forgery_protection_off_debug_on_class_view(self):
        with override_settings(DJANGO_TWILIO_FORGERY_PROTECTION=False, DEBUG=True):
            request = self.factory.post(
                self.str_class_uri,
                HTTP_X_TWILIO_SIGNATURE='fake_signature',
            )
            self.assertEquals(StrView.as_view()(request).status_code, 200)

Example 16

Project: django-twilio
Source File: decorators.py
View license
    def test_override_forgery_protection_on_debug_off(self):
        with override_settings(DJANGO_TWILIO_FORGERY_PROTECTION=True, DEBUG=False):
            request = self.factory.post(
                self.str_uri,
                HTTP_X_TWILIO_SIGNATURE='fake_signature',
            )
            self.assertEquals(str_view(request).status_code, 403)

Example 17

Project: django-twilio
Source File: decorators.py
View license
    def test_override_forgery_protection_on_debug_off_class_view(self):
        with override_settings(DJANGO_TWILIO_FORGERY_PROTECTION=True, DEBUG=False):
            request = self.factory.post(
                self.str_class_uri,
                HTTP_X_TWILIO_SIGNATURE='fake_signature',
            )
            self.assertEquals(StrView.as_view()(request).status_code, 403)

Example 18

Project: readthedocs.org
Source File: test_resolver.py
View license
    @override_settings(PRODUCTION_DOMAIN='readthedocs.org')
    def test_domain_resolver_subproject(self):
        with override_settings(USE_SUBDOMAIN=False):
            url = resolve_domain(project=self.subproject)
            self.assertEqual(url, 'readthedocs.org')
        with override_settings(USE_SUBDOMAIN=True):
            url = resolve_domain(project=self.subproject)
            self.assertEqual(url, 'pip.readthedocs.org')

Example 19

Project: readthedocs.org
Source File: test_resolver.py
View license
    @override_settings(PRODUCTION_DOMAIN='readthedocs.org')
    def test_domain_resolver_translation(self):
        with override_settings(USE_SUBDOMAIN=False):
            url = resolve_domain(project=self.translation)
            self.assertEqual(url, 'readthedocs.org')
        with override_settings(USE_SUBDOMAIN=True):
            url = resolve_domain(project=self.translation)
            self.assertEqual(url, 'pip.readthedocs.org')

Example 20

Project: readthedocs.org
Source File: test_resolver.py
View license
    @override_settings(PRODUCTION_DOMAIN='readthedocs.org', PUBLIC_DOMAIN='public.readthedocs.org')
    def test_domain_public(self):
        with override_settings(USE_SUBDOMAIN=False):
            url = resolve_domain(project=self.translation)
            self.assertEqual(url, 'readthedocs.org')
        with override_settings(USE_SUBDOMAIN=True):
            url = resolve_domain(project=self.translation)
            self.assertEqual(url, 'pip.public.readthedocs.org')
        # Private overrides domain
        with override_settings(USE_SUBDOMAIN=False):
            url = resolve_domain(project=self.translation, private=True)
            self.assertEqual(url, 'readthedocs.org')
        with override_settings(USE_SUBDOMAIN=True):
            url = resolve_domain(project=self.translation, private=True)
            self.assertEqual(url, 'pip.public.readthedocs.org')

Example 21

Project: readthedocs.org
Source File: test_resolver.py
View license
    @override_settings(PRODUCTION_DOMAIN='readthedocs.org')
    def test_resolver_subproject(self):
        with override_settings(USE_SUBDOMAIN=False):
            url = resolve(project=self.subproject)
            self.assertEqual(url, 'http://readthedocs.org/docs/pip/projects/sub/ja/latest/')
        with override_settings(USE_SUBDOMAIN=True):
            url = resolve(project=self.subproject)
            self.assertEqual(url, 'http://pip.readthedocs.org/projects/sub/ja/latest/')

Example 22

View license
    def test_docs_url_generation(self):
        with override_settings(USE_SUBDOMAIN=False):
            self.assertEqual(self.pip.get_docs_url(),
                             'http://readthedocs.org/docs/pip/')
        with override_settings(USE_SUBDOMAIN=True):
            self.assertEqual(self.pip.get_docs_url(),
                             'http://pip.public.readthedocs.org/')

        self.pip.single_version = False
        with override_settings(USE_SUBDOMAIN=False):
            self.assertEqual(self.pip.get_docs_url(),
                             'http://readthedocs.org/docs/pip/en/latest/')
        with override_settings(USE_SUBDOMAIN=True):
            self.assertEqual(self.pip.get_docs_url(),
                             'http://pip.public.readthedocs.org/en/latest/')

Example 23

Project: readthedocs.org
Source File: test_subprojects.py
View license
    @override_settings(PRODUCTION_DOMAIN='readthedocs.org')
    def test_resolver_subproject_alias(self):
        relation = self.pip.subprojects.first()
        relation.alias = 'sub_alias'
        relation.save()
        with override_settings(USE_SUBDOMAIN=False):
            resp = self.client.get('/docs/pip/projects/sub_alias/')
            self.assertEqual(resp.status_code, 302)
            self.assertEqual(
                resp._headers['location'][1],
                'http://readthedocs.org/docs/pip/projects/sub_alias/ja/latest/'
            )

Example 24

View license
@pytest.mark.django_db(transaction=False)
def test_disable_concurrency_settings(settings):
    with override_settings(CONCURRENCY_ENABLED=False):
        instance1 = SimpleConcurrentModel(username=next(nextname))
        instance1.save()
        refetch(instance1).save()

Example 25

View license
def test_middleware():
    handler = mock.Mock(status_code=409)
    type(handler.return_value).status_code = mock.PropertyMock(return_value=409)

    with override_settings(CONCURRENCY_HANDLER409=handler):
        request = _get_request('needsquoting#')
        r = ConcurrencyMiddleware().process_exception(request, RecordModifiedError(target=SimpleConcurrentModel()))
    assert r.status_code == 409

Example 26

Project: django-security
Source File: tests.py
View license
    def test_setting_change(self):
        with self.settings(
            MIDDLEWARE_CLASSES=(self.MIDDLEWARE_NAME,), R1=123, R2=True
        ):
            response = self.client.get('/home/')
            self.assertEqual(123, response.loaded_settings['R1'])

            with override_settings(R1=456):
                response = self.client.get('/home/')
                self.assertEqual(456, response.loaded_settings['R1'])

            response = self.client.get('/home/')
            self.assertEqual(123, response.loaded_settings['R1'])

Example 27

Project: shuup
Source File: test_telemetry.py
View license
@pytest.mark.django_db
def test_disable(rf):
    with override_settings(SHUUP_TELEMETRY_ENABLED=False):
        _clear_telemetry_submission()
        _backdate_installation_key()
        set_opt_out(False)
        with pytest.raises(TelemetryNotSent) as ei:
            try_send_telemetry(raise_on_error=True, max_age_hours=None)  # Should re-send (if we weren't disabled)
        assert ei.value.code == "disabled"

Example 28

Project: shuup
Source File: test_telemetry.py
View license
@pytest.mark.django_db
def test_graceful_error():
    def thrower(*args, **kwargs):
        raise ValueError("aaaagh")

    with override_settings(SHUUP_TELEMETRY_ENABLED=True):
        with patch.object(requests, "post", thrower) as requestor:
            _clear_telemetry_submission()
            _backdate_installation_key()
            set_opt_out(False)
            assert try_send_telemetry(raise_on_error=True).get("error")

Example 29

Project: shuup
Source File: test_telemetry.py
View license
def test_disabling_telemetry_hides_menu_item(rf):
    request = rf.get("/")
    with override_settings(SHUUP_TELEMETRY_ENABLED=True):
        assert any(me.original_url == "shuup_admin:telemetry" for me in SystemModule().get_menu_entries(request))
    with override_settings(SHUUP_TELEMETRY_ENABLED=False):
        assert not any(me.original_url == "shuup_admin:telemetry" for me in SystemModule().get_menu_entries(request))

Example 30

Project: shuup
Source File: test_telemetry.py
View license
@pytest.mark.django_db
def test_telemetry_is_sent_on_login(rf, admin_user):
    shop = get_default_shop()
    with patch.object(requests, "post", return_value=Response()) as requestor:
        with override_settings(SHUUP_TELEMETRY_ENABLED=True):
            _backdate_installation_key(days=0)  # instance was created today
            request = apply_request_middleware(rf.get("/"), user=admin_user)
            view_func = DashboardView.as_view()
            response = view_func(request)
            sent = get_last_submission_time()

            response = view_func(request)
            assert get_last_submission_time() == sent

            response = view_func(request)
            assert get_last_submission_time() == sent

            assert len(requestor.mock_calls) == 1

Example 31

Project: django-loginas
Source File: tests.py
View license
    def test_custom_permissions_invalid_path(self):
        def assertMessage(message):
            self.assertRaisesExact(
                ImproperlyConfigured(message),
                self.get_target_url
            )
        with override_settings(CAN_LOGIN_AS='loginas.tests.invalid_func'):
            assertMessage(
                "Module loginas.tests does not define a invalid_func function.")
        with override_settings(CAN_LOGIN_AS='loginas.tests.invalid_path.func'):
            assertMessage("Error importing CAN_LOGIN_AS function: loginas.tests.invalid_path")

Example 32

Project: SmartElect
Source File: test_db_utils.py
View license
    def test_postgres_only(self):
        # If db is not postgres, raises exception
        # Note that overriding DATABASES in a test triggers
        # a warning, but I think since we're not actually doing anything
        # in the database while we have it overridden, it's okay.
        # (The code under test just inspects the setting and returns.)
        DATABASES = {
            self.db: {
                'ENGINE': 'elcheaposqldb',
            }
        }
        with override_settings(DATABASES=DATABASES):
            with self.assertRaises(NotImplementedError):
                delete_all(self.db, [])

Example 33

View license
    def test_data_are_saved(self):
        with override_settings(ST_STORES_DATA_DIR=self.temp_dir.name):
            ds_manager = DataStorageManager(self._func_name())
            with ds_manager.save('file.xml') as buffer:
                buffer.write(b'data part 1')
                buffer.write(b'data part 2')

            content = ds_manager.get('file.xml')

        self.assertEqual(content, 'data part 1data part 2')

Example 34

View license
    def test_get_raises_no_revision_for_not_existing_revision(self):
        with override_settings(ST_STORES_DATA_DIR=self.temp_dir.name):
            ds_manager = DataStorageManager(self._func_name())
            with ds_manager.save('file.xml') as buffer:
                buffer.write(b'data part 1')

            with self.assertRaises(DataStorageManager.NoRevision):
                ds_manager.get('file.xml', revision=999)

Example 35

View license
    def test_get_raises_no_file_when_there_is_no_file(self):
        with override_settings(ST_STORES_DATA_DIR=self.temp_dir.name):
            ds_manager = DataStorageManager(self._func_name())
            with ds_manager.save('file.xml') as buffer:
                buffer.write(b'data part 1')

            with self.assertRaises(DataStorageManager.NoFile):
                ds_manager.get('other_file.xml')

Example 36

View license
    def test_get_returns_proper_revision(self):
        with override_settings(ST_STORES_DATA_DIR=self.temp_dir.name):
            ds_manager = DataStorageManager(self._func_name())

            for rev in range(10):
                with ds_manager.save('file.xml') as buffer:
                    buffer.write('file content {}'.format(rev).encode())

                self.assertEqual(ds_manager.last_revision_number(), rev)

            for rev in range(10):
                self.assertEqual(
                    'file content {}'.format(rev),
                    ds_manager.get('file.xml', rev)
                )

            # without rev argument, last revision should be returned
            self.assertEqual('file content 9', ds_manager.get('file.xml'))

Example 37

View license
    def test_last_revision_number_do_not_depend_on_filename(self):
        with override_settings(ST_STORES_DATA_DIR=self.temp_dir.name):
            ds_manager = DataStorageManager(self._func_name())

            with ds_manager.save('file1.xml') as buffer:
                buffer.write(b'data part 1')

            self.assertEqual(ds_manager.last_revision_number(), DataStorageManager.FIRST_REV_NUMBER)

            with ds_manager.save('file2.xml') as buffer:
                buffer.write(b'data part 1')

            self.assertEqual(ds_manager.last_revision_number(), DataStorageManager.FIRST_REV_NUMBER + 1)

Example 38

View license
    def test_last_revision_number_do_not_depend_on_store_name(self):
        with override_settings(ST_STORES_DATA_DIR=self.temp_dir.name):
            ds_manager = DataStorageManager(self._func_name() + '1')
            with ds_manager.save('file1.xml') as buffer:
                buffer.write(b'data part 1')

            self.assertEqual(ds_manager.last_revision_number(), DataStorageManager.FIRST_REV_NUMBER)

            ds_manager = DataStorageManager(self._func_name() + '2')
            with ds_manager.save('file1.xml') as buffer:
                buffer.write(b'data part 1')

            self.assertEqual(ds_manager.last_revision_number(), DataStorageManager.FIRST_REV_NUMBER)

Example 39

Project: splunk-webframework
Source File: tests.py
View license
    @skipIf(settings.TIME_ZONE != "America/Chicago" and pytz is None,
            "this test requires pytz when a non-default time zone is set")
    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):
                self.humanize_tester([dt], ['yesterday'], 'naturalday')
        finally:
            humanize.datetime = orig_humanize_datetime

Example 40

Project: splunk-webframework
Source File: testcases.py
View license
    def settings(self, **kwargs):
        """
        A context manager that temporarily sets a setting and reverts
        back to the original value when exiting the context.
        """
        return override_settings(**kwargs)

Example 41

Project: mezzanine
Source File: tests.py
View license
    def test_page_menu_default(self):
        """
        Test that the settings-defined default value for the ``in_menus``
        field is used, also checking that it doesn't get forced to text,
        but that sequences are made immutable.
        """
        with override_settings(
                PAGE_MENU_TEMPLATES=((8, "a", "a"), (9, "b", "b"))):
            with override_settings(PAGE_MENU_TEMPLATES_DEFAULT=None):
                page_in_all_menus = Page.objects.create()
                self.assertEqual(page_in_all_menus.in_menus, (8, 9))
            with override_settings(PAGE_MENU_TEMPLATES_DEFAULT=tuple()):
                page_not_in_menus = Page.objects.create()
                self.assertEqual(page_not_in_menus.in_menus, tuple())
            with override_settings(PAGE_MENU_TEMPLATES_DEFAULT=[9]):
                page_in_a_menu = Page.objects.create()
                self.assertEqual(page_in_a_menu.in_menus, (9,))

Example 42

Project: django-bulbs
Source File: test_content_api.py
View license
    def test_resolve_custom_content_url(self):
        # Simulate app-specific content URL
        class ContentUrls(object):
            urlpatterns = (bulbs.api.urls.urlpatterns +
                           (url(r"^article/(?P<slug>[\w-]*)-(?P<pk>\d+)$", mock.Mock()),))
        make_content(id=123)
        with override_settings(ROOT_URLCONF=ContentUrls):
            r = self.resolve(url="/article/some-slug-123?one=two")
            self.assertEqual(r.status_code, 200)
            self.assertEqual(123, r.data['id'])

Example 43

Project: django-bulbs
Source File: test_content_api.py
View license
    def test_resolve_custom_content_url_missing_pk(self):
        # Simulate app-specific content URL
        class ContentUrls(object):
            urlpatterns = (bulbs.api.urls.urlpatterns +
                           (url(r"^article/(?P<slug>[\w-]*)$", mock.Mock()),))
        with override_settings(ROOT_URLCONF=ContentUrls):
            self.assertEqual(404, self.resolve(url="/article/some-slug").status_code)

Example 44

Project: RatticWeb
Source File: test_backup.py
View license
    @mock.patch("ratticweb.management.commands.backup.BackupStorage")
    @mock.patch("ratticweb.management.commands.backup.Command.validate_options")
    @mock.patch("ratticweb.management.commands.backup.backup")
    def test_it_validates_options(self, fake_backup, fake_validate_options, FakeBackupStorage):
        backup_dir = mock.Mock(name="backup_dir")
        recipients = mock.Mock(name="recipients")
        FakeBackupStorage.return_value = mock.MagicMock(spec=BackupStorage)
        with override_settings(BACKUP_DIR=backup_dir, BACKUP_RECIPIENTS=recipients):
            call_command("backup")
            fake_validate_options.assert_called_once_with(backup_dir, recipients)

Example 45

Project: RatticWeb
Source File: test_backup.py
View license
    @mock.patch("ratticweb.management.commands.backup.BackupStorage")
    @mock.patch("ratticweb.management.commands.backup.Command.validate_options")
    @mock.patch("ratticweb.management.commands.backup.backup")
    def test_it_calls_backup(self, fake_backup, fake_validate_options, FakeBackupStorage):
        gpg_home = mock.Mock(name="gpg_home")
        backup_dir = mock.Mock(name="backup_dir")
        recipients = mock.Mock(name="recipients")
        default_db = mock.Mock(name="default_db")
        FakeBackupStorage.return_value = mock.MagicMock(spec=BackupStorage)
        with override_settings(BACKUP_DIR=backup_dir, BACKUP_RECIPIENTS=recipients, DATABASES={'default': default_db}, BACKUP_GPG_HOME=gpg_home):
            call_command("backup")
            fake_validate_options.assert_called_once_with(backup_dir, recipients)
            fake_backup.assert_called_once_with(default_db, recipients, backup_dir, gpg_home=gpg_home)

Example 46

Project: RatticWeb
Source File: test_storage.py
View license
    @mock_s3
    def test_complains_if_no_bucket(self):
        with self.assertRaisesRegexp(FailedBackup, "Please first create the s3 bucket.+"):
            with override_settings(BACKUP_S3_BUCKET="bucket_location"):
                self.storage.validate_destination()

        self.assertIs(self.storage.has_storage, False)

Example 47

Project: RatticWeb
Source File: test_storage.py
View license
    @mock.patch("ratticweb.management.commands.storage.S3Connection")
    def test_complains_if_forbidden_bucket(self, FakeS3Connection):
        error = boto.exception.S3ResponseError(403, "Forbidden")
        conn = mock.Mock(name="connection")
        conn.get_bucket.side_effect = error
        FakeS3Connection.return_value = conn

        with self.assertRaises(boto.exception.S3ResponseError):
            with override_settings(BACKUP_S3_BUCKET="blah"):
                self.storage.validate_destination()

        conn.get_bucket.assert_called_once_with("blah")
        self.assertIs(self.storage.has_storage, False)

Example 48

Project: RatticWeb
Source File: test_storage.py
View license
    @mock_s3
    def test_sets_has_storage_if_successfully_finds_bucket(self):
        bucket_name = str(uuid.uuid1())
        conn = boto.connect_s3()
        conn.create_bucket(bucket_name)

        with override_settings(BACKUP_S3_BUCKET=bucket_name):
            self.storage.validate_destination()

        self.assertIs(self.storage.has_storage, True)
        self.assertIs(self.storage.bucket_location, bucket_name)
        self.assertIs(type(self.storage.bucket), boto.s3.bucket.Bucket)

Example 49

Project: RatticWeb
Source File: test_storage.py
View license
    @mock_s3
    def test_send_from_does_send_to_s3_if_has_storage(self):
        contents = """
        Stuff and things
        blah
        """

        bucket_name = str(uuid.uuid1())
        conn = boto.connect_s3()
        conn.create_bucket(bucket_name)

        with a_temp_file(contents) as source:
            with override_settings(BACKUP_S3_BUCKET=bucket_name):
                self.storage.validate_destination()
                self.storage.send_from(source, os.path.dirname(source))

            self.assertEqual(boto.connect_s3().get_bucket(bucket_name).get_key(os.path.basename(source)).get_contents_as_string(), contents)

Example 50

Project: django-subdomains
Source File: tests.py
View license
    def test_url_join(self):
        self.assertEqual(urljoin(self.DOMAIN), 'http://%s' % self.DOMAIN)
        self.assertEqual(urljoin(self.DOMAIN, scheme='https'),
            'https://%s' % self.DOMAIN)

        with override_settings(DEFAULT_URL_SCHEME='https'):
            self.assertEqual(urljoin(self.DOMAIN), 'https://%s' % self.DOMAIN)

        self.assertEqual(urljoin(self.DOMAIN, path='/example/'),
            'http://%s/example/' % self.DOMAIN)