def test_actions_build_selected_post():
    class UserActionPOSTProxy(get_user_model()):
        def get_absolute_url(self):
            return reverse('show_user', kwargs={'pk': self.pk})

        class Meta:
            proxy = True

    user = UserActionPOSTProxy.objects.create(username='******', is_superuser=True)
    NEW_STATIC_ROOT = os.path.join(settings.BASE_DIR, 'test_collectstatic',
                                   'actions', 'build_selected_post')
    rmtree(path=NEW_STATIC_ROOT, ignore_errors=True)

    # this is a bit hoop-jumpy ;/
    url = '%s/index.html' % user.get_absolute_url()[1:]
    writer = URLWriter(data=None)
    with override_settings(BASE_DIR=NEW_STATIC_ROOT):
        storage = writer.storage
    with pytest.raises(IOError):
        storage.open(url)

    madmin = admin.site._registry[get_user_model()]
    request = RequestFactory().post('/', data={'post': '1'})
    request.user = user
    SessionMiddleware().process_request(request=request)
    MessageMiddleware().process_request(request=request)
    with override_settings(BASE_DIR=NEW_STATIC_ROOT):

        do_stuff = build_selected(modeladmin=madmin, request=request,
                                  queryset=UserActionPOSTProxy.objects.all())
        assert do_stuff is None

    url = '%s/index.html' % user.get_absolute_url()[1:]
    data = storage.open(url).readlines()
    assert data == [force_bytes(user.pk)]
示例#2
0
    def test_honor_code(self):
        params = dict(self.minimal_params)

        def assert_honor_code_error(expected_error):
            """
            Assert that requesting account creation results in the expected
            error
            """
            self.assert_error(params, "honor_code", expected_error)

        with override_settings(REGISTRATION_EXTRA_FIELDS={"honor_code": "required"}):
            # Missing
            del params["honor_code"]
            assert_honor_code_error("To enroll, you must follow the honor code.")

            # Empty, invalid
            for honor_code in ["", "false", "not_boolean"]:
                params["honor_code"] = honor_code
                assert_honor_code_error("To enroll, you must follow the honor code.")

            # True
            params["honor_code"] = "tRUe"
            self.assert_success(params)

        with override_settings(REGISTRATION_EXTRA_FIELDS={"honor_code": "optional"}):
            # Missing
            del params["honor_code"]
            # Need to change username/email because user was created above
            params["username"] = "******"
            params["email"] = "*****@*****.**"
            self.assert_success(params)
示例#3
0
    def test_process_view_replace_https_referer(self):
        post_middleware = CorsPostCsrfMiddleware()
        request = Mock(path='/')
        request.method = 'GET'
        request.is_secure = lambda: True
        request.META = {
            'HTTP_REFERER': 'https://foo.google.com/',
            'HTTP_HOST': 'foobar.com',
            'HTTP_ORIGIN': 'https://foo.google.com',
        }
        with override_settings(CORS_URLS_REGEX='^.*$',
                               CORS_ORIGIN_REGEX_WHITELIST='.*google.*',
                               CORS_REPLACE_HTTPS_REFERER=True):
            response = self.middleware.process_view(request, None, None, None)
        self.assertIsNone(response)
        self.assertEquals(request.META['ORIGINAL_HTTP_REFERER'], 'https://foo.google.com/')
        self.assertEquals(request.META['HTTP_REFERER'], 'https://foobar.com/')

        with override_settings(CORS_URLS_REGEX='^.*$', CORS_REPLACE_HTTPS_REFERER=True):
            post_middleware.process_view(request, None, None, None)
        self.assertTrue('ORIGINAL_HTTP_REFERER' not in request.META)
        self.assertEquals(request.META['HTTP_REFERER'], 'https://foo.google.com/')

        with override_settings(CORS_URLS_REGEX='^.*$', CORS_REPLACE_HTTPS_REFERER=True):
            response = post_middleware.process_view(request, None, None, None)
        self.assertIsNone(response)
示例#4
0
    def test_reverse_js_file_save_with_output_path_option(self):
        js_output_path = os.path.join(os.path.dirname(__file__), 'tmp', 'some_path')
        with override_settings(JS_REVERSE_OUTPUT_PATH=js_output_path):
            call_command('collectstatic_js_reverse')

            f = open(os.path.join(js_output_path, 'reverse.js'))
            content1 = f.read()
            if hasattr(content1, 'decode'):
                content1 = content1.decode()

            r2 = self.client.get('/jsreverse/')
            content2 = r2.content
            if hasattr(content2, 'decode'):
                content2 = content2.decode()

            self.assertEqual(len(content1), len(content2), 'Static file don\'t match http response content_1')
            self.assertEqual(content1, content2, 'Static file don\'t match http response content_2')

            # should not raise ImproperlyConfigured exception if STATIC_ROOT is not set
            with override_settings(STATIC_ROOT=None):
                try:
                    call_command('collectstatic_js_reverse')
                except ImproperlyConfigured:
                    self.fail(
                        'should not raise ImproperlyConfigured exception if STATIC_ROOT is not set and JS_REVERSE_OUTPUT_PATH is set')
示例#5
0
 def test_resolver_subproject_subdomain(self):
     with override_settings(USE_SUBDOMAIN=False):
         url = resolve_path(project=self.subproject, filename='index.html')
         self.assertEqual(url, '/docs/pip/projects/sub/ja/latest/')
     with override_settings(USE_SUBDOMAIN=True):
         url = resolve_path(project=self.subproject, filename='index.html')
         self.assertEqual(url, '/projects/sub/ja/latest/')
