Python django.test.utils.override_settings() Examples
The following are 30
code examples of django.test.utils.override_settings().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.test.utils
, or try the search function
.
Example #1
Source File: template_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_template_rendering_django18_jinja2(instrument, django_elasticapm_client, client): with override_settings( TEMPLATES=TEMPLATES, **middleware_setting(django.VERSION, ["elasticapm.contrib.django.middleware.TracingMiddleware"]) ): client.get(reverse("render-jinja2-template")) client.get(reverse("render-jinja2-template")) client.get(reverse("render-jinja2-template")) transactions = django_elasticapm_client.events[TRANSACTION] assert len(transactions) == 3 spans = django_elasticapm_client.spans_for_transaction(transactions[0]) assert len(spans) == 1, [t["name"] for t in spans] kinds = ["template"] assert set([t["type"] for t in spans]) == set(kinds) assert spans[0]["type"] == "template" assert spans[0]["subtype"] == "jinja2" assert spans[0]["action"] == "render" assert spans[0]["name"] == "jinja2_template.html" assert spans[0]["parent_id"] == transactions[0]["id"]
Example #2
Source File: test_register.py From django-rest-registration with MIT License | 6 votes |
def test_signer_with_different_secret_keys(self): user = self.create_test_user(is_active=False) data_to_sign = {'user_id': user.pk} secrets = [ '#0ka!t#6%28imjz+2t%l(()yu)tg93-1w%$du0*po)*@l+@+4h', 'feb7tjud7m=91$^mrk8dq&nz(0^!6+1xk)%gum#oe%(n)8jic7', ] signatures = [] for secret in secrets: with override_settings( SECRET_KEY=secret): signer = RegisterSigner(data_to_sign) data = signer.get_signed_data() signatures.append(data[signer.SIGNATURE_FIELD]) assert signatures[0] != signatures[1]
Example #3
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_traceparent_header_handling(django_elasticapm_client, client, header_name): with override_settings( **middleware_setting(django.VERSION, ["elasticapm.contrib.django.middleware.TracingMiddleware"]) ), mock.patch( "elasticapm.contrib.django.apps.TraceParent.from_string", wraps=TraceParent.from_string ) as wrapped_from_string: wsgi = lambda s: "HTTP_" + s.upper().replace("-", "_") wsgi_header_name = wsgi(header_name) wsgi_tracestate_name = wsgi(constants.TRACESTATE_HEADER_NAME) kwargs = { wsgi_header_name: "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-03", wsgi_tracestate_name: "foo=bar,baz=bazzinga", } client.get(reverse("elasticapm-no-error"), **kwargs) transaction = django_elasticapm_client.events[TRANSACTION][0] assert transaction["trace_id"] == "0af7651916cd43dd8448eb211c80319c" assert transaction["parent_id"] == "b7ad6b7169203331" assert "foo=bar,baz=bazzinga" in wrapped_from_string.call_args[0]
Example #4
Source File: test_register_email.py From django-rest-registration with MIT License | 6 votes |
def test_signer_with_different_secret_keys(self): email = 'testuser1@example.com' user = self.create_test_user(is_active=False) data_to_sign = { 'user_id': user.pk, 'email': email, } secrets = [ '#0ka!t#6%28imjz+2t%l(()yu)tg93-1w%$du0*po)*@l+@+4h', 'feb7tjud7m=91$^mrk8dq&nz(0^!6+1xk)%gum#oe%(n)8jic7', ] signatures = [] for secret in secrets: with override_settings( SECRET_KEY=secret): signer = RegisterEmailSigner(data_to_sign) data = signer.get_signed_data() signatures.append(data[signer.SIGNATURE_FIELD]) assert signatures[0] != signatures[1]
Example #5
Source File: benchmark.py From django-cachalot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def run(self): for db_alias in settings.DATABASES: self.db_alias = db_alias self.db_vendor = connections[self.db_alias].vendor print('Benchmarking %s…' % self.db_vendor) for cache_alias in settings.CACHES: cache = caches[cache_alias] self.cache_name = cache.__class__.__name__[:-5].lower() with override_settings(CACHALOT_CACHE=cache_alias): self.execute_benchmark() self.df = pd.DataFrame.from_records(self.data) if not os.path.exists(RESULTS_PATH): os.mkdir(RESULTS_PATH) self.df.to_csv(os.path.join(RESULTS_PATH, 'data.csv')) self.xlim = (0, self.df['time'].max() * 1.01) self.output('db') self.output('cache')
Example #6
Source File: benchmark.py From django-cachalot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def benchmark(self, query_str, to_list=True, num_queries=1): # Clears the cache before a single benchmark to ensure the same # conditions across single benchmarks. caches[settings.CACHALOT_CACHE].clear() self.query_name = query_str query_str = 'Test.objects.using(using)' + query_str if to_list: query_str = 'list(%s)' % query_str self.query_function = eval('lambda using: ' + query_str) with override_settings(CACHALOT_ENABLED=False): self.bench_once(CONTEXTS[0], num_queries) self.bench_once(CONTEXTS[1], num_queries, invalidate_before=True) self.bench_once(CONTEXTS[2], 0)
Example #7
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_django_logging_middleware(django_elasticapm_client, client): handler = LoggingHandler() logger = logging.getLogger("logmiddleware") logger.handlers = [] logger.addHandler(handler) logger.level = logging.INFO with override_settings( **middleware_setting(django.VERSION, ["elasticapm.contrib.django.middleware.LogMiddleware"]) ): client.get(reverse("elasticapm-logging")) assert len(django_elasticapm_client.events[ERROR]) == 1 event = django_elasticapm_client.events[ERROR][0] assert "request" in event["context"] assert event["context"]["request"]["url"]["pathname"] == reverse("elasticapm-logging")
Example #8
Source File: test_worker_cache.py From koku with GNU Affero General Public License v3.0 | 6 votes |
def test_get_all_running_tasks(self): """Test that multiple hosts' task lists are combined.""" second_host = "test" first_host_list = [1, 2, 3] second_host_list = [4, 5, 6] expected = first_host_list + second_host_list _cache = WorkerCache() for task in first_host_list: _cache.add_task_to_cache(task) with override_settings(HOSTNAME=second_host): _cache = WorkerCache() for task in second_host_list: _cache.add_task_to_cache(task) self.assertEqual(sorted(_cache.get_all_running_tasks()), sorted(expected))
Example #9
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_stacktrace_filtered_for_elasticapm(client, django_elasticapm_client): with override_settings( **middleware_setting(django.VERSION, ["elasticapm.contrib.django.middleware.TracingMiddleware"]) ): resp = client.get(reverse("render-heavy-template")) assert resp.status_code == 200 transactions = django_elasticapm_client.events[TRANSACTION] assert transactions[0]["result"] == "HTTP 2xx" spans = django_elasticapm_client.events[SPAN] expected_signatures = ["transaction", "list_users.html", "something_expensive"] assert spans[1]["name"] == "list_users.html" # Top frame should be inside django rendering assert spans[1]["stacktrace"][0]["module"].startswith("django.template"), spans[1]["stacktrace"][0]["function"]
Example #10
Source File: test_reset_password.py From django-rest-registration with MIT License | 6 votes |
def test_signer_with_different_secret_keys(self): user = self.create_test_user(is_active=False) data_to_sign = {'user_id': user.pk} secrets = [ '#0ka!t#6%28imjz+2t%l(()yu)tg93-1w%$du0*po)*@l+@+4h', 'feb7tjud7m=91$^mrk8dq&nz(0^!6+1xk)%gum#oe%(n)8jic7', ] signatures = [] for secret in secrets: with override_settings( SECRET_KEY=secret): signer = ResetPasswordSigner(data_to_sign) data = signer.get_signed_data() signatures.append(data[signer.SIGNATURE_FIELD]) assert signatures[0] != signatures[1]
Example #11
Source File: test_sessions.py From django-cassandra-engine with BSD 2-Clause "Simplified" License | 6 votes |
def test_get_expire_at_browser_close(self): # Tests get_expire_at_browser_close with different settings and different # set_expiry calls with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=False): self.session.set_expiry(10) self.assertFalse(self.session.get_expire_at_browser_close()) self.session.set_expiry(0) self.assertTrue(self.session.get_expire_at_browser_close()) self.session.set_expiry(None) self.assertFalse(self.session.get_expire_at_browser_close()) with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=True): self.session.set_expiry(10) self.assertFalse(self.session.get_expire_at_browser_close()) self.session.set_expiry(0) self.assertTrue(self.session.get_expire_at_browser_close()) self.session.set_expiry(None) self.assertTrue(self.session.get_expire_at_browser_close())
Example #12
Source File: test_sessions.py From django-cassandra-engine with BSD 2-Clause "Simplified" License | 6 votes |
def test_actual_expiry(self): # this doesn't work with JSONSerializer (serializing timedelta) with override_settings( SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer' ): self.session = ( self.backend() ) # reinitialize after overriding settings # Regression test for #19200 old_session_key = None new_session_key = None try: self.session['foo'] = 'bar' self.session.set_expiry(-timedelta(seconds=10)) self.session.save() old_session_key = self.session.session_key # With an expiry date in the past, the session expires instantly. new_session = self.backend(self.session.session_key) new_session_key = new_session.session_key self.assertNotIn('foo', new_session) finally: self.session.delete(old_session_key) self.session.delete(new_session_key)
Example #13
Source File: test_openedx_database_mixins.py From opencraft with GNU Affero General Public License v3.0 | 6 votes |
def test_mismatch_warning(self, mock_logger, mock_consul): """ Test that a warning is logged when trying to spawn the default, but a default already and contains mismatching parameters with the given settings. """ urls = ['http://user:pass@doesnotexist.example.com:12345', 'http://user2:pass2@doesnotexist.example.com:12345'] for url in urls: with override_settings(DEFAULT_RABBITMQ_API_URL=url): RabbitMQServer.objects._create_default() mock_logger.warning.assert_called_with( 'RabbitMQServer for %s already exists, and its settings do not match the Django ' 'settings: %s vs %s, %s vs %s, %s vs %s, %s vs %s, %s vs %s, %s vs %s', 'accepts_new_clients', True, 'admin_password', 'pass2', 'admin_username', 'user2', 'api_url', 'http://doesnotexist.example.com:12345', 'instance_host', 'rabbitmq.example.com', 'instance_port', 5671, )
Example #14
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_request_metrics_301_prepend_www(django_elasticapm_client, client): # enable middleware wrapping django_elasticapm_client.config.instrument_django_middleware = True from elasticapm.contrib.django.middleware import TracingMiddleware TracingMiddleware._elasticapm_instrumented = False with override_settings( PREPEND_WWW=True, **middleware_setting( django.VERSION, ["elasticapm.contrib.django.middleware.TracingMiddleware", "django.middleware.common.CommonMiddleware"], ) ): client.get(reverse("elasticapm-no-error")) transactions = django_elasticapm_client.events[TRANSACTION] assert transactions[0]["name"] == "GET django.middleware.common.CommonMiddleware.process_request" assert transactions[0]["result"] == "HTTP 3xx"
Example #15
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_request_metrics_301_append_slash(django_elasticapm_client, client): # enable middleware wrapping django_elasticapm_client.config.instrument_django_middleware = True from elasticapm.contrib.django.middleware import TracingMiddleware TracingMiddleware._elasticapm_instrumented = False with override_settings( APPEND_SLASH=True, **middleware_setting( django.VERSION, ["elasticapm.contrib.django.middleware.TracingMiddleware", "django.middleware.common.CommonMiddleware"], ) ): client.get(reverse("elasticapm-no-error-slash")[:-1]) transactions = django_elasticapm_client.events[TRANSACTION] assert transactions[0]["name"] in ( # django <= 1.8 "GET django.middleware.common.CommonMiddleware.process_request", # django 1.9+ "GET django.middleware.common.CommonMiddleware.process_response", ) assert transactions[0]["result"] == "HTTP 3xx"
Example #16
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_disallowed_hosts_error_django_18(django_elasticapm_client): request = WSGIRequest( environ={ "wsgi.input": compat.BytesIO(), "wsgi.url_scheme": "http", "REQUEST_METHOD": "POST", "SERVER_NAME": "testserver", "SERVER_PORT": "80", "CONTENT_TYPE": "application/json", "ACCEPT": "application/json", } ) with override_settings(ALLOWED_HOSTS=["example.com"]): # this should not raise a DisallowedHost exception django_elasticapm_client.capture("Message", message="foo", request=request) event = django_elasticapm_client.events[ERROR][0] assert event["context"]["request"]["url"] == {"full": "DisallowedHost"}
Example #17
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_disallowed_hosts_error_django_19(django_elasticapm_client): request = WSGIRequest( environ={ "wsgi.input": compat.BytesIO(), "wsgi.url_scheme": "http", "REQUEST_METHOD": "POST", "SERVER_NAME": "testserver", "SERVER_PORT": "80", "CONTENT_TYPE": "application/json", "ACCEPT": "application/json", } ) with override_settings(ALLOWED_HOSTS=["example.com"]): # this should not raise a DisallowedHost exception django_elasticapm_client.capture("Message", message="foo", request=request) event = django_elasticapm_client.events[ERROR][0] assert event["context"]["request"]["url"]["full"] == "http://testserver/"
Example #18
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_404_middleware(django_elasticapm_client, client): with override_settings( **middleware_setting(django.VERSION, ["elasticapm.contrib.django.middleware.Catch404Middleware"]) ): resp = client.get("/non-existant-page") assert resp.status_code == 404 assert len(django_elasticapm_client.events[ERROR]) == 1 event = django_elasticapm_client.events[ERROR][0] assert event["log"]["level"] == "info" assert event["log"]["logger_name"] == "http404" assert "request" in event["context"] request = event["context"]["request"] assert request["url"]["full"] == u"http://testserver/non-existant-page" assert request["method"] == "GET" assert "body" not in request
Example #19
Source File: test_django.py From asap-authentication-python with MIT License | 6 votes |
def test_request_subject_does_need_to_match_issuer_override_settings(self): """ tests that the with_asap decorator can override the ASAP_SUBJECT_SHOULD_MATCH_ISSUER setting. """ token = create_token( issuer='client-app', audience='server-app', key_id='client-app/key01', private_key=self._private_key_pem, subject='not-client-app', ) with override_settings(**dict( self.test_settings, ASAP_SUBJECT_SHOULD_MATCH_ISSUER=False)): response = self.client.get( reverse('subject_does_need_to_match_issuer'), HTTP_AUTHORIZATION=b'Bearer ' + token) self.assertContains( response, 'Unauthorized: Subject and Issuer do not match', status_code=401 )
Example #20
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_view_middleware_exception(django_elasticapm_client, client): with override_settings( **middleware_setting(django.VERSION, ["tests.contrib.django.testapp.middleware.BrokenViewMiddleware"]) ): with pytest.raises(ImportError): client.get(reverse("elasticapm-raise-exc")) assert len(django_elasticapm_client.events[ERROR]) == 1 event = django_elasticapm_client.events[ERROR][0] assert "exception" in event exc = event["exception"] assert exc["type"] == "ImportError" assert exc["message"] == "ImportError: view" assert exc["handled"] is False assert event["culprit"] == "tests.contrib.django.testapp.middleware.process_view"
Example #21
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_response_middlware_exception(django_elasticapm_client, client): if django.VERSION[:2] < (1, 3): return with override_settings( **middleware_setting(django.VERSION, ["tests.contrib.django.testapp.middleware.BrokenResponseMiddleware"]) ): with pytest.raises(ImportError): client.get(reverse("elasticapm-no-error")) assert len(django_elasticapm_client.events[ERROR]) == 1 event = django_elasticapm_client.events[ERROR][0] assert "exception" in event exc = event["exception"] assert exc["type"] == "ImportError" assert exc["message"] == "ImportError: response" assert exc["handled"] is False assert event["culprit"] == "tests.contrib.django.testapp.middleware.process_response"
Example #22
Source File: model_integration_tests.py From django-cache-manager with MIT License | 6 votes |
def test_dummy_cache(self): """ There should not be any query caching when cache backend is dummy. """ CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }, 'django_cache_manager.cache_backend': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } with override_settings(DEBUG=True, CACHES=CACHES): for i in range(5): len(Manufacturer.objects.all()) self.assertEqual(len(connection.queries), 5)
Example #23
Source File: tests.py From Spirit with MIT License | 6 votes |
def test_migration_11(self): # create users with the CI feature off # to replicate pre feature database state with override_settings(ST_CASE_INSENSITIVE_USERNAMES=False): utils.create_user(username='FOO') utils.create_user(username='BaR') utils.create_user(username='baz') # default all nicknames to empty self.assertEqual( UserProfile.objects.all().update(nickname=''), 3) data_migration_11.populate_nickname(apps, None) self.assertEqual( [u.nickname for u in UserProfile.objects.all()], ['FOO', 'BaR', 'baz']) self.assertEqual( [u.username for u in User.objects.all()], ['FOO', 'BaR', 'baz']) data_migration_11.make_usernames_lower(apps, None) self.assertEqual( [u.username for u in User.objects.all()], ['foo', 'bar', 'baz']) self.assertEqual( [u.nickname for u in UserProfile.objects.all()], ['FOO', 'BaR', 'baz'])
Example #24
Source File: tests.py From Spirit with MIT License | 6 votes |
def test_migration_11_make_usernames_lower_integrity_err(self): with override_settings(ST_CASE_INSENSITIVE_USERNAMES=False): utils.create_user(username='FOO') utils.create_user(username='fOo') utils.create_user(username='Foo') utils.create_user(username='bar') utils.create_user(username='bAr') utils.create_user(username='baz') self.assertEqual( [u.username for u in User.objects.all()], ['FOO', 'fOo', 'Foo', 'bar', 'bAr', 'baz']) # transaction is already handled with self.assertRaises(IntegrityError) as cm: data_migration_11.make_usernames_lower(apps, None) self.maxDiff = None self.assertEqual( str(cm.exception), "There are two or more users with similar name but " "different casing, for example: someUser and SomeUser, " "either remove one of them or set the " "`ST_CASE_INSENSITIVE_USERNAMES` setting to False. " "Then run the upgrade/migration again. Any change was reverted. " "Duplicate users are ['FOO', 'fOo', 'Foo', 'bar', 'bAr']")
Example #25
Source File: tests.py From Spirit with MIT License | 6 votes |
def test_migration_11_idempotency(self): """Should be idempotent""" with override_settings(ST_CASE_INSENSITIVE_USERNAMES=False): utils.create_user(username='FOO') self.assertEqual( UserProfile.objects.all().update(nickname=''), 1) data_migration_11.populate_nickname(apps, None) data_migration_11.make_usernames_lower(apps, None) self.assertEqual( [u.username for u in User.objects.all()], ['foo']) self.assertEqual( [u.nickname for u in UserProfile.objects.all()], ['FOO']) data_migration_11.populate_nickname(apps, None) data_migration_11.make_usernames_lower(apps, None) self.assertEqual( [u.username for u in User.objects.all()], ['foo']) self.assertEqual( [u.nickname for u in UserProfile.objects.all()], ['FOO'])
Example #26
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_user_info_with_custom_user_non_string_username(django_elasticapm_client, client): with override_settings(AUTH_USER_MODEL="testapp.MyIntUser"): from django.contrib.auth import get_user_model MyIntUser = get_user_model() user = MyIntUser(my_username=1) user.set_password("admin") user.save() assert client.login(username=1, password="admin") with pytest.raises(Exception): client.get(reverse("elasticapm-raise-exc")) assert len(django_elasticapm_client.events[ERROR]) == 1 event = django_elasticapm_client.events[ERROR][0] assert "user" in event["context"] user_info = event["context"]["user"] assert "username" in user_info assert isinstance(user_info["username"], compat.text_type) assert user_info["username"] == "1"
Example #27
Source File: test_cms_plugins.py From richie with MIT License | 6 votes |
def test_cms_plugins_plaintext_get_form_add(self): """ It should be possible to configure the max_length configuration when adding a plain text plugin to a specific placeholder. """ placeholder = Placeholder.objects.create(slot="first") request = RequestFactory().get(f"/?placeholder_id={placeholder.id:d}") plugin = PlainTextPlugin() max_length = random.randint(1, 5) with override_settings(RICHIE_PLAINTEXT_MAXLENGTH={"first": max_length}): form_class = plugin.get_form(request) form = form_class() body_field = form.fields["body"] self.assertEqual(len(body_field.validators), 2) self.assertEqual(body_field.validators[1].limit_value, max_length)
Example #28
Source File: test_cms_plugins.py From richie with MIT License | 6 votes |
def test_cms_plugins_plaintext_get_form_update(self): """ It should be possible to configure the max_length configuration when updating a plain text plugin on a specific placeholder. """ placeholder = Placeholder.objects.create(slot="first") request = RequestFactory().get("/") plugin = PlainTextPlugin() plain_text = PlainTextFactory(placeholder=placeholder) max_length = random.randint(1, 5) with override_settings(RICHIE_PLAINTEXT_MAXLENGTH={"first": max_length}): form_class = plugin.get_form(request, obj=plain_text) form = form_class() body_field = form.fields["body"] self.assertEqual(len(body_field.validators), 2) self.assertEqual(body_field.validators[1].limit_value, max_length)
Example #29
Source File: test_authentication.py From django-oauth-toolkit-jwt with MIT License | 6 votes |
def test_post_valid_jwt_with_auth(self): now = datetime.utcnow() payload = { 'iss': 'issuer', 'exp': now + timedelta(seconds=100), 'iat': now, 'username': 'temporary', } jwt_value = utils.encode_jwt(payload) with override_settings(JWT_AUTH_DISABLED=False): response = self.client.post( '/jwt_auth/', {'example': 'example'}, HTTP_AUTHORIZATION='JWT {}'.format(jwt_value), content_type='application/json') self.assertEqual(response.status_code, 200) self.assertEqual( json.loads(response.content), {'username': 'temporary'}) with override_settings(JWT_AUTH_DISABLED=True): response = self.client.post( '/jwt_auth/', {'example': 'example'}, HTTP_AUTHORIZATION='JWT {}'.format(jwt_value), content_type='application/json') self.assertEqual(response.status_code, 403)
Example #30
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_user_info_without_auth_middleware(django_elasticapm_client, client): with override_settings( MIDDLEWARE_CLASSES=[ m for m in settings.MIDDLEWARE_CLASSES if m != "django.contrib.auth.middleware.AuthenticationMiddleware" ] ): with pytest.raises(Exception): client.get(reverse("elasticapm-raise-exc")) assert len(django_elasticapm_client.events[ERROR]) == 1 event = django_elasticapm_client.events[ERROR][0] assert event["context"]["user"] == {}