prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
ommit mode so that code in # run_select_for_update can see this data. self.country1 = Country.objects.create(name="Belgium") self.country2 = Country.objects.create(name="France") self.city1 = City.objects.create(name="Liberchies", country=self.country1) self.city2 = City.objects....
on = connection.copy() def tearDown(self): try: self.end_blocking_transaction() except (DatabaseError, AttributeError): pass self.new_connection.close() def start_blocking_transaction(self):
_profile = PersonProfile.objects.create(person=self.person) # We need another database connection in transaction to test that one # connection issuing a SELECT ... FOR UPDATE will block. self.new_connecti
{ "filepath": "tests/select_for_update/tests.py", "language": "python", "file_size": 28047, "cut_index": 1331, "middle_length": 229 }
core.management import call_command from django.test import TestCase, TransactionTestCase from .models import Book class MigrationDataPersistenceTestCase(TransactionTestCase): """ Data loaded in migrations is available if TransactionTestCase.serialized_rollback = True. """ available_apps = ["mig...
_persistence"] serialized_rollback = True @classmethod def setUpClass(cls): # Simulate another TransactionTestCase having just torn down. call_command("flush", verbosity=0, interactive=False, allow_cascade=True) super()
ationDataPersistenceClassSetup(TransactionTestCase): """ Data loaded in migrations is available during class setup if TransactionTestCase.serialized_rollback = True. """ available_apps = ["migration_test_data
{ "filepath": "tests/migration_test_data_persistence/tests.py", "language": "python", "file_size": 1408, "cut_index": 524, "middle_length": 229 }
jango.db import migrations, models def add_book(apps, schema_editor): apps.get_model("migration_test_data_persistence", "Book").objects.using( schema_editor.connection.alias, ).create( title="I Love Django", ) class Migration(migrations.Migration): dependencies = [("migration_test_da...
verbose_name="ID", ), ), ("title", models.CharField(max_length=100)), ], options={ "managed": False, }, ), migrations.Alte
ields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False,
{ "filepath": "tests/migration_test_data_persistence/migrations/0002_add_book.py", "language": "python", "file_size": 1224, "cut_index": 518, "middle_length": 229 }
od def setUpTestData(cls): cls.a1 = Article.objects.create( headline="Hello", pub_date=datetime(2005, 11, 27) ).pk cls.a2 = Article.objects.create( headline="Goodbye", pub_date=datetime(2005, 11, 28) ).pk cls.a3 = Article.objects.create( he...
lf.assertQuerySetEqual( Article.objects.filter(headline__contains="Hello") | Article.objects.filter(headline__contains="bye"), ["Hello", "Goodbye", "Hello and goodbye"], attrgetter("headline"), )
eadline__startswith="Hello") | Article.objects.filter(headline__startswith="Goodbye") ), ["Hello", "Goodbye", "Hello and goodbye"], attrgetter("headline"), ) se
{ "filepath": "tests/or_lookups/tests.py", "language": "python", "file_size": 7624, "cut_index": 716, "middle_length": 229 }
oreignKey field = models.ForeignKey("some_fake.ModelName", models.CASCADE) name, path, args, kwargs = field.deconstruct() self.assertIsNone(name) field.set_attributes_from_name("author") name, path, args, kwargs = field.deconstruct() self.assertEqual(name, "author") ...
db_tablespace. field = models.Field(db_tablespace="foo") _, _, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {"db_tablespace": "foo"}) # With a db_tablespace equal to DEFAULT_
With a DEFAULT_DB_TABLESPACE. with self.settings(DEFAULT_DB_TABLESPACE="foo"): _, _, args, kwargs = field.deconstruct() self.assertEqual(args, []) self.assertEqual(kwargs, {}) # With a
{ "filepath": "tests/field_deconstruction/tests.py", "language": "python", "file_size": 30248, "cut_index": 1331, "middle_length": 229 }
rom django.contrib.auth.views import ( INTERNAL_RESET_SESSION_TOKEN, PasswordResetConfirmView, ) from django.test import Client def extract_token_from_url(url): token_search = re.search(r"/reset/.*/(.+?)/", url) if token_search: return token_search[1] class PasswordResetConfirmClient(Client)...
t_url_token def _get_password_reset_confirm_redirect_url(self, url): token = extract_token_from_url(url) if not token: return url # Add the token to the session session = self.session session[INTERNA
uts 'my-token' in the session and redirects to '/reset/bla/set-password/': >>> client = PasswordResetConfirmClient() >>> client.get('/reset/bla/my-token/') """ reset_url_token = PasswordResetConfirmView.rese
{ "filepath": "tests/auth_tests/client.py", "language": "python", "file_size": 1473, "cut_index": 524, "middle_length": 229 }
rt admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.test import TestCase, override_settings from django.urls import path, reverse class Router: target_db = None def db_for_read(self, model, **hints): return self.target_db db_for_write ...
ptions", "head", "trace"} @classmethod def setUpTestData(cls): cls.superusers = {} for db in cls.databases: Router.target_db = db cls.superusers[db] = User.objects.create_superuser( username=
[ path("admin/", site.urls), ] @override_settings(ROOT_URLCONF=__name__, DATABASE_ROUTERS=["%s.Router" % __name__]) class MultiDatabaseTests(TestCase): databases = {"default", "other"} READ_ONLY_METHODS = {"get", "o
{ "filepath": "tests/auth_tests/test_admin_multidb.py", "language": "python", "file_size": 2642, "cut_index": 563, "middle_length": 229 }
] class SimpleBackend(BaseBackend): def get_user_permissions(self, user_obj, obj=None): return ["user_perm"] def get_group_permissions(self, user_obj, obj=None): return ["group_perm"] @override_settings( AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.SimpleBackend"] ) c...
group_permissions(self): self.assertEqual(self.user.get_group_permissions(), {"group_perm"}) async def test_aget_group_permissions(self): self.assertEqual(await self.user.aget_group_permissions(), {"group_perm"}) def test_get_all_
self): self.assertEqual(self.user.get_user_permissions(), {"user_perm"}) async def test_aget_user_permissions(self): self.assertEqual(await self.user.aget_user_permissions(), {"user_perm"}) def test_get_
{ "filepath": "tests/auth_tests/test_auth_backends.py", "language": "python", "file_size": 56657, "cut_index": 2151, "middle_length": 229 }
yConfigured from django.db import IntegrityError from django.http import HttpRequest from django.test import TestCase, override_settings from django.utils import translation from .models import CustomUser class BasicTestCase(TestCase): def test_user(self): "Users can be created and can set their password...
has_usable_password()) u.set_password("testpw") self.assertTrue(u.check_password("testpw")) u.set_password(None) self.assertFalse(u.has_usable_password()) # Check username getter self.assertEqual(u.get_usern
.assertTrue(u.check_password("testpw")) # Check we can manually set an unusable password u.set_unusable_password() u.save() self.assertFalse(u.check_password("testpw")) self.assertFalse(u.
{ "filepath": "tests/auth_tests/test_basic.py", "language": "python", "file_size": 8622, "cut_index": 716, "middle_length": 229 }
mUserNonListRequiredFields") def test_required_fields_is_list(self): """REQUIRED_FIELDS should be a list.""" class CustomUserNonListRequiredFields(AbstractBaseUser): username = models.CharField(max_length=30, unique=True) date_of_birth = models.DateField() USERN...
], ) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserBadRequiredFields") def test_username_not_in_required_fields(self): """USERNAME_FIELD should not appear in REQUIRED_FIELDS.""" class CustomUserBadRequiredF
[ checks.Error( "'REQUIRED_FIELDS' must be a list or tuple.", obj=CustomUserNonListRequiredFields, id="auth.E001", ),
{ "filepath": "tests/auth_tests/test_checks.py", "language": "python", "file_size": 17926, "cut_index": 1331, "middle_length": 229 }
enttypes.models import ContentType from django.db.models import Q from django.test import SimpleTestCase, TestCase, override_settings from .settings import AUTH_MIDDLEWARE, AUTH_TEMPLATES class MockUser: def __repr__(self): return "MockUser()" def has_module_perms(self, perm): return perm ==...
if self.eq_calls > 0: return True self.eq_calls += 1 return False def test_repr(self): perms = PermWrapper(MockUser()) self.assertEqual(repr(perms), "PermWrapper(MockUser())") d
ntation. """ class EQLimiterObject: """ This object makes sure __eq__ will not be called endlessly. """ def __init__(self): self.eq_calls = 0 def __eq__(self, other):
{ "filepath": "tests/auth_tests/test_context_processors.py", "language": "python", "file_size": 5762, "cut_index": 716, "middle_length": 229 }
client import RequestFactory from .test_views import AuthViewsTestCase @override_settings(ROOT_URLCONF="auth_tests.urls") class LoginRequiredTestCase(AuthViewsTestCase): """ Tests the login_required decorators """ factory = RequestFactory() def test_wrapped_sync_function_is_not_coroutine_functi...
(wrapped_view), True) def test_callable(self): """ login_required is assignable to callable objects. """ class CallableView: def __call__(self, *args, **kwargs): pass login_required
def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return HttpResponse() wrapped_view = login_required(async_view) self.assertIs(iscoroutinefunction
{ "filepath": "tests/auth_tests/test_decorators.py", "language": "python", "file_size": 13404, "cut_index": 921, "middle_length": 229 }
ient", "password1": "test123", "password2": "test123", } form = self.form_class(data) self.assertFalse(form.is_valid()) self.assertEqual( form["username"].errors, [str(User._meta.get_field("username").error_messages["unique"])], ) ...
form["username"].errors, [str(validator.message)]) def test_password_verification(self): # The verification password is incorrect. data = { "username": "jsmith", "password1": "test123", "password2":
class(data) self.assertFalse(form.is_valid()) validator = next( v for v in User._meta.get_field("username").validators if v.code == "invalid" ) self.assertEqual(
{ "filepath": "tests/auth_tests/test_forms.py", "language": "python", "file_size": 67050, "cut_index": 3790, "middle_length": 229 }
_user from django.contrib.auth.hashers import get_hasher from django.contrib.auth.models import Group, User from django.test import TransactionTestCase, override_settings from .models import CustomUser # This must be a TransactionTestCase because the WSGI auth handler performs # its own transaction management. class...
hanisms.html#apache-authentication-provider """ User.objects.create_user("test", "test@example.com", "test") # User not in database self.assertIsNone(check_password({}, "unknown", "")) # Valid user with correct pas
ontenttypes", "auth_tests", ] def test_check_password(self): """ check_password() returns the correct values as per https://modwsgi.readthedocs.io/en/develop/user-guides/access-control-mec
{ "filepath": "tests/auth_tests/test_handlers.py", "language": "python", "file_size": 3914, "cut_index": 614, "middle_length": 229 }
1+ try: import hashlib scrypt = hashlib.scrypt except ImportError: scrypt = None class PBKDF2SingleIterationHasher(PBKDF2PasswordHasher): iterations = 1 @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPass(SimpleTestCase): def test_simple(self): encoded = make_p...
ssword_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) async def test_acheck_password(self): encoded = make_password("lètmein") self.assertI
) self.assertFalse(check_password("lètmeinz", encoded)) # Blank passwords blank_encoded = make_password("") self.assertTrue(blank_encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_pa
{ "filepath": "tests/auth_tests/test_hashers.py", "language": "python", "file_size": 33648, "cut_index": 1331, "middle_length": 229 }
rom django.contrib import auth from django.contrib.auth.models import User from django.http import HttpRequest from django.test import TestCase class TestLogin(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user(username="testuser", password="password") def setUp(s...
self.assertEqual(self.request.session[auth.SESSION_KEY], str(self.user.pk)) def test_without_user(self): with self.assertRaisesMessage( AttributeError, "'NoneType' object has no attribute 'get_session_auth_hash
al(self.request.session[auth.SESSION_KEY], str(self.user.pk)) def test_inactive_user(self): self.user.is_active = False self.user.save(update_fields=["is_active"]) auth.login(self.request, self.user)
{ "filepath": "tests/auth_tests/test_login.py", "language": "python", "file_size": 1056, "cut_index": 513, "middle_length": 229 }
ve createsuperuser. """ def inner(test_func): def wrapper(*args): class mock_getpass: @staticmethod def getpass(prompt=b"Password: ", stream=None): if callable(inputs["password"]): return inputs["password"]() ...
han a shortcut name. prompt_msgs = MOCK_INPUT_KEY_TO_PROMPTS.get(key, key) if isinstance(prompt_msgs, list): prompt_msgs = [ msg() if callable(msg) else msg for msg
n inputs.items(): if val == "KeyboardInterrupt": raise KeyboardInterrupt # get() fallback because sometimes 'key' is the actual # prompt rather t
{ "filepath": "tests/auth_tests/test_management.py", "language": "python", "file_size": 64938, "cut_index": 2151, "middle_length": 229 }
mport setup class FirstOfTagTests(SimpleTestCase): @setup({"firstof01": "{% firstof a b c %}"}) def test_firstof01(self): output = self.engine.render_to_string("firstof01", {"a": 0, "c": 0, "b": 0}) self.assertEqual(output, "") @setup({"firstof02": "{% firstof a b c %}"}) def test_fir...
output = self.engine.render_to_string("firstof04", {"a": 0, "c": 3, "b": 0}) self.assertEqual(output, "3") @setup({"firstof05": "{% firstof a b c %}"}) def test_firstof05(self): output = self.engine.render_to_string("firstof
ef test_firstof03(self): output = self.engine.render_to_string("firstof03", {"a": 0, "c": 0, "b": 2}) self.assertEqual(output, "2") @setup({"firstof04": "{% firstof a b c %}"}) def test_firstof04(self):
{ "filepath": "tests/template_tests/syntax_tests/test_firstof.py", "language": "python", "file_size": 3502, "cut_index": 614, "middle_length": 229 }
@setup({"if-tag04": "{% if foo %}foo{% elif bar %}bar{% endif %}"}) def test_if_tag04(self): output = self.engine.render_to_string("if-tag04", {"foo": True}) self.assertEqual(output, "foo") @setup({"if-tag05": "{% if foo %}foo{% elif bar %}bar{% endif %}"}) def test_if_tag05(self): ...
lf): output = self.engine.render_to_string("if-tag07", {"foo": True}) self.assertEqual(output, "foo") @setup({"if-tag08": "{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}"}) def test_if_tag08(self): output = se
est_if_tag06(self): output = self.engine.render_to_string("if-tag06") self.assertEqual(output, "") @setup({"if-tag07": "{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}"}) def test_if_tag07(se
{ "filepath": "tests/template_tests/syntax_tests/test_if.py", "language": "python", "file_size": 28658, "cut_index": 1331, "middle_length": 229 }
class IncludeTagTests(SimpleTestCase): libraries = {"bad_tag": "template_tests.templatetags.bad_tag"} @setup({"include01": '{% include "basic-syntax01" %}'}, basic_templates) def test_include01(self): output = self.engine.render_to_string("include01") self.assertEqual(output, "something c...
{"template_name": "basic-syntax02", "headline": "Included"}, ) self.assertEqual(output, "Included") @setup({"include04": 'a{% include "nonexistent" %}b'}) def test_include04(self): template = self.engine.get_tem
ded"}) self.assertEqual(output, "Included") @setup({"include03": "{% include template_name %}"}, basic_templates) def test_include03(self): output = self.engine.render_to_string( "include03",
{ "filepath": "tests/template_tests/syntax_tests/test_include.py", "language": "python", "file_size": 15156, "cut_index": 921, "middle_length": 229 }
s import setup class ListIndexTests(SimpleTestCase): @setup({"list-index01": "{{ var.1 }}"}) def test_list_index01(self): """ List-index syntax allows a template to access a certain item of a subscriptable object. """ output = self.engine.render_to_string( "...
tring_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") @setup({"list-index03": "{{ var.1 }}"}) def test_list_index03(self): """ Fail silently when the list index is
""" Fail silently when the list index is out of range. """ output = self.engine.render_to_string( "list-index02", {"var": ["first item", "second item"]} ) if self.engine.s
{ "filepath": "tests/template_tests/syntax_tests/test_list_index.py", "language": "python", "file_size": 2759, "cut_index": 563, "middle_length": 229 }
mport setup class LoadTagTests(SimpleTestCase): libraries = { "subpackage.echo": "template_tests.templatetags.subpackage.echo", "testtags": "template_tests.templatetags.testtags", } @setup( { "load01": ( '{% load testtags subpackage.echo %}{% echo test ...
tags @setup({"load03": "{% load echo from testtags %}{% echo this that theother %}"}) def test_load03(self): output = self.engine.render_to_string("load03") self.assertEqual(output, "this that theother") @setup( {
p({"load02": '{% load subpackage.echo %}{% echo2 "test" %}'}) def test_load02(self): output = self.engine.render_to_string("load02") self.assertEqual(output, "test") # {% load %} tag, importing individual
{ "filepath": "tests/template_tests/syntax_tests/test_load.py", "language": "python", "file_size": 3654, "cut_index": 614, "middle_length": 229 }
import TemplateSyntaxError from django.test import SimpleTestCase from django.utils.formats import date_format from ..utils import setup class NowTagTests(SimpleTestCase): @setup({"now01": '{% now "j n Y" %}'}) def test_now01(self): """ Simple case """ output = self.engine.re...
self.assertEqual(output, date_format(datetime.now())) @setup({"now03": "{% now 'j n Y' %}"}) def test_now03(self): """ #15092 - Also accept simple quotes """ output = self.engine.render_to_string("now03") s
datetime.now().year, ), ) # Check parsing of locale strings @setup({"now02": '{% now "DATE_FORMAT" %}'}) def test_now02(self): output = self.engine.render_to_string("now02")
{ "filepath": "tests/template_tests/syntax_tests/test_now.py", "language": "python", "file_size": 2754, "cut_index": 563, "middle_length": 229 }
n!", "@at", "slash/something", "inline", "inline-inline", "INLINE" "with+plus", "with&amp", "with%percent", "with,comma", "with:colon", "with;semicolon", "[brackets]", "(parens)", "{curly}", ) def gen_partial_template(name, *args, **kwargs): if args or kwargs: ...
ldef_names}) def test_valid_partialdef_names(self): for template_name in valid_partialdef_names: with self.subTest(template_name=template_name): output = self.engine.render_to_string(template_name) se
aldef %}}" f"{{% partial {name} %}}" ) class PartialTagTests(SimpleTestCase): libraries = {"bad_tag": "template_tests.templatetags.bad_tag"} @setup({name: gen_partial_template(name) for name in valid_partia
{ "filepath": "tests/template_tests/syntax_tests/test_partials.py", "language": "python", "file_size": 24053, "cut_index": 1331, "middle_length": 229 }
pleTestCase from ..utils import setup class RegroupTagTests(SimpleTestCase): @setup( { "regroup01": "" "{% regroup data by bar as grouped %}" "{% for group in grouped %}" "{{ group.grouper }}:" "{% for item in group.list %}" "{{ item...
oo": "x", "bar": 3}, ], }, ) self.assertEqual(output, "1:cd,2:ab,3:x,") @setup( { "regroup02": "" "{% regroup data by bar as grouped %}" "{% for group in grouped %
{ "data": [ {"foo": "c", "bar": 1}, {"foo": "d", "bar": 1}, {"foo": "a", "bar": 2}, {"foo": "b", "bar": 2}, {"f
{ "filepath": "tests/template_tests/syntax_tests/test_regroup.py", "language": "python", "file_size": 4777, "cut_index": 614, "middle_length": 229 }
s import setup class SpacelessTagTests(SimpleTestCase): @setup( { "spaceless01": ( "{% spaceless %} <b> <i> text </i> </b> {% endspaceless %}" ) } ) def test_spaceless01(self): output = self.engine.render_to_string("spaceless01") ...
i></b>{% endspaceless %}"}) def test_spaceless03(self): output = self.engine.render_to_string("spaceless03") self.assertEqual(output, "<b><i>text</i></b>") @setup( { "spaceless04": ( "{% spaceles
) } ) def test_spaceless02(self): output = self.engine.render_to_string("spaceless02") self.assertEqual(output, "<b><i> text </i></b>") @setup({"spaceless03": "{% spaceless %}<b><i>text</
{ "filepath": "tests/template_tests/syntax_tests/test_spaceless.py", "language": "python", "file_size": 2043, "cut_index": 563, "middle_length": 229 }
m django.test import SimpleTestCase from ..utils import setup class TemplateTagTests(SimpleTestCase): @setup({"templatetag01": "{% templatetag openblock %}"}) def test_templatetag01(self): output = self.engine.render_to_string("templatetag01") self.assertEqual(output, "{%") @setup({"temp...
atetag closevariable %}"}) def test_templatetag04(self): output = self.engine.render_to_string("templatetag04") self.assertEqual(output, "}}") @setup({"templatetag05": "{% templatetag %}"}) def test_templatetag05(self):
({"templatetag03": "{% templatetag openvariable %}"}) def test_templatetag03(self): output = self.engine.render_to_string("templatetag03") self.assertEqual(output, "{{") @setup({"templatetag04": "{% templ
{ "filepath": "tests/template_tests/syntax_tests/test_template_tag.py", "language": "python", "file_size": 2607, "cut_index": 563, "middle_length": 229 }
utput = self.engine.render_to_string("basic-syntax01") self.assertEqual(output, "something cool") @setup(basic_templates) def test_basic_syntax02(self): """ Variables should be replaced with their value in the current context """ output = self.engine.render_to_st...
sic-syntax04": "as{{ missing }}df"}) def test_basic_syntax04(self): """ Fail silently when a variable is not found in the current context """ output = self.engine.render_to_string("basic-syntax04") if self.engine
placement variable is allowed in a template """ output = self.engine.render_to_string( "basic-syntax03", {"first": 1, "second": 2} ) self.assertEqual(output, "1 --- 2") @setup({"ba
{ "filepath": "tests/template_tests/syntax_tests/test_basic.py", "language": "python", "file_size": 17639, "cut_index": 1331, "middle_length": 229 }
sts(SimpleTestCase): libraries = { "cache": "django.templatetags.cache", "custom": "template_tests.templatetags.custom", } def tearDown(self): cache.clear() @setup({"cache03": "{% load cache %}{% cache 2 test %}cache03{% endcache %}"}) def test_cache03(self): output...
) self.assertEqual(output, "cache03") @setup({"cache05": "{% load cache %}{% cache 2 test foo %}cache05{% endcache %}"}) def test_cache05(self): output = self.engine.render_to_string("cache05", {"foo": 1}) self.assertEqual(
"cache04": "{% load cache %}{% cache 2 test %}cache04{% endcache %}", } ) def test_cache04(self): self.engine.render_to_string("cache03") output = self.engine.render_to_string("cache04"
{ "filepath": "tests/template_tests/syntax_tests/test_cache.py", "language": "python", "file_size": 7492, "cut_index": 716, "middle_length": 229 }
st_cycle01(self): msg = "No named cycles in template. 'a' is not defined" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.get_template("cycle01") @setup({"cycle05": "{% cycle %}"}) def test_cycle05(self): msg = "'cycle' tag requires at least two argument...
ycle 'a' 'b' 'c' as abc %}{% cycle abc %}"}) def test_cycle10(self): output = self.engine.render_to_string("cycle10") self.assertEqual(output, "ab") @setup({"cycle11": "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}"}
test_cycle07(self): msg = "Could not parse the remainder: ',b,c' from 'a,b,c'" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.get_template("cycle07") @setup({"cycle10": "{% c
{ "filepath": "tests/template_tests/syntax_tests/test_cycle.py", "language": "python", "file_size": 7969, "cut_index": 716, "middle_length": 229 }
models import Group from django.test import SimpleTestCase, override_settings from ..utils import setup @override_settings(DEBUG=True) class DebugTests(SimpleTestCase): @override_settings(DEBUG=False) @setup({"non_debug": "{% debug %}"}) def test_non_debug(self): output = self.engine.render_to_st...
in", {"a": 1}) self.assertTrue( output.startswith( "{&#x27;a&#x27;: 1}" "{&#x27;False&#x27;: False, &#x27;None&#x27;: None, " "&#x27;True&#x27;: True}\n\n{" ) ) @s
self.assertIn( "&#x27;django&#x27;: &lt;module &#x27;django&#x27; ", output, ) @setup({"plain": "{% debug %}"}) def test_plain(self): output = self.engine.render_to_string("pla
{ "filepath": "tests/template_tests/syntax_tests/test_debug.py", "language": "python", "file_size": 1549, "cut_index": 537, "middle_length": 229 }
tring("for-tag01", {"values": [1, 2, 3]}) self.assertEqual(output, "123") @setup({"for-tag02": "{% for val in values reversed %}{{ val }}{% endfor %}"}) def test_for_tag02(self): output = self.engine.render_to_string("for-tag02", {"values": [1, 2, 3]}) self.assertEqual(output, "321") ...
t = self.engine.render_to_string("for-tag-vars02", {"values": [6, 6, 6]}) self.assertEqual(output, "012") @setup( { "for-tag-vars03": ( "{% for val in values %}{{ forloop.revcounter }}{% endfor %}"
g-vars01", {"values": [6, 6, 6]}) self.assertEqual(output, "123") @setup( {"for-tag-vars02": "{% for val in values %}{{ forloop.counter0 }}{% endfor %}"} ) def test_for_tag_vars02(self): outpu
{ "filepath": "tests/template_tests/syntax_tests/test_for.py", "language": "python", "file_size": 13447, "cut_index": 921, "middle_length": 229 }
ed01(self): output = self.engine.render_to_string("ifchanged01", {"num": (1, 2, 3)}) self.assertEqual(output, "123") @setup( { "ifchanged02": ( "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}" ) } ) def test_ifc...
self.assertEqual(output, "1") @setup( { "ifchanged04": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}" "{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}" "{% endfor %}{% endfor
"{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}" ) } ) def test_ifchanged03(self): output = self.engine.render_to_string("ifchanged03", {"num": (1, 1, 1)})
{ "filepath": "tests/template_tests/syntax_tests/test_if_changed.py", "language": "python", "file_size": 12232, "cut_index": 921, "middle_length": 229 }
m django.test import SimpleTestCase from ..utils import setup class NamedEndblockTests(SimpleTestCase): @setup( { "namedendblocks01": "1{% block first %}_{% block second %}" "2{% endblock second %}_{% endblock first %}3" } ) def test_namedendblocks01(self): ...
("namedendblocks02") @setup( { "namedendblocks03": "1{% block first %}_{% block second %}" "2{% endblock %}_{% endblock second %}3" } ) def test_namedendblocks03(self): with self.assertRaises(Tem
irst %}_{% block second %}" "2{% endblock first %}_{% endblock second %}3" } ) def test_namedendblocks02(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template
{ "filepath": "tests/template_tests/syntax_tests/test_named_endblock.py", "language": "python", "file_size": 2475, "cut_index": 563, "middle_length": 229 }
g(template_name, context) self.assertEqual(output, expected) def assertTemplateSyntaxError(self, template_name, context, expected): with self.assertRaisesMessage(TemplateSyntaxError, expected): self.engine.render_to_string(template_name, context) @setup({"querystring_empty_get_para...
?a=b")) empty_context = RequestContext(self.request_factory.get("/")) for context in [non_empty_context, empty_context]: with self.subTest(context=context): self.assertRenderEqual("querystring_remove_all_params",
t_params", context, expected="?") @setup({"querystring_remove_all_params": "{% querystring a=None %}"}) def test_querystring_remove_all_params(self): non_empty_context = RequestContext(self.request_factory.get("/
{ "filepath": "tests/template_tests/syntax_tests/test_querystring.py", "language": "python", "file_size": 12018, "cut_index": 921, "middle_length": 229 }
mport setup class ResetCycleTagTests(SimpleTestCase): @setup({"resetcycle01": "{% resetcycle %}"}) def test_resetcycle01(self): with self.assertRaisesMessage(TemplateSyntaxError, "No cycles in template."): self.engine.get_template("resetcycle01") @setup({"resetcycle02": "{% resetcycle...
rror, "Named cycle 'undefinedcycle' does not exist." ): self.engine.get_template("resetcycle03") @setup({"resetcycle04": "{% cycle 'a' 'b' as ab %}{% resetcycle undefinedcycle %}"}) def test_resetcycle04(self): with sel
self.engine.get_template("resetcycle02") @setup({"resetcycle03": "{% cycle 'a' 'b' %}{% resetcycle undefinedcycle %}"}) def test_resetcycle03(self): with self.assertRaisesMessage( TemplateSyntaxE
{ "filepath": "tests/template_tests/syntax_tests/test_resetcycle.py", "language": "python", "file_size": 4329, "cut_index": 614, "middle_length": 229 }
eSyntaxError from django.templatetags.static import StaticNode from django.test import SimpleTestCase, override_settings from ..utils import setup @override_settings(INSTALLED_APPS=[], MEDIA_URL="media/", STATIC_URL="static/") class StaticTagTests(SimpleTestCase): libraries = {"static": "django.templatetags.stat...
test_static_prefixtag02(self): output = self.engine.render_to_string("static-prefixtag02") self.assertEqual(output, settings.STATIC_URL) @setup({"static-prefixtag03": "{% load static %}{% get_media_prefix %}"}) def test_static_pref
self.assertEqual(output, settings.STATIC_URL) @setup( { "static-prefixtag02": "{% load static %}" "{% get_static_prefix as static_prefix %}{{ static_prefix }}" } ) def
{ "filepath": "tests/template_tests/syntax_tests/test_static.py", "language": "python", "file_size": 4411, "cut_index": 614, "middle_length": 229 }
tCase): @setup({"comment-syntax01": "{# this is hidden #}hello"}) def test_comment_syntax01(self): output = self.engine.render_to_string("comment-syntax01") self.assertEqual(output, "hello") @setup({"comment-syntax02": "{# this is hidden #}hello{# foo #}"}) def test_comment_syntax02(sel...
utput = self.engine.render_to_string("comment-syntax04") self.assertEqual(output, "foo") @setup({"comment-syntax05": "foo{# {% somerandomtag %} #}"}) def test_comment_syntax05(self): output = self.engine.render_to_string("comment
ntax03(self): output = self.engine.render_to_string("comment-syntax03") self.assertEqual(output, "foo") @setup({"comment-syntax04": "foo{# {% endblock %} #}"}) def test_comment_syntax04(self): o
{ "filepath": "tests/template_tests/syntax_tests/test_comment.py", "language": "python", "file_size": 3685, "cut_index": 614, "middle_length": 229 }
x01", {"var": "Django is the greatest!"} ) self.assertEqual(output, "DJANGO IS THE GREATEST!") @setup({"filter-syntax02": "{{ var|upper|lower }}"}) def test_filter_syntax02(self): """ Chained filters """ output = self.engine.render_to_string( "filter-...
output, "DJANGO IS THE GREATEST!") @setup({"filter-syntax04": "{{ var| upper }}"}) def test_filter_syntax04(self): """ Allow spaces after the filter pipe """ output = self.engine.render_to_string( "filte
tax03(self): """ Allow spaces before the filter pipe """ output = self.engine.render_to_string( "filter-syntax03", {"var": "Django is the greatest!"} ) self.assertEqual(
{ "filepath": "tests/template_tests/syntax_tests/test_filter_syntax.py", "language": "python", "file_size": 9524, "cut_index": 921, "middle_length": 229 }
s import setup class InvalidStringTests(SimpleTestCase): libraries = {"i18n": "django.templatetags.i18n"} @setup({"invalidstr01": '{{ var|default:"Foo" }}'}) def test_invalidstr01(self): output = self.engine.render_to_string("invalidstr01") if self.engine.string_if_invalid: se...
03": "{% for v in var %}({{ v }}){% endfor %}"}) def test_invalidstr03(self): output = self.engine.render_to_string("invalidstr03") self.assertEqual(output, "") @setup({"invalidstr04": "{% if var %}Yes{% else %}No{% endif %}"})
output = self.engine.render_to_string("invalidstr02") if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") @setup({"invalidstr
{ "filepath": "tests/template_tests/syntax_tests/test_invalid_string.py", "language": "python", "file_size": 2386, "cut_index": 563, "middle_length": 229 }
import TemplateSyntaxError from django.test import SimpleTestCase from django.utils.lorem_ipsum import COMMON_P, WORDS from ..utils import setup class LoremTagTests(SimpleTestCase): @setup({"lorem1": "{% lorem 3 w %}"}) def test_lorem1(self): output = self.engine.render_to_string("lorem1") s...
output = self.engine.render_to_string("lorem_default") self.assertEqual(output, COMMON_P) @setup({"lorem_syntax_error": "{% lorem 1 2 3 4 %}"}) def test_lorem_syntax(self): msg = "Incorrect format for 'lorem' tag" with s
m") words = output.split(" ") self.assertEqual(len(words), 3) for word in words: self.assertIn(word, WORDS) @setup({"lorem_default": "{% lorem %}"}) def test_lorem_default(self):
{ "filepath": "tests/template_tests/syntax_tests/test_lorem.py", "language": "python", "file_size": 1590, "cut_index": 537, "middle_length": 229 }
@setup({"url01": '{% url "client" client.id %}'}) def test_url01(self): output = self.engine.render_to_string("url01", {"client": {"id": 1}}) self.assertEqual(output, "/client/1/") @setup({"url02": '{% url "client_action" id=client.id action="update" %}'}) def test_url02(self): ...
n='update' %}"}) def test_url02b(self): output = self.engine.render_to_string("url02b", {"client": {"id": 1}}) self.assertEqual(output, "/client/1/update/") @setup({"url02c": "{% url 'client_action' client.id 'update' %}"}) def
'}) def test_url02a(self): output = self.engine.render_to_string("url02a", {"client": {"id": 1}}) self.assertEqual(output, "/client/1/update/") @setup({"url02b": "{% url 'client_action' id=client.id actio
{ "filepath": "tests/template_tests/syntax_tests/test_url.py", "language": "python", "file_size": 12620, "cut_index": 921, "middle_length": 229 }
otExist, TemplateSyntaxError from django.test import SimpleTestCase from ..utils import setup from .test_extends import inheritance_templates class ExceptionsTests(SimpleTestCase): @setup({"exception01": "{% extends 'nonexistent' %}"}) def test_exception01(self): """ Raise exception for inval...
self.engine.render_to_string("exception02") else: with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string("exception02") @setup( { "exception03": "{% extends 'inheritance
}"}) def test_exception02(self): """ Raise exception for invalid variable template name """ if self.engine.string_if_invalid: with self.assertRaises(TemplateDoesNotExist):
{ "filepath": "tests/template_tests/syntax_tests/test_exceptions.py", "language": "python", "file_size": 2726, "cut_index": 563, "middle_length": 229 }
nittest import skipIf from django.test import SimpleTestCase from ..utils import setup try: import numpy except ImportError: numpy = False @skipIf(numpy is False, "Numpy must be installed to run these tests.") class NumpyTests(SimpleTestCase): @setup({"numpy-array-index01": "{{ var.1 }}"}) def test...
def test_numpy_array_index02(self): """ Fail silently when the array index is out of range. """ output = self.engine.render_to_string( "numpy-array-index02", {"var": numpy.array(["first item", "s
e.render_to_string( "numpy-array-index01", {"var": numpy.array(["first item", "second item"])}, ) self.assertEqual(output, "second item") @setup({"numpy-array-index02": "{{ var.5 }}"})
{ "filepath": "tests/template_tests/syntax_tests/test_numpy.py", "language": "python", "file_size": 1174, "cut_index": 518, "middle_length": 229 }
text, Template from django.test import SimpleTestCase, override_settings @override_settings(STATIC_URL="/static/") class CspNonceTagTests(SimpleTestCase): def test_with_nonce_in_context(self): t = Template("<script {% csp_nonce_attr %}></script>") result = t.render(Context({"csp_nonce": "abc123"})...
once": None})) self.assertEqual(result, "<script ></script>") def test_nonce_is_escaped(self): t = Template("<script {% csp_nonce_attr %}></script>") result = t.render(Context({"csp_nonce": '<script>"'})) self.assertIn(
result = t.render(Context()) self.assertEqual(result, "<script ></script>") def test_with_csp_nonce_none(self): t = Template("<script {% csp_nonce_attr %}></script>") result = t.render(Context({"csp_n
{ "filepath": "tests/template_tests/syntax_tests/test_csp_nonce_attr.py", "language": "python", "file_size": 3675, "cut_index": 614, "middle_length": 229 }
eSyntaxError from django.test import SimpleTestCase from ..utils import setup class SimpleTagTests(SimpleTestCase): libraries = {"custom": "template_tests.templatetags.custom"} @setup({"simpletag-renamed01": "{% load custom %}{% minusone 7 %}"}) def test_simpletag_renamed01(self): output = self....
("simpletag-renamed02") self.assertEqual(output, "5") @setup({"simpletag-renamed03": "{% load custom %}{% minustwo_overridden_name 7 %}"}) def test_simpletag_renamed03(self): with self.assertRaises(TemplateSyntaxError):
self): output = self.engine.render_to_string
{ "filepath": "tests/template_tests/syntax_tests/test_simple_tag.py", "language": "python", "file_size": 904, "cut_index": 547, "middle_length": 52 }
import models class Email(models.Model): email = models.EmailField(verbose_name="email address", max_length=255, unique=True) class CustomUserWithFKManager(BaseUserManager): def create_superuser(self, username, email, group, password): user = self.model(username_id=username, email_id=email, group_i...
reignKey( Email, models.CASCADE, to_field="email", related_name="secondary" ) group = models.ForeignKey(Group, models.CASCADE) custom_objects = CustomUserWithFKManager() USERNAME_FIELD = "username" REQUIRED_FIELDS = ["email",
SCADE, related_name="primary") email = models.Fo
{ "filepath": "tests/auth_tests/models/with_foreign_key.py", "language": "python", "file_size": 923, "cut_index": 606, "middle_length": 52 }
on_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], "action": "mail_admin", "index": 0, } self.client.post( reverse("admin:admin_views_subscriber_changelist"), action_data ) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.ou...
ost": "yes", } confirmation = self.client.post( reverse("admin:admin_views_subscriber_changelist"), action_data ) self.assertIsInstance(confirmation, TemplateResponse) self.assertContains( con
, "action": "delete_selected", "index": 0, } delete_confirmation_data = { ACTION_CHECKBOX_NAME: [self.s1.pk, self.s2.pk], "action": "delete_selected", "p
{ "filepath": "tests/admin_views/test_actions.py", "language": "python", "file_size": 37423, "cut_index": 2151, "middle_length": 229 }
contrib.auth.models import User from django.test import SimpleTestCase, TestCase, override_settings from django.test.client import RequestFactory from django.urls import path, reverse from .models import Article site = admin.AdminSite(name="test_adminsite") site.register(User) site.register(Article) class CustomAdm...
ontext contains the documented variables and that available_apps context variable structure is the expected one. """ request_factory = RequestFactory() @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_superuse
= [ path("test_admin/admin/", site.urls), path("test_custom_admin/admin/", custom_site.urls), ] @override_settings(ROOT_URLCONF="admin_views.test_adminsite") class SiteEachContextTest(TestCase): """ Check each_c
{ "filepath": "tests/admin_views/test_adminsite.py", "language": "python", "file_size": 4544, "cut_index": 614, "middle_length": 229 }
m .tests import AdminViewBasicTestCase PAGINATOR_SIZE = AutocompleteJsonView.paginate_by class AuthorAdmin(admin.ModelAdmin): ordering = ["id"] search_fields = ["id"] class AuthorshipInline(admin.TabularInline): model = Authorship autocomplete_fields = ["author"] class BookAdmin(admin.ModelAdmin)...
["recipient"]) site.register(PKChild, search_fields=["name"]) site.register(Toy, autocomplete_fields=["child"]) @contextmanager def model_admin(model, model_admin, admin_site=site): try: org_admin = admin_site.get_model_admin(model) excep
in) site.register(Book, BookAdmin) site.register(Employee, search_fields=["name"]) site.register(WorkHour, autocomplete_fields=["employee"]) site.register(Manager, search_fields=["name"]) site.register(Bonus, autocomplete_fields=
{ "filepath": "tests/admin_views/test_autocomplete_view.py", "language": "python", "file_size": 23706, "cut_index": 1331, "middle_length": 229 }
rom django.contrib.auth.models import User from django.test import TestCase, override_settings from django.urls import reverse @override_settings(ROOT_URLCONF="admin_views.urls") class AdminBreadcrumbsTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( ...
ient.get(reverse("admin:auth_user_add")) self.assertContains(response, '<nav aria-label="Breadcrumbs">') response = self.client.get( reverse("admin:app_list", kwargs={"app_label": "auth"}) ) self.assertContains(r
t_breadcrumbs_absent(self): response = self.client.get(reverse("admin:index")) self.assertNotContains(response, '<nav aria-label="Breadcrumbs">') def test_breadcrumbs_present(self): response = self.cl
{ "filepath": "tests/admin_views/test_breadcrumbs.py", "language": "python", "file_size": 1041, "cut_index": 513, "middle_length": 229 }
e_settings from django.urls import reverse @override_settings( ROOT_URLCONF="admin_views.urls", TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "dj...
superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) def setUp(self): self.client.force_login(self.superuser) @override_settings( TEMPLATES=[ {
}, } ], ) @modify_settings( MIDDLEWARE={"append": "django.middleware.csp.ContentSecurityPolicyMiddleware"} ) class AdminCspNonceTests(TestCase): @classmethod def setUpTestData(cls): cls.
{ "filepath": "tests/admin_views/test_csp.py", "language": "python", "file_size": 4026, "cut_index": 614, "middle_length": 229 }
.forms import AdminAuthenticationForm from django.contrib.admin.helpers import AdminForm from django.contrib.auth.models import User from django.test import SimpleTestCase, TestCase, override_settings from .admin import ArticleForm # To verify that the login form rejects inactive users, use an authentication # backe...
, "password": "password", } form = AdminAuthenticationForm(None, data) self.assertEqual(form.non_field_errors(), ["This account is inactive."]) class AdminFormTests(SimpleTestCase): def test_repr(self): fie
def setUpTestData(cls): User.objects.create_user( username="inactive", password="password", is_active=False ) def test_inactive_user(self): data = { "username": "inactive"
{ "filepath": "tests/admin_views/test_forms.py", "language": "python", "file_size": 1575, "cut_index": 537, "middle_length": 229 }
eleniumTestCase from django.contrib.auth.models import User from django.core.paginator import Paginator from django.test import TestCase, override_settings from django.urls import reverse from .models import City, State @override_settings(ROOT_URLCONF="admin_views.urls") class AdminHistoryViewTests(TestCase): @c...
field names. """ state = State.objects.create(name="My State Name") city = City.objects.create(name="My City Name", state=state) change_dict = { "name": "My State Name 2", "nolabel_form_field": True,
, ) def setUp(self): self.client.force_login(self.superuser) def test_changed_message_uses_form_labels(self): """ Admin's model history change messages use form labels instead of
{ "filepath": "tests/admin_views/test_history_view.py", "language": "python", "file_size": 4547, "cut_index": 614, "middle_length": 229 }
django.test import TestCase, override_settings from django.urls import path, reverse from .models import Book class Router: target_db = None def db_for_read(self, model, **hints): return self.target_db db_for_write = db_for_read def allow_relation(self, obj1, obj2, **hints): retur...
READ_ONLY_METHODS = {"get", "options", "head", "trace"} @classmethod def setUpTestData(cls): cls.superusers = {} cls.test_book_ids = {} for db in cls.databases: Router.target_db = db cls.superus
path("admin/", site.urls), path("books/<book_id>/", book), ] @override_settings(ROOT_URLCONF=__name__, DATABASE_ROUTERS=["%s.Router" % __name__]) class MultiDatabaseTests(TestCase): databases = {"default", "other"}
{ "filepath": "tests/admin_views/test_multidb.py", "language": "python", "file_size": 7867, "cut_index": 716, "middle_length": 229 }
ls import path, reverse from .models import Héllo class AdminSiteWithSidebar(admin.AdminSite): pass class AdminSiteWithoutSidebar(admin.AdminSite): enable_nav_sidebar = False site_with_sidebar = AdminSiteWithSidebar(name="test_with_sidebar") site_without_sidebar = AdminSiteWithoutSidebar(name="test_witho...
er( username="super", password="secret", email="super@example.com", ) def setUp(self): self.client.force_login(self.superuser) def test_sidebar_not_on_index(self): response = self.client
, site_without_sidebar.urls), ] @override_settings(ROOT_URLCONF="admin_views.test_nav_sidebar") class AdminSidebarTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superus
{ "filepath": "tests/admin_views/test_nav_sidebar.py", "language": "python", "file_size": 9025, "cut_index": 716, "middle_length": 229 }
ango.urls import reverse @override_settings(ROOT_URLCONF="auth_tests.urls_admin") class SeleniumAuthTests(AdminSeleniumTestCase): available_apps = AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="...
admin:auth_user_add") self.admin_login(username="super", password="secret") self.selenium.get(self.live_server_url + user_add_url) pw_switch_on = self.selenium.find_element( By.CSS_SELECTOR, 'input[name="usable_password
ld shows/hides the password fields when adding a user. """ from selenium.common import NoSuchElementException from selenium.webdriver.common.by import By user_add_url = reverse("auth_test_
{ "filepath": "tests/admin_views/test_password_form.py", "language": "python", "file_size": 6104, "cut_index": 716, "middle_length": 229 }
lCaseModel @override_settings(ROOT_URLCONF="admin_views.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="s...
id_owner", "change_id_owner", "delete_id_owner", "view_id_owner", ] for link_id in tests: with self.subTest(link_id): link_image = self.selenium.find_element(
butes(self): from selenium.webdriver.common.by import By album_add_url = reverse("admin:admin_views_album_add") self.selenium.get(self.live_server_url + album_add_url) tests = [ "add_
{ "filepath": "tests/admin_views/test_related_object_lookups.py", "language": "python", "file_size": 8352, "cut_index": 716, "middle_length": 229 }
ast @override_settings(ROOT_URLCONF="admin_views.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", ...
# `Skip link` is not present. skip_link = self.selenium.find_element(By.CLASS_NAME, "skip-to-content-link") self.assertFalse(skip_link.is_displayed()) # 1st TAB is pressed, `skip link` is shown. body = self.selenium.fi
iver.common.by import By from selenium.webdriver.common.keys import Keys self.admin_login( username="super", password="secret", login_url=reverse("admin:index"), )
{ "filepath": "tests/admin_views/test_skip_link_to_content.py", "language": "python", "file_size": 7193, "cut_index": 716, "middle_length": 229 }
ango.contrib.auth import get_permission_codename from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.template.base import Token, TokenType from django.test import RequestFactory, SimpleTestCase, TestCase from django.urls import reverse from django.utils.version import...
def test_max_items_zero(self): result = truncated_unordered_list(["a", "b", "c"], 0) self.assertEqual(result, "") self.assertNotIn("more object", result) def test_flat_list_truncated(self): self.assertEqual(
def test_no_max_items(self): result = truncated_unordered_list(["item 1", "item 2"], None) self.assertEqual(result, ("\t<li>item 1</li>\n" "\t<li>item 2</li>")) self.assertNotIn("more object", result)
{ "filepath": "tests/admin_views/test_templatetags.py", "language": "python", "file_size": 14421, "cut_index": 921, "middle_length": 229 }
", { "value": "gold", "warm": True, **save_option, }, ) parsed_url = urlsplit(response.url) self.assertEqual(parsed_url.query, q...
GET on the change_view (when passing a string as the PK argument for a model with an integer PK field) redirects to the index page with a message saying the object doesn't exist. """ response = self.client.get(
n_views_section_change", args=(self.s1.pk,)) ) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_basic_edit_GET_string_PK(self): """
{ "filepath": "tests/admin_views/tests.py", "language": "python", "file_size": 406206, "cut_index": 13624, "middle_length": 229 }
ttpResponse from django.urls import include, path from . import admin, custom_has_permission_admin, customadmin, views from .test_autocomplete_view import site as autocomplete_site def non_admin_view(request): return HttpResponse() urlpatterns = [ path("test_admin/admin/doc/", include("django.contrib.admin...
("test_admin/admin4/", customadmin.simple_site.urls), path("test_admin/admin5/", admin.site2.urls), path("test_admin/admin6/", admin.site6.urls), path("test_admin/admin7/", admin.site7.urls), # All admin views accept `extra_context` to allo
est_admin/admin/", admin.site.urls), path("test_admin/admin2/", customadmin.site.urls), path( "test_admin/admin3/", (admin.site.get_urls(), "admin", "admin3"), {"form_url": "pony"}, ), path
{ "filepath": "tests/admin_views/urls.py", "language": "python", "file_size": 1880, "cut_index": 537, "middle_length": 229 }
, mixed. "..&#x2F;hax0rd.txt", # HTML entities. "..&sol;hax0rd.txt", # HTML entities. ] CANDIDATE_INVALID_FILE_NAMES = [ "/tmp/", # Directory, *nix-style. "c:\\tmp\\", # Directory, win-style. "/tmp/.", # Directory dot, *nix-style. "c:\\tmp\\.", # Directory dot, *nix-style. "/tmp/..", ...
def test_upload_name_is_validated(self): candidates = [ "/tmp/", "/tmp/..", "/tmp/.", ] if sys.platform == "win32": candidates.extend( [ "c:\\tmp\
s", MIDDLEWARE=[] ) class FileUploadTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() os.makedirs(MEDIA_ROOT, exist_ok=True) cls.addClassCleanup(shutil.rmtree, MEDIA_ROOT)
{ "filepath": "tests/file_uploads/tests.py", "language": "python", "file_size": 35862, "cut_index": 2151, "middle_length": 229 }
port os from tempfile import NamedTemporaryFile from django.core.files.uploadhandler import ( FileUploadHandler, StopUpload, TemporaryFileUploadHandler, ) class QuotaUploadHandler(FileUploadHandler): """ This test upload handler terminates the connection if more than a quota (5MB) is uploaded...
class StopUploadTemporaryFileHandler(TemporaryFileUploadHandler): """A handler that raises a StopUpload exception.""" def receive_data_chunk(self, raw_data, start): raise StopUpload() class CustomUploadError(Exception): pass class
t): self.total_upload += len(raw_data) if self.total_upload >= self.QUOTA: raise StopUpload(connection_reset=True) return raw_data def file_complete(self, file_size): return None
{ "filepath": "tests/file_uploads/uploadhandler.py", "language": "python", "file_size": 2277, "cut_index": 563, "middle_length": 229 }
from django.urls import path, re_path from . import views urlpatterns = [ path("upload/", views.file_upload_view), path("upload_traversal/", views.file_upload_traversal_view), path("verify/", views.file_upload_view_verify), path("unicode_name/", views.file_upload_unicode_name), path("echo/", views...
top_upload_temporary_file), path("temp_file/upload_interrupted/", views.file_upload_interrupted_temporary_file), path("filename_case/", views.file_upload_filename_case_view), re_path(r"^fd_closing/(?P<access>t|f)/$", views.file_upload_fd_closin
quota), path("quota/broken/", views.file_upload_quota_broken), path("getlist_count/", views.file_upload_getlist_count), path("upload_errors/", views.file_upload_errors), path("temp_file/stop_upload/", views.file_s
{ "filepath": "tests/file_uploads/urls.py", "language": "python", "file_size": 1003, "cut_index": 512, "middle_length": 229 }
erverError, JsonResponse from .models import FileModel from .tests import UNICODE_FILENAME, UPLOAD_FOLDER from .uploadhandler import ( ErroringUploadHandler, QuotaUploadHandler, StopUploadTemporaryFileHandler, TraversalUploadHandler, ) def file_upload_view(request): """ A file upload can be u...
ttpResponseServerError() return HttpResponse() else: return HttpResponseServerError() def file_upload_view_verify(request): """ Use the sha digest hash to verify the uploaded contents. """ form_data = request.POST.copy
form_data["name"], str ): # If a file is posted, the dummy client should only post the file name, # not the full path. if os.path.dirname(form_data["file_field"].name) != "": return H
{ "filepath": "tests/file_uploads/views.py", "language": "python", "file_size": 5531, "cut_index": 716, "middle_length": 229 }
class R(models.Model): is_default = models.BooleanField(default=False) p = models.ForeignKey(P, models.CASCADE, null=True) def get_default_r(): return R.objects.get_or_create(is_default=True)[0].pk class S(models.Model): r = models.ForeignKey(R, models.CASCADE) class T(models.Model): s = mod...
ass Meta: required_db_features = {"supports_on_delete_db_cascade"} class CascadeDbModel(models.Model): name = models.CharField(max_length=30) db_cascade = models.ForeignKey( RelatedDbOptionParent, models.DB_CASCADE, related_name="
ass RChildChild(RChild): pass class RelatedDbOptionGrandParent(models.Model): pass class RelatedDbOptionParent(models.Model): p = models.ForeignKey(RelatedDbOptionGrandParent, models.DB_CASCADE, null=True) cl
{ "filepath": "tests/delete/models.py", "language": "python", "file_size": 7803, "cut_index": 716, "middle_length": 229 }
User, create_a, get_default_r, ) class OnDeleteTests(TestCase): def setUp(self): self.DEFAULT = get_default_r() def test_auto(self): a = create_a("auto") a.auto.delete() self.assertFalse(A.objects.filter(name="auto").exists()) def test_non_callable(self): ...
ble").exists()) def test_setvalue(self): a = create_a("setvalue") a.setvalue.delete() a = A.objects.get(pk=a.pk) self.assertEqual(self.DEFAULT, a.setvalue.pk) def test_setnull(self): a = create_a("setnull")
, msg): models.OneToOneField("self", on_delete=None) def test_auto_nullable(self): a = create_a("auto_nullable") a.auto_nullable.delete() self.assertFalse(A.objects.filter(name="auto_nulla
{ "filepath": "tests/delete/tests.py", "language": "python", "file_size": 33076, "cut_index": 1331, "middle_length": 229 }
datetime from django.db import models from django.test import TestCase from django.test.utils import isolate_apps from .models import InternationalArticle class SimpleTests(TestCase): def test_international(self): a = InternationalArticle.objects.create( headline="Girl wins €12.500 in lotte...
tr__/__repr__ to make sure str()/repr() don't # coerce the returned value. self.assertIsInstance(obj.__str__(), str) self.assertIsInstance(obj.__repr__(), str) self.assertEqual(str(obj), "Default object (None)") self
""" The default implementation of __str__ and __repr__ should return instances of str. """ class Default(models.Model): pass obj = Default() # Explicit call to __s
{ "filepath": "tests/str/tests.py", "language": "python", "file_size": 1230, "cut_index": 518, "middle_length": 229 }
check if the order is preserved. SOME_INSTALLED_APPS = [ "apps.apps.MyAdmin", "apps.apps.MyAuth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] SOME_INSTALLED_APPS_NAMES = [ "django.contrib.admin", "django.contrib....
istry is always ready when the tests run. self.assertIs(apps.ready, True) # Non-main app registries are populated in __init__. self.assertIs(Apps().ready, True) # The condition is set when apps are ready self.assertI
""" with self.assertRaises(RuntimeError): Apps(installed_apps=None) def test_ready(self): """ Tests the ready property of the main registry. """ # The main app reg
{ "filepath": "tests/apps/tests.py", "language": "python", "file_size": 24758, "cut_index": 1331, "middle_length": 229 }
port connections class BaseAppConfig(AppConfig): name = "apps.query_performing_app" database = "default" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.query_results = [] def ready(self): self.query_results = [] self._perform_query() ...
database = "default" class QueryOtherDatabaseModelAppConfig(ModelQueryAppConfig): database = "other" class CursorQueryAppConfig(BaseAppConfig): def _perform_query(self): connection = connections[self.database] with connection
et = TotallyNormal.objects.using(self.database) queryset.update_or_create(name="new name") self.query_results = list(queryset.values_list("name")) class QueryDefaultDatabaseModelAppConfig(ModelQueryAppConfig):
{ "filepath": "tests/apps/query_performing_app/apps.py", "language": "python", "file_size": 2672, "cut_index": 563, "middle_length": 229 }
l=True) unit = models.CharField(max_length=15, null=True) class Meta: required_db_features = { "supports_table_check_constraints", } constraints = [ models.CheckConstraint( condition=models.Q(price__gt=models.F("discounted_price")), ...
it_list", ), ] class GeneratedFieldStoredProduct(models.Model): name = models.CharField(max_length=255, null=True) price = models.IntegerField(null=True) discounted_price = models.IntegerField(null=True) rebate = model
", ), models.CheckConstraint( condition=models.Q( models.Q(unit__isnull=True) | models.Q(unit__in=["μg/mL", "ng/mL"]) ), name="unicode_un
{ "filepath": "tests/constraints/models.py", "language": "python", "file_size": 5258, "cut_index": 716, "middle_length": 229 }
_sql(self): c = BaseConstraint(name="name") msg = "This method must be implemented by a subclass." with self.assertRaisesMessage(NotImplementedError, msg): c.remove_sql(None, None) def test_validate(self): c = BaseConstraint(name="name") msg = "This method must b...
name="base_name", violation_error_message="custom %(name)s message" ) self.assertEqual(c.get_violation_error_message(), "custom base_name message") def test_custom_violation_error_message_clone(self): constraint = BaseC
= BaseConstraint(name="name") self.assertEqual( c.get_violation_error_message(), "Constraint “name” is violated." ) def test_custom_violation_error_message(self): c = BaseConstraint(
{ "filepath": "tests/constraints/tests.py", "language": "python", "file_size": 60302, "cut_index": 2151, "middle_length": 229 }
ib.auth.forms import AuthenticationForm from django.contrib.auth.urls import urlpatterns as auth_urlpatterns from django.contrib.auth.views import LoginView from django.contrib.messages.api import info from django.http import HttpRequest, HttpResponse from django.shortcuts import render from django.template import Requ...
uper().__init__(request, *args, **kwargs) @never_cache def remote_user_auth_view(request): "Dummy view for remote user tests" t = Template("Username is {{ user }}.") c = RequestContext(request, {}) return HttpResponse(t.render(c)) def a
mport never_cache from django.views.i18n import set_language class CustomRequestAuthenticationForm(AuthenticationForm): def __init__(self, request, *args, **kwargs): assert isinstance(request, HttpRequest) s
{ "filepath": "tests/auth_tests/urls.py", "language": "python", "file_size": 8334, "cut_index": 716, "middle_length": 229 }
eturn "(%s) %%%% 3 = %s" % (lhs, rhs), params def as_oracle(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = (*lhs_params, *rhs_params) return "mod(%s, 3) = %s" % (lhs, rhs), param...
): bilateral = True class Mult3BilateralTransform(models.Transform): bilateral = True lookup_name = "mult3" def as_sql(self, compiler, connection): lhs, lhs_params = compiler.compile(self.lhs) return "3 * (%s)" % lhs, lhs
3" % lhs, lhs_params def as_oracle(self, compiler, connection, **extra_context): lhs, lhs_params = compiler.compile(self.lhs) return "mod(%s, 3)" % lhs, lhs_params class Div3BilateralTransform(Div3Transform
{ "filepath": "tests/custom_lookups/tests.py", "language": "python", "file_size": 32050, "cut_index": 1331, "middle_length": 229 }
m django.apps import apps from django.contrib.sites.models import Site from django.core.cache import cache from django.test import TestCase, modify_settings, override_settings from .models import I18nTestModel, TestModel @modify_settings(INSTALLED_APPS={"append": "django.contrib.sitemaps"}) @override_settings(ROOT_U...
ame="Test Object") def setUp(self): self.base_url = "%s://%s" % (self.protocol, self.domain) cache.clear() @classmethod def setUpClass(cls): super().setUpClass() # This cleanup is necessary because contrib.site
nstalled else "testserver" @classmethod def setUpTestData(cls): # Create an object for sitemap content. TestModel.objects.create(name="Test Object") cls.i18n_model = I18nTestModel.objects.create(n
{ "filepath": "tests/sitemaps_tests/base.py", "language": "python", "file_size": 1103, "cut_index": 515, "middle_length": 229 }
ort override_settings from .base import SitemapTestsBase from .models import TestModel @override_settings(ABSOLUTE_URL_OVERRIDES={}) class GenericViewsSitemapTests(SitemapTestsBase): def test_generic_sitemap_attributes(self): datetime_value = datetime.now() queryset = TestModel.objects.all() ...
", "https"), ) for attr_name, expected_value in attr_values: with self.subTest(attr_name=attr_name): self.assertEqual(getattr(generic_sitemap, attr_name), expected_value) self.assertCountEqual(generic_sit
changefreq="monthly", protocol="https", ) attr_values = ( ("date_field", datetime_value), ("priority", 0.6), ("changefreq", "monthly"), ("protocol
{ "filepath": "tests/sitemaps_tests/test_generic.py", "language": "python", "file_size": 3841, "cut_index": 614, "middle_length": 229 }
emapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap><loc>%s/simple/sitemap-simple.xml</loc><lastmod>%s</lastmod></sitemap> </sitemapindex> """ % ( self.base_url, date.today(), ) self.assertXMLEqual(response.text, expected_content) def test_sitemap_not_cal...
) self.assertXMLEqual(response.text, expected_content) def test_paged_sitemap(self): """A sitemap may have multiple pages.""" response = self.client.get("/simple-paged/index.xml") expected_content = """<?xml vers
"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap><loc>%s/simple/sitemap-simple.xml</loc><lastmod>%s</lastmod></sitemap> </sitemapindex> """ % ( self.base_url, date.today(),
{ "filepath": "tests/sitemaps_tests/test_http.py", "language": "python", "file_size": 25765, "cut_index": 1331, "middle_length": 229 }
override_settings from .base import SitemapTestsBase @override_settings(ROOT_URLCONF="sitemaps_tests.urls.https") class HTTPSSitemapTests(SitemapTestsBase): protocol = "https" def test_secure_sitemap_index(self): "A secure sitemap index can be rendered" response = self.client.get("/secure/in...
"A secure sitemap section can be rendered" response = self.client.get("/secure/sitemap-simple.xml") expected_content = ( '<?xml version="1.0" encoding="UTF-8"?>\n' '<urlset xmlns="http://www.sitemaps.org/schemas
c><lastmod>%s</lastmod></sitemap> </sitemapindex> """ % ( self.base_url, date.today(), ) self.assertXMLEqual(response.text, expected_content) def test_secure_sitemap_section(self):
{ "filepath": "tests/sitemaps_tests/test_https.py", "language": "python", "file_size": 2929, "cut_index": 563, "middle_length": 229 }
priority = 0.5 location = "/location/" lastmod = date.today() def items(self): return [object()] class SimplePagedSitemap(Sitemap): lastmod = date.today() def items(self): return [object() for x in range(Sitemap.limit + 1)] class SimpleI18nSitemap(Sitemap): changefreq =...
item(self, item): if item.name == "Only for PT": return ["pt"] return super().get_languages_for_item(item) class ItemByLangAlternatesSitemap(AlternatesI18nSitemap): x_default = True def get_languages_for_item(self, it
rue class LimitedI18nSitemap(AlternatesI18nSitemap): languages = ["en", "es"] class XDefaultI18nSitemap(AlternatesI18nSitemap): x_default = True class ItemByLangSitemap(SimpleI18nSitemap): def get_languages_for_
{ "filepath": "tests/sitemaps_tests/urls/http.py", "language": "python", "file_size": 12033, "cut_index": 921, "middle_length": 229 }
(self, val, **kwargs): return val a_signal = Signal() b_signal = Signal() c_signal = Signal() d_signal = Signal(use_caching=True) class DispatcherTests(SimpleTestCase): def assertTestIsClean(self, signal): """Assert that everything has been cleaned up automatically""" # Note that dead we...
gnal receivers must accept keyword arguments (**kwargs)." with self.assertRaisesMessage(ValueError, msg): a_signal.connect(receiver_no_kwargs) self.assertTestIsClean(a_signal) @override_settings(DEBUG=True) def test_can
e(signal.has_listeners()) self.assertEqual(signal.receivers, []) @override_settings(DEBUG=True) def test_cannot_connect_no_kwargs(self): def receiver_no_kwargs(sender): pass msg = "Si
{ "filepath": "tests/dispatch/tests.py", "language": "python", "file_size": 9827, "cut_index": 921, "middle_length": 229 }
gression tests for proper working of ForeignKey(null=True). """ from django.db import models class SystemDetails(models.Model): details = models.TextField() class SystemInfo(models.Model): system_details = models.ForeignKey(SystemDetails, models.CASCADE) system_name = models.CharField(max_length=32) ...
comment_text = models.CharField(max_length=250) class Meta: ordering = ("comment_text",) # Ticket 15823 class Item(models.Model): title = models.CharField(max_length=100) class PropertyValue(models.Model): label = models.Char
gnKey(Forum, models.SET_NULL, null=True) title = models.CharField(max_length=32) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, models.SET_NULL, null=True)
{ "filepath": "tests/null_fk/models.py", "language": "python", "file_size": 1246, "cut_index": 518, "middle_length": 229 }
gth=255) parent = models.ForeignKey("self", models.CASCADE) class Message(models.Model): from_field = models.ForeignKey(People, models.CASCADE, db_column="from_id") author = models.ForeignKey(People, models.CASCADE, related_name="message_authors") class PeopleData(models.Model): people_pk = models.F...
eopleMoreData, models.CASCADE, to_field="people_unique", ) class DigitsInColumnName(models.Model): all_digits = models.CharField(max_length=11, db_column="123") leading_digit = models.CharField(max_length=11, db_column="4extra
, unique=True) message = models.ForeignKey(Message, models.CASCADE, blank=True, null=True) license = models.CharField(max_length=255) class ForeignKeyToField(models.Model): to_field_fk = models.ForeignKey( P
{ "filepath": "tests/inspectdb/models.py", "language": "python", "file_size": 5937, "cut_index": 716, "middle_length": 229 }
ving models custom methods Any method you add to a model will be available to instances. """ import datetime from django.db import models class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() def __str__(self): return self.headline def was_...
port connection with connection.cursor() as cursor: cursor.execute( """ SELECT id, headline, pub_date FROM custom_methods_article WHERE pub_date = %s A
elf.id) def articles_from_same_day_2(self): """ Verbose version of get_articles_from_same_day_1, which does a custom database query for the sake of demonstration. """ from django.db im
{ "filepath": "tests/custom_methods/models.py", "language": "python", "file_size": 1184, "cut_index": 518, "middle_length": 229 }
ptyModelMixin, EmptyModelVisible, ExplicitlyProvidedPK, ExternalSubscriber, Fabric, FancyDoodad, FieldOverridePost, FilteredManager, FooAccount, FoodDelivery, FunkyTag, Gadget, Gallery, GenRelReference, GetQuerySetModel, Grommet, ImplicitlyGeneratedPK, ...
cast, Post, PrePopulatedPost, PrePopulatedPostLargeSlug, PrePopulatedSubPost, Promo, Question, ReadablePizza, ReadOnlyPizza, ReadOnlyRelatedField, Recipe, Recommendation, Recommender, ReferencedByGenRel,
bscriber, OtherStory, Paper, Parent, ParentWithDependentChildren, ParentWithUUIDPK, Person, Persona, Picture, Pizza, Plot, PlotDetails, PlotProxy, PluggableSearchPerson, Pod
{ "filepath": "tests/admin_views/admin.py", "language": "python", "file_size": 43776, "cut_index": 2151, "middle_length": 229 }
n from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.http import HttpResponse from django.urls import path from . import admin as base_admin from . import forms, models class Admin2(admin.AdminSite): app_index_template = "custom_admin/app_index.html" login...
ge_done.html" # A custom index view. def index(self, request, extra_context=None): return super().index(request, {"foo": "*bar*"}) def get_urls(self): return [ path("my_view/", self.admin_view(self.my_view), name="
a list, to test fix for #18697 password_change_form = forms.CustomAdminPasswordChangeForm password_change_template = "custom_admin/password_change_form.html" password_change_done_template = "custom_admin/password_chan
{ "filepath": "tests/admin_views/customadmin.py", "language": "python", "file_size": 3238, "cut_index": 614, "middle_length": 229 }
turn self.name class Article(models.Model): """ A simple article to test admin views. Test backwards compatibility. """ title = models.CharField(max_length=100) content = models.TextField() date = models.DateTimeField() section = models.ForeignKey(Section, models.CASCADE, null=True, blank...
y(ordering="-date", description="") def model_year_reversed(self): return self.date.year @property @admin.display(ordering="date") def model_property_year(self): return self.date.year @property def model_month(self
NULL, null=True, blank=True, related_name="+" ) def __str__(self): return self.title @admin.display(ordering="date", description="") def model_year(self): return self.date.year @admin.displa
{ "filepath": "tests/admin_views/models.py", "language": "python", "file_size": 31136, "cut_index": 1331, "middle_length": 229 }
.contrib.auth.migrations.0011_update_proxy_permissions" ) class ProxyModelWithDifferentAppLabelTests(TransactionTestCase): available_apps = [ "auth_tests", "django.contrib.auth", "django.contrib.contenttypes", ] def setUp(self): """ Create proxy permissions with co...
name="Can add userproxy", ) self.custom_permission = Permission.objects.create( content_type=self.concrete_content_type, codename="use_different_app_label", name="May use a different app label",
lf.concrete_content_type = ContentType.objects.get_for_model(UserProxy) self.default_permission = Permission.objects.create( content_type=self.concrete_content_type, codename="add_userproxy",
{ "filepath": "tests/auth_tests/test_migrations.py", "language": "python", "file_size": 10864, "cut_index": 921, "middle_length": 229 }
ws.generic import View class AlwaysTrueMixin(UserPassesTestMixin): def test_func(self): return True class AlwaysFalseMixin(UserPassesTestMixin): def test_func(self): return False class EmptyResponseView(View): def get(self, request, *args, **kwargs): return HttpResponse() cla...
in, EmptyResponseView ): permission_required = ["auth_tests.add_customuser", "auth_tests.change_customuser"] raise_exception = True class AccessMixinTests(TestCase): factory = RequestFactory() def test_stacked_mixins_success(self):
ssionRequiredMixin, EmptyResponseView ): permission_required = ["auth_tests.add_customuser", "auth_tests.change_customuser"] raise_exception = True class StackedMixinsView2( PermissionRequiredMixin, LoginRequiredMix
{ "filepath": "tests/auth_tests/test_mixins.py", "language": "python", "file_size": 10043, "cut_index": 921, "middle_length": 229 }
.auth.models import User from django.core.exceptions import FieldDoesNotExist from django.test import TestCase, override_settings from django.test.client import RequestFactory from .models import MinimalUser, UserWithDisabledLastLoginField @override_settings(ROOT_URLCONF="auth_tests.urls") class SignalTestCase(TestC...
, sender, **kwargs): self.login_failed.append(kwargs) def setUp(self): """Set up the listeners and reset the logged in/logged out counters""" self.logged_in = [] self.logged_out = [] self.login_failed = []
ff", password="password") def listener_login(self, user, **kwargs): self.logged_in.append(user) def listener_logout(self, user, **kwargs): self.logged_out.append(user) def listener_login_failed(self
{ "filepath": "tests/auth_tests/test_signals.py", "language": "python", "file_size": 4892, "cut_index": 614, "middle_length": 229 }
hashers import make_password from django.contrib.auth.templatetags.auth import render_password_as_hash from django.test import SimpleTestCase, override_settings class RenderPasswordAsHashTests(SimpleTestCase): @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.PBKDF2PasswordHasher"] ) ...
ng>: <bdi>WmCkn9**************************************" "</bdi></p>" ) self.assertEqual(render_password_as_hash(value), hashed_html) def test_invalid_password(self): expected = ( "<p><strong>Invalid pass
( "<p><strong>algorithm</strong>: <bdi>pbkdf2_sha256</bdi> " "<strong>iterations</strong>: <bdi>100000</bdi> " "<strong>salt</strong>: <bdi>a6Pucb******</bdi> " "<strong>hash</stro
{ "filepath": "tests/auth_tests/test_templatetags.py", "language": "python", "file_size": 1574, "cut_index": 537, "middle_length": 229 }
f.assertNotIn(SESSION_KEY, self.client.session) def assertFormError(self, response, error): """Assert that error is found in response.context['form'] errors""" form_errors = list(itertools.chain(*response.context["form"].errors.values())) self.assertIn(str(error), form_errors) @override_s...
done", [], {}), ( "password_reset_confirm", [], { "uidb64": "aaaaaaa", "token": "1111-aaaaa", }, ), ("password_reset
_urls = [ ("login", [], {}), ("logout", [], {}), ("password_change", [], {}), ("password_change_done", [], {}), ("password_reset", [], {}), ("password_reset_
{ "filepath": "tests/auth_tests/test_views.py", "language": "python", "file_size": 70424, "cut_index": 3790, "middle_length": 229 }
ators_help_text_html, password_validators_help_texts, validate_password, ) from django.core.exceptions import ImproperlyConfigured, ValidationError from django.db import models from django.test import SimpleTestCase, TestCase, override_settings from django.test.utils import isolate_apps from django.utils.html i...
t_password_validators(self): validators = get_default_password_validators() self.assertEqual(len(validators), 2) self.assertEqual(validators[0].__class__.__name__, "CommonPasswordValidator") self.assertEqual(validators[1].__
"django.contrib.auth.password_validation.MinimumLengthValidator", "OPTIONS": { "min_length": 12, }, }, ] ) class PasswordValidationTest(SimpleTestCase): def test_get_defaul
{ "filepath": "tests/auth_tests/test_validators.py", "language": "python", "file_size": 16325, "cut_index": 921, "middle_length": 229 }
e CustomPermissionsUser users email as the identifier, but uses the normal Django permissions model. This allows us to check that the PermissionsMixin includes everything that is needed to interact with the ModelBackend. """ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db impor...
missionsUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name="email address", max_length=255, unique=True ) date_of_birth = models.DateField() custom_objects = CustomPermissionsUserM
f_birth): u = self.create_user(email, password=password, date_of_birth=date_of_birth) u.is_superuser = True u.save(using=self._db) return u with RemoveGroupsAndPermissions(): class CustomPer
{ "filepath": "tests/auth_tests/models/custom_permissions.py", "language": "python", "file_size": 1148, "cut_index": 518, "middle_length": 229 }
django.db import models # No related name is needed here, since symmetrical relations are not # explicitly reversible. class SelfRefer(models.Model): name = models.CharField(max_length=10) references = models.ManyToManyField("self") related = models.ManyToManyField("self") def __str__(self): ...
cause # they are both addressable as reverse relations from Tag. class Entry(models.Model): name = models.CharField(max_length=10) topics = models.ManyToManyField(Tag) related = models.ManyToManyField(Tag, related_name="similar") def __str
class class TagCollection(Tag): tags = models.ManyToManyField(Tag, related_name="tag_collections") def __str__(self): return self.name # A related_name is required on one of the ManyToManyField entries here be
{ "filepath": "tests/m2m_regress/models.py", "language": "python", "file_size": 2624, "cut_index": 563, "middle_length": 229 }
ferChildSibling, Tag, TagCollection, Worksheet, ) class M2MRegressionTests(TestCase): def test_multiple_m2m(self): # Multiple m2m references to model must be distinguished when # accessing the relations through an instance attribute. s1 = SelfRefer.objects.create(name="s1") ...
quenceEqual(s1.related.all(), [s3]) self.assertSequenceEqual(e1.topics.all(), [t1]) self.assertSequenceEqual(e1.related.all(), [t2]) def test_internal_related_name_not_in_error_msg(self): # The secret internal related names fo
="e1") t1 = Tag.objects.create(name="t1") t2 = Tag.objects.create(name="t2") e1.topics.add(t1) e1.related.add(t2) self.assertSequenceEqual(s1.references.all(), [s2]) self.assertSe
{ "filepath": "tests/m2m_regress/tests.py", "language": "python", "file_size": 5102, "cut_index": 716, "middle_length": 229 }
atetime import date from django.test import TestCase from .models import Article class MethodsTests(TestCase): def test_custom_methods(self): a = Article.objects.create( headline="Parrot programs in Python", pub_date=date(2005, 7, 27) ) b = Article.objects.create( ...
te", ], lambda a: a.headline, ) self.assertQuerySetEqual( b.articles_from_same_day_1(), [ "Parrot programs in Python", ], lambda a: a.headline,
[ "Beatles reunite", ], lambda a: a.headline, ) self.assertQuerySetEqual( a.articles_from_same_day_2(), [ "Beatles reuni
{ "filepath": "tests/custom_methods/tests.py", "language": "python", "file_size": 1200, "cut_index": 518, "middle_length": 229 }
forms import AdminAuthenticationForm, AdminPasswordChangeForm from django.contrib.admin.helpers import ActionForm from django.core.exceptions import ValidationError from .models import Section class CustomAdminAuthenticationForm(AdminAuthenticationForm): class Media: css = {"all": ("path/to/media.css",)}...
class MediaActionForm(ActionForm): class Media: js = ["path/to/media.js"] class SectionFormWithOptgroups(forms.ModelForm): articles = forms.ChoiceField( choices=[ ("Published", [("1", "Test Article")]), ("
username class CustomAdminPasswordChangeForm(AdminPasswordChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["old_password"].label = "Custom old password label"
{ "filepath": "tests/admin_views/forms.py", "language": "python", "file_size": 2709, "cut_index": 563, "middle_length": 229 }
uest, HttpResponse from django.test import TestCase, modify_settings, override_settings from django.urls import reverse class TestAuthenticationMiddleware(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user( "test_user", "test@example.com", "test_password" ...
elf): self.request.session = self.client.session self.middleware(self.request) self.assertIsNotNone(self.request.user) self.assertFalse(self.request.user.is_anonymous) def test_changed_password_invalidates_session(self)
iddleware(lambda req: HttpResponse()) self.client.force_login(self.user) self.request = HttpRequest() self.request.session = self.client.session def test_no_password_change_doesnt_invalidate_session(s
{ "filepath": "tests/auth_tests/test_middleware.py", "language": "python", "file_size": 10394, "cut_index": 921, "middle_length": 229 }
s") class RemoteUserTest(TestCase): middleware = "django.contrib.auth.middleware.RemoteUserMiddleware" backend = "django.contrib.auth.backends.RemoteUserBackend" # ASGI tests always provide this value via `headers`. # WSGI tests provide this value directly into the environ via `**extra`. # When sub...
ownuser" known_user2 = "knownuser2" @classmethod def setUpClass(cls): cls.enterClassContext( modify_settings( AUTHENTICATION_BACKENDS={"append": cls.backend}, MIDDLEWARE={"append": cls.middle
WSGI, and only when # the value is exactly "REMOTE_USER". header = "REMOTE_USER" email_header = "HTTP_REMOTE_EMAIL" # Usernames to be passed in REMOTE_USER for the test_known_user test case. known_user = "kn
{ "filepath": "tests/auth_tests/test_remote_user.py", "language": "python", "file_size": 27118, "cut_index": 1331, "middle_length": 229 }