示例#6
0
    def test_has_access(self, mock_method):
        """ Test get_login_urls() with has_access = False """

        # Make sure user is set on the request
        self.request.user = self.user

        mock_method.return_value = self.test_token

        local_settings = sso_settings.copy()
        local_settings['URL_SSO_IPROVA']['has_access'] = \
            lambda request, service: False

        with override_settings(**local_settings):
            urls = iprova_plugin.get_login_urls(self.request)

        self.assertEquals(urls, {})

        # No request should have been sent out
        self.assertFalse(mock_method.called)

        # Now test with just one service allowed
        local_settings['URL_SSO_IPROVA']['has_access'] = \
            lambda request, service: service == 'iportal'

        with override_settings(**local_settings):
            urls = iprova_plugin.get_login_urls(self.request)

        self.assertEquals(urls, {
            'IPROVA_IPORTAL_SSO_URL':
                'http://intranet.organisation.com/iportal/?token=' + self.test_token,
        })

        mock_method.assert_called_once_with(self.user.username)
示例#7
0
 def test_resolver_private_project(self):
     with override_settings(USE_SUBDOMAIN=False):
         url = resolve(project=self.pip, private=True)
         self.assertEqual(url, 'http://readthedocs.org/docs/pip/en/latest/')
     with override_settings(USE_SUBDOMAIN=True):
         url = resolve(project=self.pip, private=True)
         self.assertEqual(url, 'http://pip.readthedocs.org/en/latest/')
示例#8
0
 def test_missing_signature_returns_forbidden(self):
     with override_settings(DEBUG=False):
         self.assertEqual(self.client.post(self.str_uri).status_code, 403)
         self.assertEqual(self.client.post(self.str_class_uri).status_code, 403)
     with override_settings(DEBUG=True):
         self.assertEqual(self.client.post(self.str_uri).status_code, 200)
         self.assertEqual(self.client.post(self.str_class_uri).status_code, 200)
 def test_display_advertising(self):
     with override_settings(GOOGLE_ANALYTICS_DISPLAY_ADVERTISING=False):
         r = GoogleAnalyticsNode().render(Context())
         self.assertTrue("google-analytics.com/ga.js" in r, r)
     with override_settings(GOOGLE_ANALYTICS_DISPLAY_ADVERTISING=True):
         r = GoogleAnalyticsNode().render(Context())
         self.assertTrue("stats.g.doubleclick.net/dc.js" in r, r)
示例#10
0
    def test_www_domain(self):
        def host(host):
            """
            Returns the subdomain for the provided HTTP Host.
            """
            request = RequestFactory().get('/', HTTP_HOST=host)
            self.middleware.process_request(request)
            return request.subdomain

        self.site.domain = 'www.%s' % self.DOMAIN
        self.site.save()

        with override_settings(REMOVE_WWW_FROM_DOMAIN=False):
            self.assertEqual(host('www.%s' % self.DOMAIN), None)

            # Squelch the subdomain warning for cleaner test output, since we
            # already know that this is an invalid subdomain.
            with warnings.catch_warnings(record=True) as warnlist:
                self.assertEqual(host('www.subdomain.%s' % self.DOMAIN), None)
                self.assertEqual(host('subdomain.%s' % self.DOMAIN), None)

            # Trick pyflakes into not warning us about variable usage.
            del warnlist

            self.assertEqual(host('subdomain.www.%s' % self.DOMAIN),
                'subdomain')
            self.assertEqual(host('www.subdomain.www.%s' % self.DOMAIN),
                'www.subdomain')

        with override_settings(REMOVE_WWW_FROM_DOMAIN=True):
            self.assertEqual(host('www.%s' % self.DOMAIN), 'www')
            self.assertEqual(host('subdomain.%s' % self.DOMAIN), 'subdomain')
            self.assertEqual(host('subdomain.www.%s' % self.DOMAIN),
                'subdomain.www')
示例#11
0
    def resp_info_with_diff_settings(self, url):
        contains_korean_result = []
        response_content_language_result = []

        with override_settings(USE_I18N=True, LANGUAGE_CODE='en-us'):
            resp = self.c.get(url)
            self.assertEqual(resp.status_code, 200)
            contains_korean_result.append(self.response_contains_korean(resp))
            response_content_language_result.append(resp['content-language'])

            resp = self.c.get(url, HTTP_ACCEPT_LANGUAGE='ko')
            self.assertEqual(resp.status_code, 200)
            contains_korean_result.append(self.response_contains_korean(resp))
            response_content_language_result.append(resp['content-language'])

        with override_settings(USE_I18N=False):
            resp = self.c.get(url)
            self.assertEqual(resp.status_code, 200)
            contains_korean_result.append(self.response_contains_korean(resp))
            response_content_language_result.append(resp['content-language'])

            resp = self.c.get(url, HTTP_ACCEPT_LANGUAGE='ko')
            self.assertEqual(resp.status_code, 200)
            contains_korean_result.append(self.response_contains_korean(resp))
            response_content_language_result.append(resp['content-language'])

        return contains_korean_result, response_content_language_result
def test_using_as_postsave():
    class UserPostsaveProxy(get_user_model()):
        def get_absolute_url(self):
            return reverse('show_user', kwargs={'pk': self.pk})

        class Meta:
            proxy = True

    user = UserPostsaveProxy.objects.create(username='******')
    NEW_STATIC_ROOT = os.path.join(settings.BASE_DIR, 'test_collectstatic',
                                   'utils', 'using_as_postsave')
    rmtree(path=NEW_STATIC_ROOT, ignore_errors=True)

    # this is a bit hoop-jumpy ;/
    url = '%s/index.html' % user.get_absolute_url()[1:]
    writer = URLWriter(data=None)
    with override_settings(BASE_DIR=NEW_STATIC_ROOT):
        storage = writer.storage
    with pytest.raises(IOError):
        storage.open(url)

    with override_settings(BASE_DIR=NEW_STATIC_ROOT):
        with tidying_signal(cls=UserPostsaveProxy, signal=post_save):
            user.save()

    url = '%s/index.html' % user.get_absolute_url()[1:]
    data = storage.open(url).readlines()
    assert data == [force_bytes(user.pk)]
示例#13
0
 def test_not_use_sites(self):
     with override_settings(META_USE_SITES=False):
         with self.assertRaises(RuntimeError):
             self.post.as_meta()
     with override_settings(META_USE_SITES=True):
         meta = self.post.as_meta()
         self.assertEqual(meta.url, 'http://example.com/title/')
示例#14
0
 def test_resolver_force_domain(self):
     with override_settings(USE_SUBDOMAIN=False):
         url = resolve_path(project=self.pip, filename='index.html', cname=True)
         self.assertEqual(url, '/en/latest/')
     with override_settings(USE_SUBDOMAIN=True):
         url = resolve_path(project=self.pip, filename='index.html', cname=True)
         self.assertEqual(url, '/en/latest/')
示例#15
0
    def test_force_switch(self):
        """
        If enabled, you can force a switch to be a specific value.
        """
        # Request params
        OVERRIDE = ("__switcher_force=i.am.enabled:False&" +
                    "__switcher_force=i.am.disabled:True")
        request = HttpRequest()
        request.GET = QueryDict(OVERRIDE)
        # Not testing POST
        request.REQUEST = request.GET

        with override_settings(SWITCHER_ALLOW_FORCE=False):
            self.assertIs(switch_is_enabled("i.am.enabled", request), True)
            self.assertIs(switch_is_enabled("i.am.disabled", request), False)

        with override_settings(SWITCHER_ALLOW_FORCE=True):
            self.assertIs(switch_is_enabled("i.am.enabled", request), False)
            self.assertIs(switch_is_enabled("i.am.disabled", request), True)

        # Cookies
        request = HttpRequest()
        request.COOKIES = {
            '__switcher_force_i.am.enabled': 'False',
            '__switcher_force_i.am.disabled': 'True'
        }

        with override_settings(SWITCHER_ALLOW_FORCE=False):
            self.assertIs(switch_is_enabled("i.am.enabled", request), True)
            self.assertIs(switch_is_enabled("i.am.disabled", request), False)

        with override_settings(SWITCHER_ALLOW_FORCE=True):
            self.assertIs(switch_is_enabled("i.am.enabled", request), False)
            self.assertIs(switch_is_enabled("i.am.disabled", request), True)
示例#16
0
 def test_resolver_force_version(self):
     with override_settings(USE_SUBDOMAIN=False):
         url = resolve_path(project=self.pip, filename='index.html', version_slug='foo')
         self.assertEqual(url, '/docs/pip/en/foo/')
     with override_settings(USE_SUBDOMAIN=True):
         url = resolve_path(project=self.pip, filename='index.html', version_slug='foo')
         self.assertEqual(url, '/en/foo/')
示例#17
0
 def test_resolver_force_language(self):
     with override_settings(USE_SUBDOMAIN=False):
         url = resolve_path(project=self.pip, filename='index.html', language='cz')
         self.assertEqual(url, '/docs/pip/cz/latest/')
     with override_settings(USE_SUBDOMAIN=True):
         url = resolve_path(project=self.pip, filename='index.html', language='cz')
         self.assertEqual(url, '/cz/latest/')
示例#18
0
 def test_resolver_no_force_translation_with_version(self):
     with override_settings(USE_SUBDOMAIN=False):
         url = resolve_path(project=self.translation, filename='index.html', language='cz', version_slug='foo')
         self.assertEqual(url, '/docs/pip/ja/foo/')
     with override_settings(USE_SUBDOMAIN=True):
         url = resolve_path(project=self.translation, filename='index.html', language='cz', version_slug='foo')
         self.assertEqual(url, '/ja/foo/')
示例#19
0
 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')
示例#20
0
 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/')
示例#21
0
    def test_sites_contrib(self):

        site_one = Site.objects.get(pk=1)
        site_two = Site(domain='some.com', name='some.com')
        site_two.save()

        site_two_code = Keycode(site=site_two, provider='google', keycode='222')
        site_two_code.save()

        self.assertIn('222', '%s' % site_two_code)

        tpl = '{% load sitemetrics %}{% sitemetrics %}'

        with override_settings(SITE_ID=1):
            self.assertEqual(render_string(tpl), '')  # Test none code for current site

            site_one_code = Keycode(site=site_one, provider='yandex', keycode='111', active=False)
            site_one_code.save()

            self.assertEqual(render_string(tpl), '')  # Test inactive

            site_one_code.active = True
            site_one_code.save()
            self.assertIn('111', render_string(tpl))  # Test active

            self.assertIn('111', render_string(tpl))  # Test cached hit

        with override_settings(SITE_ID=2):
            self.assertIn('222', render_string(tpl))
示例#22
0
 def test_resolver_translation(self):
     with override_settings(USE_SUBDOMAIN=False):
         url = resolve_path(project=self.translation, filename='index.html')
         self.assertEqual(url, '/docs/pip/ja/latest/')
     with override_settings(USE_SUBDOMAIN=True):
         url = resolve_path(project=self.translation, filename='index.html')
         self.assertEqual(url, '/ja/latest/')
示例#23
0
    def test_not_listed_contributor(self):
        self.collection.update(listed=False)

        random_user = user_factory()
        setting_key = 'COLLECTION_FEATURED_THEMES_ID'
        with override_settings(**{setting_key: self.collection.id}):
            self.client.login_api(random_user)
            # Not their collection so not allowed.
            response = self.client.get(self.url)
            assert response.status_code == 403

            self.grant_permission(random_user, 'Collections:Contribute')
            # Now they can access it.
            response = self.client.get(self.url)
            assert response.status_code == 200
            assert response.data['id'] == self.collection.id

        # Double check only the COLLECTION_FEATURED_THEMES_ID is allowed.
        response = self.client.get(self.url)
        assert response.status_code == 403

        # Even on a mozilla-owned collection.
        with override_settings(TASK_USER_ID=random_user.id):
            response = self.client.get(self.url)
        assert response.status_code == 403
示例#24
0
    def test_requestable(self):
        fa = self.findingaid['abbey244']
        fa2 = self.findingaid['bailey807']
        fa3 = self.findingaid['pomerantz890'] # EAD with multiple subareas

        with override_settings(REQUEST_MATERIALS_REPOS = [
            'Manuscript, Archives, and Rare Book Library',
            'Emory University Archives'
            ]):
            self.assertTrue(fa.requestable(),"EAD from Marbl should be able to be requested.")

        # Fail if the REQUEST_MATERIALS_URL is empty
        with override_settings(REQUEST_MATERIALS_URL = ''):
            self.assertFalse(fa.requestable(),"Cannot request EAD if the REQUEST_MATERIALS_URL is not set.")

        # Fail if the REQUEST_MATERIALS_REPOS is empty
        with override_settings(REQUEST_MATERIALS_REPOS = ''):
            self.assertFalse(fa.requestable(),"Cannot request EAD if the REQUEST_MATERIALS_REPOS is not set.")

        # Fail if the requested EAD repo is not set in REQUEST_MATERIALS_REPOS
        with override_settings(REQUEST_MATERIALS_REPOS = [
            'Manuscript, Archives, and Rare Book Library'
            ]):
            self.assertFalse(fa2.requestable(),"EAD from University Archives (not set) shouldn't be able to be requested.")

        # Multiple subareas per one EAD
        with override_settings(REQUEST_MATERIALS_REPOS = [
            'Pitts Theology Library'
            ]):
            self.assertTrue(fa3.requestable(),"Even if there are multiple subareas, an EAD from the set repos should be able to be requested.")
def test_using_as_presave_but_cannot_build():
    class UserPostsaveCannotBuild(get_user_model()):
        def jackfrost_can_build(self):
            return False

        def get_absolute_url(self):
            return reverse('show_user', kwargs={'pk': self.pk})

        class Meta:
            proxy = True

    user = UserPostsaveCannotBuild.objects.create(username='******')  # noqa
    NEW_STATIC_ROOT = os.path.join(settings.BASE_DIR, 'test_collectstatic',
                                   'utils', 'using_as_presave_but_cannot_build')
    rmtree(path=NEW_STATIC_ROOT, ignore_errors=True)

    # this is a bit hoop-jumpy ;/
    url = '%s/index.html' % user.get_absolute_url()[1:]
    writer = URLWriter(data=None)
    with override_settings(BASE_DIR=NEW_STATIC_ROOT):
        storage = writer.storage
    with pytest.raises(IOError):
        storage.open(url)

    with override_settings(BASE_DIR=NEW_STATIC_ROOT):
        with tidying_signal(cls=UserPostsaveCannotBuild, signal=pre_save):
            user.save()

    # Should still error because we didn't build it ...
    with pytest.raises(IOError):
        storage.open(url)
示例#26
0
文件: tests.py 项目: JiangJie/django
    def test_is_extendable(self):
        """
        Tests that the XFrameOptionsMiddleware method that determines the
        X-Frame-Options header value can be overridden based on something in
        the request or response.
        """
        class OtherXFrameOptionsMiddleware(XFrameOptionsMiddleware):
            # This is just an example for testing purposes...
            def get_xframe_options_value(self, request, response):
                if getattr(request, 'sameorigin', False):
                    return 'SAMEORIGIN'
                if getattr(response, 'sameorigin', False):
                    return 'SAMEORIGIN'
                return 'DENY'

        with override_settings(X_FRAME_OPTIONS='DENY'):
            response = HttpResponse()
            response.sameorigin = True
            r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(),
                                                                response)
            self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')

            request = HttpRequest()
            request.sameorigin = True
            r = OtherXFrameOptionsMiddleware().process_response(request,
                                                                HttpResponse())
            self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')

        with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
            r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(),
                                                                HttpResponse())
            self.assertEqual(r['X-Frame-Options'], 'DENY')
示例#27
0
    def test_requires_get_or_post(self):
        client = Client(enforce_csrf_checks=True)
        with override_settings(DEBUG=False):
            self.assertEquals(client.get(self.str_uri).status_code, 403)
            self.assertEquals(client.post(self.str_uri).status_code, 403)
            self.assertEquals(client.head(self.str_uri).status_code, 405)
            self.assertEquals(client.options(self.str_uri).status_code, 405)
            self.assertEquals(client.put(self.str_uri).status_code, 405)
            self.assertEquals(client.delete(self.str_uri).status_code, 405)

            self.assertEquals(client.get(self.str_class_uri).status_code, 403)
            self.assertEquals(client.post(self.str_class_uri).status_code, 403)
            self.assertEquals(client.head(self.str_class_uri).status_code, 405)
            self.assertEquals(client.put(self.str_class_uri).status_code, 405)
            self.assertEquals(client.delete(self.str_class_uri).status_code, 405)

        with override_settings(DEBUG=True):
            self.assertEquals(client.get(self.str_uri).status_code, 200)
            self.assertEquals(client.post(self.str_uri).status_code, 200)
            self.assertEquals(client.head(self.str_uri).status_code, 200)
            self.assertEquals(client.options(self.str_uri).status_code, 200)
            self.assertEquals(client.put(self.str_uri).status_code, 200)
            self.assertEquals(client.delete(self.str_uri).status_code, 200)

            self.assertEquals(client.get(self.str_class_uri).status_code, 200)
            self.assertEquals(client.post(self.str_class_uri).status_code, 200)
            self.assertEquals(client.head(self.str_class_uri).status_code, 200)
示例#28
0
 def test_resolver_translation(self):
     with override_settings(USE_SUBDOMAIN=False):
         url = resolve(project=self.translation)
         self.assertEqual(url, 'http://readthedocs.org/docs/pip/ja/latest/')
     with override_settings(USE_SUBDOMAIN=True):
         url = resolve(project=self.translation)
         self.assertEqual(url, 'http://pip.readthedocs.org/ja/latest/')
示例#29
0
 def test_resolver_domain_object_not_canonical(self):
     self.domain = get(Domain, domain='http://docs.foobar.com', project=self.pip, canonical=False)
     with override_settings(USE_SUBDOMAIN=False):
         url = resolve_path(project=self.pip, filename='')
         self.assertEqual(url, '/docs/pip/en/latest/')
     with override_settings(USE_SUBDOMAIN=True):
         url = resolve_path(project=self.pip, filename='')
         self.assertEqual(url, '/en/latest/')
示例#30
0
 def test_resolver_single_version(self):
     self.pip.single_version = True
     with override_settings(USE_SUBDOMAIN=False):
         url = resolve(project=self.pip)
         self.assertEqual(url, 'http://readthedocs.org/docs/pip/')
     with override_settings(USE_SUBDOMAIN=True):
         url = resolve(project=self.pip)
         self.assertEqual(url, 'http://pip.readthedocs.org/')
示例#31
0
    def test_site_homepage_course_max(self):
        """
        Verify that the number of courses displayed on the homepage honors
        the HOMEPAGE_COURSE_MAX setting.
        """
        @contextmanager
        def homepage_course_max_site_config(limit):
            """Temporarily set the microsite HOMEPAGE_COURSE_MAX setting to desired value."""
            with patch.dict(
                    settings.MICROSITE_CONFIGURATION, {
                        'test_site':
                        dict(
                            settings.MICROSITE_CONFIGURATION['test_site'],
                            HOMEPAGE_COURSE_MAX=limit,
                        )
                    }):
                yield

        def assert_displayed_course_count(response, expected_count):
            """Assert that the number of courses displayed matches the expectation."""
            soup = BeautifulSoup(response.content, 'html.parser')
            courses = soup.find_all(class_='course')
            self.assertEqual(len(courses), expected_count)

        # By default the number of courses on the homepage is not limited.
        # We should see both courses and no link to all courses.
        resp = self.client.get('/', HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
        self.assertEqual(resp.status_code, 200)
        assert_displayed_course_count(resp, 2)
        self.assertNotContains(resp, 'View all Courses')

        # With the limit set to 5, we should still see both courses and no link to all courses.
        with homepage_course_max_site_config(5):
            resp = self.client.get('/',
                                   HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
            self.assertEqual(resp.status_code, 200)
            assert_displayed_course_count(resp, 2)
            self.assertNotContains(resp, 'View all Courses')

        # With the limit set to 2, we should still see both courses and no link to all courses.
        with homepage_course_max_site_config(2):
            resp = self.client.get('/',
                                   HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
            self.assertEqual(resp.status_code, 200)
            assert_displayed_course_count(resp, 2)
            self.assertNotContains(resp, 'View all Courses')

        # With the limit set to 1, we should only see one course.
        # We should also see the link to all courses.
        with homepage_course_max_site_config(1):
            resp = self.client.get('/',
                                   HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
            self.assertEqual(resp.status_code, 200)
            assert_displayed_course_count(resp, 1)
            self.assertContains(resp, 'View all Courses')

        # If no site configuration is set, the limit falls back to settings.HOMEPAGE_COURSE_MAX.
        with override_settings(HOMEPAGE_COURSE_MAX=1):
            resp = self.client.get('/',
                                   HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
            self.assertEqual(resp.status_code, 200)
            assert_displayed_course_count(resp, 1)
            self.assertContains(resp, 'View all Courses')

        # Site configuration takes precedence over settings when both are set.
        with homepage_course_max_site_config(2), override_settings(
                HOMEPAGE_COURSE_MAX=1):
            resp = self.client.get('/',
                                   HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
            self.assertEqual(resp.status_code, 200)
            assert_displayed_course_count(resp, 2)
            self.assertNotContains(resp, 'View all Courses')
示例#32
0
 def setUpClass(cls):
     # Override settings
     cls.settings_override = override_settings(**TEST_SETTINGS)
     cls.settings_override.enable()
     super(LiveServerBase, cls).setUpClass()
示例#33
0
        self.assertContains(response, "url: /userpage/super/")

        # See if this object can be used for queries where a Q() comparing
        # a user can be used with another Q() (in an AND or OR fashion).
        # This simulates what a template tag might do with the user from the
        # context. Note that we don't need to execute a query, just build it.
        #
        # The failure case (bug #12049) on Python 2.4 with a LazyObject-wrapped
        # User is a fatal TypeError: "function() takes at least 2 arguments
        # (0 given)" deep inside deepcopy().
        #
        # Python 2.5 and 2.6 succeeded, but logged internally caught exception
        # spew:
        #
        #    Exception RuntimeError: 'maximum recursion depth exceeded while
        #    calling a Python object' in <type 'exceptions.AttributeError'>
        #    ignored"
        query = Q(user=response.context['user']) & Q(someflag=True)

        # Tests for user equality.  This is hard because User defines
        # equality in a non-duck-typing way
        # See bug #12060
        self.assertEqual(response.context['user'], user)
        self.assertEqual(user, response.context['user'])


AuthContextProcessorTests = override_settings(
    TEMPLATE_DIRS=(os.path.join(os.path.dirname(__file__), 'templates'), ),
    USE_TZ=False,  # required for loading the fixture
)(AuthContextProcessorTests)
 def test_command_detects_schema_generation_mode(self):
     """Switching between CoreAPI & OpenAPI"""
     command = generateschema.Command()
     assert command.get_mode() == generateschema.OPENAPI_MODE
     with override_settings(REST_FRAMEWORK={'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema'}):
         assert command.get_mode() == generateschema.COREAPI_MODE
示例#35
0
文件: views.py 项目: lewmarka/dwitter
    def login(self, password='******'):
        response = self.client.post('/login/', {
            'username': '******',
            'password': password,
        })
        self.assertEqual(response.status_code, 302)
        self.assertTrue(response['Location'].endswith(
            settings.LOGIN_REDIRECT_URL))
        self.assertTrue(SESSION_KEY in self.client.session)

    def assertContainsEscaped(self, response, text, **kwargs):
        return self.assertContains(response, escape(force_unicode(text)),
                                   **kwargs)


AuthViewsTestCase = override_settings(USE_TZ=False)(AuthViewsTestCase)


class AuthViewNamedURLTests(AuthViewsTestCase):
    urls = 'auth.urls'

    def test_named_urls(self):
        "Named URLs should be reversible"
        expected_named_urls = [
            ('login', [], {}),
            ('logout', [], {}),
            ('password_change', [], {}),
            ('password_change_done', [], {}),
            ('password_reset', [], {}),
            ('password_reset_done', [], {}),
            ('password_reset_confirm', [], {
示例#36
0
def use_makefiles(fn):
    return override_settings(USE_SINOLPACK_MAKEFILES=True)((fn))
示例#37
0
class RegressionTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        User = get_user_model()
        editor_credentials = {
            User.USERNAME_FIELD: 'editor',
            'password': '******'
        }
        author_credentials = {
            User.USERNAME_FIELD: 'author',
            'password': '******'
        }
        editor = User.objects.create_user(**editor_credentials)
        author = User.objects.create_user(**author_credentials)
        # We are explicitly setting is_active because of django 1.8
        editor.is_active = True
        editor.save()
        author.is_active = True
        author.save()
        edit_permission = Permission.objects.get(
            codename='change_content',
            content_type__app_label='cfblog'
        )
        publish_permission = Permission.objects.get(
            codename='can_publish',
            content_type__app_label='cfblog'
        )
        author.user_permissions.add(publish_permission)
        editor.user_permissions.add(edit_permission)
        cls.author = author
        cls.editor = editor
        cls.author_client = cls.client_class()
        cls.author_client.login(**author_credentials)
        cls.editor_client = cls.client_class()
        cls.editor_client.login(**editor_credentials)

    def setUp(self):
        cms_page, _ = Content.objects.get_or_create(
            url='/test-golbfc/',
            template="cms_templates/template_1.html",
            category_id=1,
            author=self.author
        )
        self.cms_page = cms_page

    def test_unpublished_url(self):
        self.cms_page.status = Content.DRAFT
        self.cms_page.save()
        response = self.client.get(self.cms_page.url)
        self.assertEqual(response.status_code, 404)
        response = self.editor_client.get(self.cms_page.url)
        self.assertEqual(response.status_code, 200)
        response = self.author_client.get(self.cms_page.url)
        self.assertEqual(response.status_code, 200)

    def test_published_url(self):
        self.cms_page.status = Content.PUBLIC
        self.cms_page.save()
        response = self.client.get(self.cms_page.url)
        self.assertEqual(response.status_code, 200)
        response = self.editor_client.get(self.cms_page.url)
        self.assertEqual(response.status_code, 200)
        response = self.author_client.get(self.cms_page.url)
        self.assertEqual(response.status_code, 200)

    @method_decorator(override_settings(ROOT_URLCONF=()))
    def test_custom_url_conf(self):
        # response should be served by the middleware
        self.test_published_url()
        self.test_unpublished_url()

    def test_editor_cannot_publish(self):
        response1 = self.editor_client.post(
            path='/cms/ajax/save/publish/',
            data={},
            HTTP_X_REQUESTED_WITH='XMLHttpRequest'
        )
        self.assertEqual(response1.status_code, 403)

    def test_author_can_publish(self):
        response1 = self.author_client.post(
            path='/cms/ajax/save/publish/',
            data={},
            HTTP_X_REQUESTED_WITH='XMLHttpRequest'
        )
        self.assertNotEqual(response1.status_code, 403)

    def test_versioning(self):

        content = json.dumps({
            "body": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
            "body_attr": "random data",
            "decrp": "Hi!!",
            "title": "Hello World!!!"
        })
        draft_time = self.cms_page.modified_on + datetime.timedelta(minutes=5)
        data = {
            'auth_data': content,
            'draft_modified': draft_time.isoformat(),
            'cms_page_id': self.cms_page.id
        }

        response1 = self.author_client.post(
            path='/cms/ajax/save/publish/',
            data=data,
            HTTP_X_REQUESTED_WITH='XMLHttpRequest'
        )
        self.assertEqual(response1.status_code, 200)
        self.assertTrue(json.loads(response1.content)['success'])

        draft_time = self.cms_page.modified_on - datetime.timedelta(minutes=5)
        data['draft_modified'] = draft_time.isoformat()
        response2 = self.author_client.post(
            path='/cms/ajax/save/publish/',
            data=data,
            HTTP_X_REQUESTED_WITH='XMLHttpRequest'
        )
        self.assertEqual(response2.status_code, 200)
        self.assertFalse(json.loads(response2.content)['success'])
        self.assertTrue(json.loads(response2.content)['draft_error'])
示例#38
0
 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)
示例#39
0
def no_makefiles(fn):
    return override_settings(USE_SINOLPACK_MAKEFILES=False)(fn)
示例#40
0
def override_cache_settings(BACKEND='django_mysql.cache.MySQLCache',
                            LOCATION='test cache table',
                            **kwargs):
    return override_settings(CACHES=caches_setting_for_tests(BACKEND=BACKEND,
                                                             LOCATION=LOCATION,
                                                             **kwargs), )
from django.test.utils import override_settings
from sis_provisioner.tests import (fdao_pws_override, fdao_hrp_override,
                                   fdao_bridge_override)
from sis_provisioner.tests.account_managers import set_uw_account

user_file_name_override = override_settings(
    BRIDGE_IMPORT_USER_FILENAME="users")


def set_db_records():
    affiemp = set_uw_account("affiemp")

    javerage = set_uw_account("javerage")

    ellen = set_uw_account("ellen")

    staff = set_uw_account("staff")
    staff.set_disable()

    retiree = set_uw_account("retiree")

    tyler = set_uw_account("faculty")

    leftuw = set_uw_account("leftuw")
    leftuw.set_terminate_date()

    testid = set_uw_account("testid")
示例#42
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
示例#43
0
        self.profile = UserProfileWithCustomUser.objects.create(
            user=self.user,
            description='Old description',
            url='http://google.com')
        self.moderation = setup_moderation([UserProfileWithCustomUser])

    def tearDown(self):
        teardown_moderation()
        ModeratedObject.moderated_by = self.copy_m

    # The actual tests are inherited from ModerateTestCase


if VERSION >= (1, 5):
    ModerateCustomUserTestCase = override_settings(
        AUTH_USER_MODEL='tests.CustomUser')(ModerateCustomUserTestCase)


@unittest.skipIf(
    VERSION[:2] < (1, 5),
    "django.utils.six.with_metaclass does not work properly until 1.5")
class ModeratedModelTestCase(TestCase):
    def tearDown(self):
        teardown_moderation()

    def test_moderatedmodel_automatic_registration(self):
        from tests.more_models import MyTestModel
        from tests.more_models import MyTestModelWithoutModerator
        from moderation import moderation

        registered_models = moderation._registered_models
示例#44
0
        """Can customize the template used at render time."""
        widget = forms.TextInput()

        rendered = widget.render('text', 'value', template_name='custom.html')
        self.assertHTMLEqual(rendered, '<input type="custom" name="text" />')

        # Can explicitly give None and will not override
        rendered = widget.render('text', 'value', template_name=None)
        self.assertHTMLEqual(
            rendered, '<input type="text" name="text" value="value" />')


class WidgetRenderingTestWithTemplateStringIfInvalidSet(WidgetRenderingTest):
    pass

WidgetRenderingTestWithTemplateStringIfInvalidSet = override_settings(TEMPLATE_STRING_IF_INVALID=InvalidVariable('INVALID'))(WidgetRenderingTestWithTemplateStringIfInvalidSet)


class WidgetContextTests(TestCase):
    def test_widget_render_method_should_not_clutter_the_context(self):
        '''
        Make sure that the widget rendering pops the context as often as it
        pushed onto it. Otherwise this would lead to leaking variables into
        outer scopes.

        See issue #43 for more information.
        '''
        context = Context({
            'one': 1,
        })
        context_levels = len(context.dicts)
示例#45
0
def setUpModule():
    if settings.USE_PARTITIONED_DATABASE:
        print(
            '============= WARNING: not running test setup because settings.USE_PARTITIONED_DATABASE is True.'
        )
        return

    _call_center_domain_mock = mock.patch(
        'corehq.apps.callcenter.data_source.call_center_data_source_configuration_provider'
    )
    _call_center_domain_mock.start()

    domain = create_domain('icds-cas')
    location_type = LocationType.objects.create(
        domain=domain.name,
        name='block',
    )
    SQLLocation.objects.create(domain=domain.name,
                               name='b1',
                               location_id='b1',
                               location_type=location_type)

    awc_location_type = LocationType.objects.create(
        domain=domain.name,
        name='awc',
    )
    SQLLocation.objects.create(domain=domain.name,
                               name='a7',
                               location_id='a7',
                               location_type=awc_location_type)

    with override_settings(SERVER_ENVIRONMENT='icds'):
        configs = StaticDataSourceConfiguration.by_domain('icds-cas')
        adapters = [get_indicator_adapter(config) for config in configs]

        for adapter in adapters:
            if adapter.config.table_id == 'static-child_health_cases':
                # hack because this is in a migration
                continue
            adapter.build_table()

        engine = connection_manager.get_session_helper(
            settings.ICDS_UCR_TEST_DATABASE_ALIAS).engine
        metadata = sqlalchemy.MetaData(bind=engine)
        metadata.reflect(bind=engine, extend_existing=True)
        path = os.path.join(os.path.dirname(__file__), 'fixtures')
        for file_name in os.listdir(path):
            with open(os.path.join(path, file_name)) as f:
                table_name = FILE_NAME_TO_TABLE_MAPPING[file_name[:-4]]
                table = metadata.tables[table_name]
                postgres_copy.copy_from(f,
                                        table,
                                        engine,
                                        format='csv',
                                        null='',
                                        header=True)

        try:
            move_ucr_data_into_aggregation_tables(datetime(2017, 5, 28),
                                                  intervals=2)
        except AssertionError:
            pass
    _call_center_domain_mock.stop()
示例#46
0
 def base_tearDownClass(cls):
     with override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True):
         FormProcessorTestUtils.delete_all_cases_forms_ledgers()
示例#47
0
def _teardown_ucr_tables():
    with override_settings(SERVER_ENVIRONMENT=TEST_ENVIRONMENT):
        configs = StaticDataSourceConfiguration.by_domain(TEST_DOMAIN)
        adapters = [get_indicator_adapter(config) for config in configs]
        for adapter in adapters:
            adapter.drop_table()
示例#48
0
 def base_setUpClass(cls):
     cls.domain = uuid.uuid4().hex
     with override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True):
         FormProcessorTestUtils.delete_all_cases_forms_ledgers()
         cls.all_doc_ids = cls.create_docs(cls.domain, 9)
         cls.first_doc_id = cls.all_doc_ids[0]
示例#49
0
from django.test.utils import override_settings

from ratticweb.tests.helper import TestData

from cred.tasks import change_queue_emails


class CredEmailTests(TestCase):
    def setUp(self):
        self.data = TestData()

    def test_change_queue_email(self):
        change_queue_emails()

        print mail.outbox[0].body

        salutation = 'Hello ' + self.data.unorm.username + ',\n'
        credlink = 'https://' + settings.HOSTNAME + reverse(
            'cred:detail', args=(self.data.cred.id, ))

        self.assertEqual('RatticDB - Passwords requiring changes',
                         mail.outbox[0].subject)
        self.assertEqual(1, len(mail.outbox[0].to))
        self.assertEqual(self.data.unorm.email, mail.outbox[0].to[0])
        self.assertIn(salutation, mail.outbox[0].body)
        self.assertIn(credlink, mail.outbox[0].body)


CredEmailTests = override_settings(PASSWORD_HASHERS=(
    'django.contrib.auth.hashers.MD5PasswordHasher', ))(CredEmailTests)
示例#50
0
 def func_wrapper(*args, **kwargs):
     with override_settings(CACHALOT_ENABLED=False):
         func(*args, **kwargs)
 def test_is_static_positive_yaml(self):
     with override_settings(STATIC_DATA_SOURCES=[
             self.get_path('sample_static_data_source', 'yaml')
     ]):
         example = list(StaticDataSourceConfiguration.all())[0]
         self.assertTrue(example.is_static)
示例#52
0
 def test_get_complete_on_view_delay_ms(self, delay):
     service = CompletionService(self.user, self.context_key)
     with override_settings(COMPLETION_BY_VIEWING_DELAY_MS=delay):
         self.assertEqual(service.get_complete_on_view_delay_ms(), delay)
 def test_raises_on_no_historical_manager(self):
     with override_settings(DEVICE_ID="10"):
         try:
             TestOfflineModelNoHistoryManager.objects.using("client").create()
         except OfflineHistoricalManagerError:
             self.fail("OfflineHistoricalManagerError unexpectedly raised.")
    def test_with_token_bypass(self, mock_signal, fake):
        user = self.create_user()
        no_digits = 6
        for instruct in ('initial_login', 'skip_token_login', 'bad_signature',
                         'setup_sign_expired', 'signature_expired'):
            user.totpdevice_set.create(name='default',
                                       key=random_hex().decode(),
                                       digits=no_digits)
            device = user.phonedevice_set.create(name='backup',
                                                 number='+31101234567',
                                                 method='sms',
                                                 key=random_hex().decode())

            if instruct in ('skip_token_login', 'signature_expired'):
                # restore cookies cleared by logout()
                # need to ignore flake8 error since this is copying cookies from prev response
                self.client.cookies = response.cookies  # noqa: F821
            if instruct == 'bad_signature':  # corrupt cookie
                self.client.cookies['rememberdevice'].set(
                    'rememberdevice', instruct + ':' + instruct,
                    instruct + ':' + instruct)
            # Backup phones should be listed on the login form
            response = self._post({
                'auth-username': '******',
                'auth-password': '******',
                'login_view-current_step': 'auth'
            })

            if instruct == 'skip_token_login':
                # if login was sent with a valid 'rememberdevice' cookie, it should skip token steps
                self.assertRedirects(response,
                                     resolve_url(settings.LOGIN_REDIRECT_URL))
                remember_cookie = self.client.cookies['rememberdevice']
                self.client.logout()
                self.client.cookies[
                    'rememberdevice'] = remember_cookie  # restore cookies cleared by logout()
                continue
            elif instruct in ('bad_signature', 'signature_expired'):
                self.assertContains(response,
                                    'Send text message to +31 ** *** **67')

            self._phone_validation(mock_signal, fake, device, no_digits)
            if instruct == 'setup_sign_expired':  # setup expired cookie
                with override_settings(TWO_FACTOR_TRUSTED_DAYS=-1):
                    response = self._post({
                        'token-otp_token':
                        totp(device.bin_key),
                        'login_view-current_step':
                        'token',
                        'token-remember':
                        'on'
                    })
            else:
                # Valid token should be accepted.
                response = self._post({
                    'token-otp_token': totp(device.bin_key),
                    'login_view-current_step': 'token',
                    'token-remember': 'on'
                })
            if instruct == 'initial_login':
                self.assertEqual(mail.outbox[0].subject,
                                 'New sign in to your account')

            self.assertRedirects(response,
                                 resolve_url(settings.LOGIN_REDIRECT_URL))
            self.assertEqual(device.persistent_id,
                             self.client.session.get(DEVICE_ID_SESSION_KEY))

            # Check that the signal was fired.
            mock_signal.assert_called_with(sender=mock.ANY,
                                           request=mock.ANY,
                                           user=user,
                                           device=device)
            self.client.logout()
 def test_raises_on_missing_get_by_natural_key(self):
     with override_settings(DEVICE_ID="10"):
         with self.assertRaises(OfflineGetByNaturalKeyMissing):
             AnotherBadTestModel.objects.using("client").create()
 def test_raises_on_missing_uuid_primary_key(self):
     with override_settings(DEVICE_ID="10"):
         with self.assertRaises(OfflineUuidPrimaryKeyMissing):
             TestOfflineModelNoUuid.objects.using("client").create()
示例#57
0
 def test_script_prefix(self):
     script_prefix = '/test/foo/bar/'
     with override_settings(JS_REVERSE_SCRIPT_PREFIX=script_prefix):
         self.assertEqualJSUrlEval(
             'Urls.test_no_url_args()',
             '{0}test_no_url_args/'.format(script_prefix))
 def test_raises_on_wrong_type_of_historical_manager(self):
     with override_settings(DEVICE_ID="10"):
         with self.assertRaises(OfflineHistoricalManagerError):
             YetAnotherBadTestModel.objects.using("client").create()
示例#59
0
 def test_minification(self):
     js_not_minified = smart_str(self.client.post('/jsreverse/').content)
     with override_settings(JS_REVERSE_JS_MINIFY=True):
         js_minified = smart_str(self.client.post('/jsreverse/').content)
         self.assertTrue(len(js_minified) < len(js_not_minified))
 def test_does_not_create_outgoing(self):
     with override_settings(DEVICE_ID="10", ALLOW_MODEL_SERIALIZATION=False):
         test_model = TestModel.objects.using("client").create(f1="erik")
         with self.assertRaises(OutgoingTransaction.DoesNotExist):
             OutgoingTransaction.objects.using("client").get(tx_pk=test_model.pk)