prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
s, so the tests don't fail when run with a backend other than PostgreSQL. """ import enum from django.db import models try: from django.contrib.postgres.fields import ( ArrayField, BigIntegerRangeField, DateRangeField, DateTimeRangeField, DecimalRangeField, HStoreF...
"base_field": "", "size": 1, } ) return name, path, args, kwargs class DummyContinuousRangeField(models.Field): def __init__(self, *args, default_bounds="[)", **kwarg
__init__(self, base_field, size=None, **kwargs): super().__init__(**kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() kwargs.update( {
{ "filepath": "tests/postgres_tests/fields.py", "language": "python", "file_size": 2062, "cut_index": 563, "middle_length": 229 }
RangeField, OffByOneField, SearchVectorField, ) class Tag: def __init__(self, tag_id): self.tag_id = tag_id def __eq__(self, other): return isinstance(other, Tag) and self.tag_id == other.tag_id class TagField(models.SmallIntegerField): def from_db_value(self, value, expression,...
required_db_vendor = "postgresql" class IntegerArrayModel(PostgreSQLModel): field = ArrayField(models.BigIntegerField(), default=list, blank=True) class NullableIntegerArrayModel(PostgreSQLModel): field = ArrayField(models.BigIntegerField(),
if value is None: return value return Tag(int(value)) def get_prep_value(self, value): return value.tag_id class PostgreSQLModel(models.Model): class Meta: abstract = True
{ "filepath": "tests/postgres_tests/models.py", "language": "python", "file_size": 6379, "cut_index": 716, "middle_length": 229 }
signals import connection_created from django.db.migrations.writer import MigrationWriter from django.test import TestCase from django.test.utils import CaptureQueriesContext, modify_settings, override_settings try: from django.contrib.postgres.fields import ( DateRangeField, DateTimeRangeField, ...
ostgresConfigTests(TestCase): def test_install_app_no_warning(self): # Clear cache to force queries when (re)initializing the # "django.contrib.postgres" app. get_hstore_oids.cache_clear() with CaptureQueriesContext(conn
teRange, DateTimeRange, DateTimeTZRange, NumericRange, is_psycopg3, ) except ImportError: pass @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests") class P
{ "filepath": "tests/postgres_tests/test_apps.py", "language": "python", "file_size": 3654, "cut_index": 614, "middle_length": 229 }
solate_apps("postgres_tests") class BasicTests(PostgreSQLSimpleTestCase): def test_get_field_display(self): class MyModel(PostgreSQLModel): field = ArrayField( models.CharField(max_length=16), choices=[ ["Media", [(["vinyl", "cd"], "Audio")]], ...
self.assertEqual(instance.get_field_display(), display) def test_get_field_display_nested_array(self): class MyModel(PostgreSQLModel): field = ArrayField( ArrayField(models.CharField(max_length=16)),
(("a", "b"), "('a', 'b')"), (["c", "d"], "['c', 'd']"), ) for value, display in tests: with self.subTest(value=value, display=display): instance = MyModel(field=value)
{ "filepath": "tests/postgres_tests/test_array.py", "language": "python", "file_size": 59869, "cut_index": 2151, "middle_length": 229 }
s GEOSIOTest(SimpleTestCase): def test01_wktreader(self): # Creating a WKTReader instance wkt_r = WKTReader() wkt = "POINT (5 23)" # read() should return a GEOSGeometry ref = GEOSGeometry(wkt) g1 = wkt_r.read(wkt.encode()) g2 = wkt_r.read(wkt) for ge...
r, msg.format(bad_wkt)), ): wkt_r.read(bad_wkt) def test02_wktwriter(self): # Creating a WKTWriter instance, testing its ptr property. wkt_w = WKTWriter() msg = "Incompatible pointer type: "
emoryview(b"foo")) msg = "'wkt' must be bytes or str (got {} instead)." for bad_wkt in bad_input: with ( self.subTest(bad_wkt=bad_wkt), self.assertRaisesMessage(TypeErro
{ "filepath": "tests/gis_tests/geos_tests/test_io.py", "language": "python", "file_size": 8763, "cut_index": 716, "middle_length": 229 }
available_apps = ["gis_tests.rasterapp"] def setUp(self): rast = GDALRaster( { "srid": 4326, "origin": [0, 0], "scale": [-1, 1], "skew": [0, 0], "width": 5, "height": 5, "nr_of_ba...
where the RasterField has a null value. """ r = RasterModel.objects.create(rast=None) r.refresh_from_db() self.assertIsNone(r.rast) def test_access_band_data_directly_from_queryset(self): RasterModel.objects.cre
rastprojected=rast, geom="POINT (-95.37040 29.70486)", ) RasterRelatedModel.objects.create(rastermodel=model_instance) def test_field_null_value(self): """ Test creating a model
{ "filepath": "tests/gis_tests/rasterapp/test_rasterfield.py", "language": "python", "file_size": 19301, "cut_index": 1331, "middle_length": 229 }
rations.CreateModel( name="Neighborhood", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ...
auto_created=True, primary_key=True, ), ), ( "neighborhood", models.ForeignKey( "gis_migrations.Neighborhood",
, ), migrations.CreateModel( name="Household", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False,
{ "filepath": "tests/gis_tests/gis_migrations/migrations/0002_create_models.py", "language": "python", "file_size": 3047, "cut_index": 614, "middle_length": 229 }
rror: Image = None else: temp_storage_dir = tempfile.mkdtemp() temp_storage = FileSystemStorage(temp_storage_dir) class MyFileField(models.FileField): pass class Member(models.Model): name = models.CharField(max_length=100) birthdate = models.DateTimeField(blank=True, null=True) gender =...
.ManyToManyField(Member) def __str__(self): return self.name class UnsafeLimitChoicesTo(models.Model): band = models.ForeignKey( Band, models.CASCADE, limit_choices_to={"name": '"&><escapeme'}, ) class Album
class Artist(models.Model): pass class Band(Artist): uuid = models.UUIDField(unique=True, default=uuid.uuid4) name = models.CharField(max_length=100) style = models.CharField(max_length=20) members = models
{ "filepath": "tests/admin_widgets/models.py", "language": "python", "file_size": 5796, "cut_index": 716, "middle_length": 229 }
g signals before/after saving and deleting. """ from django.db import models class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Car(models.Model): m...
class Book(models.Model): name = models.CharField(max_length=20) authors = models.ManyToManyField(Author) def __str__(self): return self.name class Page(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE)
n self.name
{ "filepath": "tests/signals/models.py", "language": "python", "file_size": 818, "cut_index": 522, "middle_length": 14 }
"Club") class YearInSchool(models.TextChoices): FRESHMAN = "FR", _("Freshman") SOPHOMORE = "SO", _("Sophomore") JUNIOR = "JR", _("Junior") SENIOR = "SR", _("Senior") GRADUATE = "GR", _("Graduate") class Vehicle(models.IntegerChoices): CAR = 1, "Carriage" TRUCK = 2 JET_SKI = 3 __...
self.assertEqual(Suit.values, [1, 2, 3, 4]) self.assertEqual(Suit.names, ["DIAMOND", "SPADE", "HEART", "CLUB"]) self.assertEqual(repr(Suit.DIAMOND), "Suit.DIAMOND") self.assertEqual(Suit.DIAMOND.label, "Diamond") self
ef test_integerchoices(self): self.assertEqual( Suit.choices, [(1, "Diamond"), (2, "Spade"), (3, "Heart"), (4, "Club")] ) self.assertEqual(Suit.labels, ["Diamond", "Spade", "Heart", "Club"])
{ "filepath": "tests/model_enums/tests.py", "language": "python", "file_size": 10850, "cut_index": 921, "middle_length": 229 }
ing from django.contrib.postgres.aggregates import ( StringAgg, # RemovedInDjango70Warning. ) from django.contrib.postgres.aggregates import ( ArrayAgg, BoolAnd, BoolOr, Corr, CovarPop, JSONBAgg, RegrAvgX, RegrAvgY, RegrCount, ...
AggregateTestModel( boolean_field=True, char_field="Foo1", text_field="Text1", integer_field=0, ), AggregateTestModel(
eld except ImportError: pass # psycopg2 is not installed class TestGeneralAggregate(PostgreSQLTestCase): @classmethod def setUpTestData(cls): cls.aggs = AggregateTestModel.objects.bulk_create( [
{ "filepath": "tests/postgres_tests/test_aggregates.py", "language": "python", "file_size": 32716, "cut_index": 1331, "middle_length": 229 }
om django.test.utils import isolate_apps from . import PostgreSQLTestCase from .fields import ( BigIntegerRangeField, DateRangeField, DateTimeRangeField, DecimalRangeField, HStoreField, IntegerRangeField, SearchVectorField, ) from .models import IntegerArrayModel, NestedIntegerArrayModel, P...
def _make_error(self, obj, klass_name): """Helper to create postgres.E005 error for specific objects.""" return checks.Error( "'django.contrib.postgres' must be in INSTALLED_APPS in order to " f"use {klass_name}.",
es.indexes import GinIndex, PostgresIndex from django.contrib.postgres.search import SearchQueryField except ImportError: pass @isolate_apps("postgres_tests") class TestPostgresAppInstalledCheck(PostgreSQLTestCase):
{ "filepath": "tests/postgres_tests/test_app_installed_check.py", "language": "python", "file_size": 4945, "cut_index": 614, "middle_length": 229 }
m django.db import connection from django.test import TransactionTestCase class MigrateTests(TransactionTestCase): """ Tests running the migrate command in GeoDjango. """ available_apps = ["gis_tests.gis_migrations"] def get_table_description(self, table): with connection.cursor() as cur...
def test_migrate_gis(self): """ Tests basic usage of the migrate command when a model uses GeoDjango fields (#22001). It's also used to showcase an error in migrations where spatialite is enabled and geo tables
rtIn(table, connection.introspection.table_names(cursor)) def assertTableNotExists(self, table): with connection.cursor() as cursor: self.assertNotIn(table, connection.introspection.table_names(cursor))
{ "filepath": "tests/gis_tests/gis_migrations/test_commands.py", "language": "python", "file_size": 2491, "cut_index": 563, "middle_length": 229 }
ue"), True) self.assertIs(cache.add("addkey1", "newvalue"), True) self.assertIsNone(cache.get("addkey1")) def test_non_existent(self): "Nonexistent keys aren't found in the dummy cache backend" self.assertIsNone(cache.get("does_not_exist")) self.assertEqual(cache.get("does_n...
with self.assertWarnsMessage(CacheKeyWarning, msg): cache.get_many(["key with spaces"]) def test_delete(self): "Cache deletion is transparently ignored on the dummy cache backend" cache.set_many({"key1": "spam", "ke
self.assertEqual(cache.get_many(["a", "c", "d"]), {}) self.assertEqual(cache.get_many(["a", "b", "e"]), {}) def test_get_many_invalid_key(self): msg = KEY_ERRORS_WITH_MEMCACHED_MSG % ":1:key with spaces"
{ "filepath": "tests/cache/tests.py", "language": "python", "file_size": 120585, "cut_index": 3790, "middle_length": 229 }
ritanceTests(SimpleTestCase): def test_single_parent(self): class AbstractBase(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class AbstractDescendant(AbstractBase): name = models.CharField(max_length=50) ...
._meta.get_field("name").max_length, 50) def test_multiple_inheritance_allows_inherited_field(self): """ Single layer multiple inheritance is as expected, deriving the inherited field from the first base. """ c
dant): pass self.assertEqual(AbstractDescendant._meta.get_field("name").max_length, 50) self.assertEqual(DerivedChild._meta.get_field("name").max_length, 50) self.assertEqual(DerivedGrandChild
{ "filepath": "tests/model_inheritance/test_abstract_inheritance.py", "language": "python", "file_size": 15654, "cut_index": 921, "middle_length": 229 }
self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb) self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb) # Redundant sanity check. self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid) def test_kml(self): "Testing KML output." for tg in self.geometries....
rtRaisesMessage((GEOSException, ValueError), err.msg), ): fromstr(err.wkt) # Bad WKB with self.assertRaisesMessage( GEOSException, self.error_checking_geom.format("GEOSWKBReader_read_r") ):
geom.kml) def test_errors(self): "Testing the Error handlers." # string-based for err in self.geometries.errors: with ( self.subTest(err=err.wkt), self.asse
{ "filepath": "tests/gis_tests/geos_tests/test_geos.py", "language": "python", "file_size": 69530, "cut_index": 3790, "middle_length": 229 }
aaaaaaaaaaaaaa", "http://200.8.9.10/", "http://200.8.9.10:8000/test", "http://su--b.valid-----hyphens.com/", "http://example.com?something=value", "http://example.com/index.php?something=value&another=value2", "https://example.com/", "ftp://example.com/", "ftps://example.com/", "http...
, "http://userid@example.com:65535", "http://userid@example.com:65535/", "http://userid:@example.com", "http://userid:@example.com/", "http://userid:@example.com:8080", "http://userid:@example.com:8080/", "http://userid:password
64", "https://www.example.com/foo/?bar=baz&inga=42&quux", "http://✪df.ws/123", "http://userid@example.com", "http://userid@example.com/", "http://userid@example.com:8080", "http://userid@example.com:8080/"
{ "filepath": "tests/validators/tests.py", "language": "python", "file_size": 38139, "cut_index": 2151, "middle_length": 229 }
est from forms_tests.widget_tests.base import WidgetTest from django.db import connection from django.test import SimpleTestCase, TestCase, modify_settings from django.utils.functional import cached_property @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests") # To register type hand...
: @cached_property def default_text_search_config(self): with connection.cursor() as cursor: cursor.execute("SHOW default_text_search_config") row = cursor.fetchone() return row[0] if row else None d
nnection.vendor == "postgresql", "PostgreSQL specific tests") # To register type handlers and locate the widget's template. @modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"}) class PostgreSQLTestCase(TestCase)
{ "filepath": "tests/postgres_tests/__init__.py", "language": "python", "file_size": 1470, "cut_index": 524, "middle_length": 229 }
t admin from .models import ( Advisor, Album, Band, Bee, Car, CarTire, Event, Inventory, Member, Profile, ReleaseEvent, School, Student, User, VideoStream, ) class WidgetAdmin(admin.AdminSite): pass class CarAdmin(admin.ModelAdmin): list_display =...
in.ModelAdmin): raw_id_fields = ["main_band", "supporting_bands"] class AlbumAdmin(admin.ModelAdmin): fields = ( "name", "cover_art", ) readonly_fields = ("cover_art",) class SchoolAdmin(admin.ModelAdmin): filter_ver
== "car": kwargs["queryset"] = Car.objects.filter(owner=request.user) return db_field.formfield(**kwargs) return super().formfield_for_foreignkey(db_field, request, **kwargs) class EventAdmin(adm
{ "filepath": "tests/admin_widgets/widgetadmin.py", "language": "python", "file_size": 1589, "cut_index": 537, "middle_length": 229 }
Variable, VariableDoesNotExist from django.test import SimpleTestCase class VariableResolveLoggingTests(SimpleTestCase): loglevel = logging.DEBUG def test_log_on_variable_does_not_exist_silent(self): class TestObject: class SilentDoesNotExist(Exception): silent_variable_f...
in dir(TestObject) if attr[:2] != "__") def __getitem__(self, item): return self.__dict__[item] with self.assertLogs("django.template", self.loglevel) as cm: Variable("article").resolve(TestObject())
ngine().from_string("") @property def article(self): raise TestObject.SilentDoesNotExist("Attribute does not exist.") def __iter__(self): return (attr for attr
{ "filepath": "tests/template_tests/test_logging.py", "language": "python", "file_size": 2412, "cut_index": 563, "middle_length": 229 }
ultfilters import length from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class LengthTests(SimpleTestCase): @setup({"length01": "{{ list|length }}"}) def test_length01(self): output = self.engine.render_to_string( "length01", ...
self.assertEqual(output, "0") @setup({"length04": "{{ string|length }}"}) def test_length04(self): output = self.engine.render_to_string("length04", {"string": "django"}) self.assertEqual(output, "6") @setup({"length05":
to_string("length02", {"list": []}) self.assertEqual(output, "0") @setup({"length03": "{{ string|length }}"}) def test_length03(self): output = self.engine.render_to_string("length03", {"string": ""})
{ "filepath": "tests/template_tests/filter_tests/test_length.py", "language": "python", "file_size": 1942, "cut_index": 537, "middle_length": 229 }
ks_filter from django.test import SimpleTestCase from django.utils.functional import lazy from django.utils.safestring import mark_safe from ..utils import setup class LinebreaksTests(SimpleTestCase): """ The contents in "linebreaks" are escaped according to the current autoescape setting. """ @...
"{% endautoescape %}" ) } ) def test_linebreaks02(self): output = self.engine.render_to_string( "linebreaks02", {"a": "x&\ny", "b": mark_safe("x&\ny")} ) self.assertEqual(outp
mark_safe("x&\ny")} ) self.assertEqual(output, "<p>x&amp;<br>y</p> <p>x&<br>y</p>") @setup( { "linebreaks02": ( "{% autoescape off %}{{ a|linebreaks }} {{ b|linebreaks }}"
{ "filepath": "tests/template_tests/filter_tests/test_linebreaks.py", "language": "python", "file_size": 2344, "cut_index": 563, "middle_length": 229 }
ultfilters import linebreaksbr from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class LinebreaksbrTests(SimpleTestCase): """ The contents in "linebreaksbr" are escaped according to the current autoescape setting. """ @setup({"linebrea...
"{% endautoescape %}" ) } ) def test_linebreaksbr02(self): output = self.engine.render_to_string( "linebreaksbr02", {"a": "x&\ny", "b": mark_safe("x&\ny")} ) self.assertEqual(output, "x&<br
safe("x&\ny")} ) self.assertEqual(output, "x&amp;<br>y x&<br>y") @setup( { "linebreaksbr02": ( "{% autoescape off %}{{ a|linebreaksbr }} {{ b|linebreaksbr }}"
{ "filepath": "tests/template_tests/filter_tests/test_linebreaksbr.py", "language": "python", "file_size": 1842, "cut_index": 537, "middle_length": 229 }
ers from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class LinenumbersTests(SimpleTestCase): """ The contents of "linenumbers" is escaped according to the current autoescape setting. """ @setup({"linenumbers01": "{{ a|linenumbers }} {...
% autoescape off %}{{ a|linenumbers }} {{ b|linenumbers }}" "{% endautoescape %}" ) } ) def test_linenumbers02(self): output = self.engine.render_to_string( "linenumbers02", {"a":
&lt;two&gt;\nthree")}, ) self.assertEqual( output, "1. one\n2. &lt;two&gt;\n3. three 1. one\n2. &lt;two&gt;\n3. three" ) @setup( { "linenumbers02": ( "{
{ "filepath": "tests/template_tests/filter_tests/test_linenumbers.py", "language": "python", "file_size": 2043, "cut_index": 563, "middle_length": 229 }
jango.template.defaultfilters import ljust from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class LjustTests(SimpleTestCase): @setup( { "ljust01": ( '{% autoescape off %}.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.' ...
02", {"a": "a&b", "b": mark_safe("a&b")} ) self.assertEqual(output, ".a&amp;b . .a&b .") class FunctionTests(SimpleTestCase): def test_ljust(self): self.assertEqual(ljust("test", 10), "test ") self.assertEqual(l
&b")} ) self.assertEqual(output, ".a&b . .a&b .") @setup({"ljust02": '.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.'}) def test_ljust02(self): output = self.engine.render_to_string( "ljust
{ "filepath": "tests/template_tests/filter_tests/test_ljust.py", "language": "python", "file_size": 1210, "cut_index": 518, "middle_length": 229 }
jango.template.defaultfilters import lower from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class LowerTests(SimpleTestCase): @setup( { "lower01": ( "{% autoescape off %}{{ a|lower }} {{ b|lower }}{% endautoescape %...
r02", {"a": "Apple & banana", "b": mark_safe("Apple &amp; banana")} ) self.assertEqual(output, "apple &amp; banana apple &amp; banana") class FunctionTests(SimpleTestCase): def test_lower(self): self.assertEqual(lower("TEST"),
) self.assertEqual(output, "apple & banana apple &amp; banana") @setup({"lower02": "{{ a|lower }} {{ b|lower }}"}) def test_lower02(self): output = self.engine.render_to_string( "lowe
{ "filepath": "tests/template_tests/filter_tests/test_lower.py", "language": "python", "file_size": 1200, "cut_index": 518, "middle_length": 229 }
ultfilters import make_list from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class MakeListTests(SimpleTestCase): """ The make_list filter can destroy existing escaping, so the results are escaped. """ @setup({"make_list01": "{% autoe...
;&#x27;]") @setup( { "make_list03": ( '{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}' "{% endautoescape %}" ) } ) def test_make_list03(self): output
(output, "['&']") @setup({"make_list02": "{{ a|make_list }}"}) def test_make_list02(self): output = self.engine.render_to_string("make_list02", {"a": mark_safe("&")}) self.assertEqual(output, "[&#x27;&amp
{ "filepath": "tests/template_tests/filter_tests/test_make_list.py", "language": "python", "file_size": 1582, "cut_index": 537, "middle_length": 229 }
ultfilters import phone2numeric_filter from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class Phone2numericTests(SimpleTestCase): @setup({"phone2numeric01": "{{ a|phone2numeric }} {{ b|phone2numeric }}"}) def test_phone2numeric01(self): ou...
} ) def test_phone2numeric02(self): output = self.engine.render_to_string( "phone2numeric02", {"a": "<1-800-call-me>", "b": mark_safe("<1-800-call-me>")}, ) self.assertEqual(output, "<1-800-2255-63>
00-2255-63&gt; <1-800-2255-63>") @setup( { "phone2numeric02": ( "{% autoescape off %}{{ a|phone2numeric }} {{ b|phone2numeric }}" "{% endautoescape %}" )
{ "filepath": "tests/template_tests/filter_tests/test_phone2numeric.py", "language": "python", "file_size": 1573, "cut_index": 537, "middle_length": 229 }
efaultfilters import pluralize from django.test import SimpleTestCase from ..utils import setup class PluralizeTests(SimpleTestCase): def check_values(self, *tests): for value, expected in tests: with self.subTest(value=value): output = self.engine.render_to_string("t", {"valu...
ies" }}'}) def test_singular_and_plural_suffix(self): self.check_values(("0", "candies"), ("1", "candy"), ("2", "candies")) class FunctionTests(SimpleTestCase): def test_integers(self): self.assertEqual(pluralize(1), "") s
"vote"), ("2", "votes")) @setup({"t": 'class{{ value|pluralize:"es" }}'}) def test_suffix(self): self.check_values(("0", "classes"), ("1", "class"), ("2", "classes")) @setup({"t": 'cand{{ value|pluralize:"y,
{ "filepath": "tests/template_tests/filter_tests/test_pluralize.py", "language": "python", "file_size": 2288, "cut_index": 563, "middle_length": 229 }
from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class RandomTests(SimpleTestCase): @setup({"random01": "{{ a|random }} {{ b|random }}"}) def test_random01(self): output = self.engine.render_to_string( "random01", {"a": ["a&b",...
mark_safe("a&b")]} ) self.assertEqual(output, "a&b a&b") @setup({"empty_list": "{{ list|random }}"}) def test_empty_list(self): output = self.engine.render_to_string("empty_list", {"list": []}) self.assertEqual(out
f %}{{ a|random }} {{ b|random }}{% endautoescape %}" ) } ) def test_random02(self): output = self.engine.render_to_string( "random02", {"a": ["a&b", "a&b"], "b": [mark_safe("a&b"),
{ "filepath": "tests/template_tests/filter_tests/test_random.py", "language": "python", "file_size": 1006, "cut_index": 512, "middle_length": 229 }
jango.template.defaultfilters import rjust from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class RjustTests(SimpleTestCase): @setup( { "rjust01": ( '{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.' ...
02", {"a": "a&b", "b": mark_safe("a&b")} ) self.assertEqual(output, ". a&amp;b. . a&b.") class FunctionTests(SimpleTestCase): def test_rjust(self): self.assertEqual(rjust("test", 10), " test") def test_less_than_st
&b")} ) self.assertEqual(output, ". a&b. . a&b.") @setup({"rjust02": '.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.'}) def test_rjust02(self): output = self.engine.render_to_string( "rjust
{ "filepath": "tests/template_tests/filter_tests/test_rjust.py", "language": "python", "file_size": 1159, "cut_index": 518, "middle_length": 229 }
ultfilters import slice_filter from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class SliceTests(SimpleTestCase): @setup({"slice01": '{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}'}) def test_slice01(self): output = self.engine.render_to_string(...
"b": mark_safe("a&b")} ) self.assertEqual(output, "&b &b") class FunctionTests(SimpleTestCase): def test_zero_length(self): self.assertEqual(slice_filter("abcdefg", "0"), "") def test_index(self): self.assertEqual
pe off %}{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}' "{% endautoescape %}" ) } ) def test_slice02(self): output = self.engine.render_to_string( "slice02", {"a": "a&b",
{ "filepath": "tests/template_tests/filter_tests/test_slice.py", "language": "python", "file_size": 1738, "cut_index": 537, "middle_length": 229 }
ultfilters import slugify from django.test import SimpleTestCase from django.utils.functional import lazy from django.utils.safestring import mark_safe from ..utils import setup class SlugifyTests(SimpleTestCase): """ Running slugify on a pre-escaped string leads to odd behavior, but the result is still ...
ugify }} {{ b|slugify }}"}) def test_slugify02(self): output = self.engine.render_to_string( "slugify02", {"a": "a & b", "b": mark_safe("a &amp; b")} ) self.assertEqual(output, "a-b a-amp-b") class FunctionTests(Si
est_slugify01(self): output = self.engine.render_to_string( "slugify01", {"a": "a & b", "b": mark_safe("a &amp; b")} ) self.assertEqual(output, "a-b a-amp-b") @setup({"slugify02": "{{ a|sl
{ "filepath": "tests/template_tests/filter_tests/test_slugify.py", "language": "python", "file_size": 1913, "cut_index": 537, "middle_length": 229 }
ultfilters import stringformat from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class StringformatTests(SimpleTestCase): """ Notice that escaping is applied *after* any filters, so the string formatting here only needs to deal with pre-escaped...
output, ". a<b. . a<b.") @setup( {"stringformat02": '.{{ a|stringformat:"5s" }}. .{{ b|stringformat:"5s" }}.'} ) def test_stringformat02(self): output = self.engine.render_to_string( "stringformat02", {"a": "a<b",
dautoescape %}' ) } ) def test_stringformat01(self): output = self.engine.render_to_string( "stringformat01", {"a": "a<b", "b": mark_safe("a<b")} ) self.assertEqual(
{ "filepath": "tests/template_tests/filter_tests/test_stringformat.py", "language": "python", "file_size": 1814, "cut_index": 537, "middle_length": 229 }
ultfilters import striptags from django.test import SimpleTestCase from django.utils.functional import lazystr from django.utils.safestring import mark_safe from ..utils import setup class StriptagsTests(SimpleTestCase): @setup({"striptags01": "{{ a|striptags }} {{ b|striptags }}"}) def test_striptags01(self...
oescape %}" ) } ) def test_striptags02(self): output = self.engine.render_to_string( "striptags02", { "a": "<a>x</a> <p><b>y</b></p>", "b": mark_safe("<a>x</a> <p><
</p>"), }, ) self.assertEqual(output, "x y x y") @setup( { "striptags02": ( "{% autoescape off %}{{ a|striptags }} {{ b|striptags }}" "{% endaut
{ "filepath": "tests/template_tests/filter_tests/test_striptags.py", "language": "python", "file_size": 1857, "cut_index": 537, "middle_length": 229 }
aultfilters import time as time_filter from django.test import SimpleTestCase from django.utils import timezone, translation from ..utils import setup from .timezone_utils import TimezoneTestCase class TimeTests(TimezoneTestCase): """ #20693: Timezone support for the time template filter """ @setup(...
6:25") @setup({"time01": '{{ dt|time:"e:O:T:Z" }}'}) def test_time01(self): output = self.engine.render_to_string("time01", {"dt": self.now_tz_i}) self.assertEqual(output, "+0315:+0315:+0315:11700") @setup({"time02": '{{ dt|ti
{"time00_l10n": "{{ dt|time }}"}) def test_time00_l10n(self): with translation.override("fr"): output = self.engine.render_to_string("time00_l10n", {"dt": time(16, 25)}) self.assertEqual(output, "1
{ "filepath": "tests/template_tests/filter_tests/test_time.py", "language": "python", "file_size": 2409, "cut_index": 563, "middle_length": 229 }
import setup from .timezone_utils import TimezoneTestCase class TimesinceTests(TimezoneTestCase): """ #20246 - \xa0 in output avoids line-breaks between value and unit """ # Default compare with datetime.now() @setup({"timesince01": "{{ a|timesince }}"}) def test_timesince01(self): o...
qual(output, "1\xa0day") @setup({"timesince03": "{{ a|timesince }}"}) def test_timesince03(self): output = self.engine.render_to_string( "timesince03", {"a": datetime.now() - timedelta(hours=1, minutes=25, seconds=1
p({"timesince02": "{{ a|timesince }}"}) def test_timesince02(self): output = self.engine.render_to_string( "timesince02", {"a": datetime.now() - timedelta(days=1, minutes=1)} ) self.assertE
{ "filepath": "tests/template_tests/filter_tests/test_timesince.py", "language": "python", "file_size": 6496, "cut_index": 716, "middle_length": 229 }
import setup from .timezone_utils import TimezoneTestCase class TimeuntilTests(TimezoneTestCase): # Default compare with datetime.now() @setup({"timeuntil01": "{{ a|timeuntil }}"}) def test_timeuntil01(self): output = self.engine.render_to_string( "timeuntil01", {"a": datetime.now() +...
st_timeuntil03(self): output = self.engine.render_to_string( "timeuntil03", {"a": (datetime.now() + timedelta(hours=8, minutes=10, seconds=10))}, ) self.assertEqual(output, "8\xa0hours, 10\xa0minutes") #
self.engine.render_to_string( "timeuntil02", {"a": (datetime.now() + timedelta(days=1, seconds=10))} ) self.assertEqual(output, "1\xa0day") @setup({"timeuntil03": "{{ a|timeuntil }}"}) def te
{ "filepath": "tests/template_tests/filter_tests/test_timeuntil.py", "language": "python", "file_size": 5258, "cut_index": 716, "middle_length": 229 }
import title from django.test import SimpleTestCase from ..utils import setup class TitleTests(SimpleTestCase): @setup({"title1": "{{ a|title }}"}) def test_title1(self): output = self.engine.render_to_string("title1", {"a": "JOE'S CRAB SHACK"}) self.assertEqual(output, "Joe&#x27;s Crab Shac...
TestCase): def test_title(self): self.assertEqual(title("a nice title, isn't it?"), "A Nice Title, Isn't It?") def test_unicode(self): self.assertEqual(title("discoth\xe8que"), "Discoth\xe8que") def test_non_string_input(self)
"555 West 53rd Street") class FunctionTests(Simple
{ "filepath": "tests/template_tests/filter_tests/test_title.py", "language": "python", "file_size": 901, "cut_index": 547, "middle_length": 52 }
m django.test import SimpleTestCase from ..utils import setup class TruncatecharsTests(SimpleTestCase): @setup({"truncatechars01": "{{ a|truncatechars:3 }}"}) def test_truncatechars01(self): output = self.engine.render_to_string( "truncatechars01", {"a": "Testing, testing"} ) ...
"truncatechars03", {"a": "Testing, testing"} ) self.assertEqual(output, "Testing, testing") @setup({"truncatechars04": "{{ a|truncatechars:3 }}"}) def test_truncatechars04(self): output = self.engine.render_to_string
02", {"a": "Testing"}) self.assertEqual(output, "Testing") @setup({"truncatechars03": "{{ a|truncatechars:'e' }}"}) def test_fail_silently_incorrect_arg(self): output = self.engine.render_to_string(
{ "filepath": "tests/template_tests/filter_tests/test_truncatechars.py", "language": "python", "file_size": 1076, "cut_index": 515, "middle_length": 229 }
ultfilters import escape from django.test import SimpleTestCase from django.utils.functional import Promise, lazy from django.utils.safestring import mark_safe from ..utils import setup class EscapeTests(SimpleTestCase): """ The "escape" filter works the same whether autoescape is on or off, but it has n...
% endautoescape %}" ) } ) def test_escape02(self): output = self.engine.render_to_string( "escape02", {"a": "x&y", "b": mark_safe("x&y")} ) self.assertEqual(output, "x&amp;y x&y") @setup(
"escape01", {"a": "x&y", "b": mark_safe("x&y")} ) self.assertEqual(output, "x&amp;y x&y") @setup( { "escape02": ( "{% autoescape off %}{{ a|escape }} {{ b|escape }}{
{ "filepath": "tests/template_tests/filter_tests/test_escape.py", "language": "python", "file_size": 1870, "cut_index": 537, "middle_length": 229 }
template.defaultfilters import truncatechars_html from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_truncate_zero(self): self.assertEqual( truncatechars_html( '<p>one <a href="#">two - three <br>four</a> five</p>', 0 ), ...
p>one <a href="#">two …</a></p>', ) def test_truncate3(self): self.assertEqual( truncatechars_html( '<p>one <a href="#">two - three <br>four</a> five</p>', 100 ), '<p>one <a href="#">
"<p>one…</p>", ) def test_truncate2(self): self.assertEqual( truncatechars_html( '<p>one <a href="#">two - three <br>four</a> five</p>', 9 ), '<
{ "filepath": "tests/template_tests/filter_tests/test_truncatechars_html.py", "language": "python", "file_size": 1501, "cut_index": 524, "middle_length": 229 }
ultfilters import truncatewords from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class TruncatewordsTests(SimpleTestCase): @setup( { "truncatewords01": ( '{% autoescape off %}{{ a|truncatewords:"2" }} {{ b|truncatew...
}) def test_truncatewords02(self): output = self.engine.render_to_string( "truncatewords02", {"a": "alpha & bravo", "b": mark_safe("alpha &amp; bravo")}, ) self.assertEqual(output, "alpha &amp; … alpha &a
, {"a": "alpha & bravo", "b": mark_safe("alpha &amp; bravo")}, ) self.assertEqual(output, "alpha & … alpha &amp; …") @setup({"truncatewords02": '{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}'
{ "filepath": "tests/template_tests/filter_tests/test_truncatewords.py", "language": "python", "file_size": 1852, "cut_index": 537, "middle_length": 229 }
ultfilters import truncatewords_html from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_truncate_zero(self): self.assertEqual( truncatewords_html( '<p>one <a href="#">two - three <br>four</a> five</p>', 0 ), "", ...
'<p>one <a href="#">two - three <br> …</a></p>', ) def test_truncate3(self): self.assertEqual( truncatewords_html( '<p>one <a href="#">two - three <br>four</a> five</p>', 5 ), '
<p>one <a href="#">two …</a></p>', ) def test_truncate2(self): self.assertEqual( truncatewords_html( '<p>one <a href="#">two - three <br>four</a> five</p>', 4 ),
{ "filepath": "tests/template_tests/filter_tests/test_truncatewords_html.py", "language": "python", "file_size": 1872, "cut_index": 537, "middle_length": 229 }
ls import setup class UnorderedListTests(SimpleTestCase): @setup({"unordered_list01": "{{ a|unordered_list }}"}) def test_unordered_list01(self): output = self.engine.render_to_string("unordered_list01", {"a": ["x>", ["<y"]]}) self.assertEqual( output, "\t<li>x&gt;\n\t<ul>\n\t\t<li...
@setup({"unordered_list03": "{{ a|unordered_list }}"}) def test_unordered_list03(self): output = self.engine.render_to_string( "unordered_list03", {"a": ["x>", [mark_safe("<y")]]} ) self.assertEqual(
} ) def test_unordered_list02(self): output = self.engine.render_to_string("unordered_list02", {"a": ["x>", ["<y"]]}) self.assertEqual(output, "\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>")
{ "filepath": "tests/template_tests/filter_tests/test_unordered_list.py", "language": "python", "file_size": 6577, "cut_index": 716, "middle_length": 229 }
template.defaultfilters import upper from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class UpperTests(SimpleTestCase): """ The "upper" filter messes up entities (which are case-sensitive), so it's not safe for non-escaping purposes. """ ...
def test_upper02(self): output = self.engine.render_to_string( "upper02", {"a": "a & b", "b": mark_safe("a &amp; b")} ) self.assertEqual(output, "A &amp; B A &amp;AMP; B") class FunctionTests(SimpleTestCase):
output = self.engine.render_to_string( "upper01", {"a": "a & b", "b": mark_safe("a &amp; b")} ) self.assertEqual(output, "A & B A &AMP; B") @setup({"upper02": "{{ a|upper }} {{ b|upper }}"})
{ "filepath": "tests/template_tests/filter_tests/test_upper.py", "language": "python", "file_size": 1291, "cut_index": 524, "middle_length": 229 }
ate.defaultfilters import urlencode from django.test import SimpleTestCase from ..utils import setup class UrlencodeTests(SimpleTestCase): @setup({"urlencode01": "{{ url|urlencode }}"}) def test_urlencode01(self): output = self.engine.render_to_string("urlencode01", {"url": '/test&"/me?/'}) s...
.assertEqual(output, "/test/escape%2Fslash/") class FunctionTests(SimpleTestCase): def test_urlencode(self): self.assertEqual(urlencode("fran\xe7ois & jill"), "fran%C3%A7ois%20%26%20jill") def test_non_string_input(self): self.as
lencode02", {"urlbit": "escape/slash"}) self
{ "filepath": "tests/template_tests/filter_tests/test_urlencode.py", "language": "python", "file_size": 866, "cut_index": 529, "middle_length": 52 }
utput, '<a href="http://example.com/?x=&amp;y=" rel="nofollow">' "http://example.com/?x=&y=</a> " '<a href="http://example.com?x=&amp;y=%3C2%3E" rel="nofollow">' "http://example.com?x=&amp;y=&lt;2&gt;</a>", ) @setup({"urlize02": "{{ a|urlize }} {{ b|urlize }}...
'<a href="http://example.com?x=&amp;y=" rel="nofollow">' "http://example.com?x=&amp;y=</a>", ) @setup({"urlize03": "{% autoescape off %}{{ a|urlize }}{% endautoescape %}"}) def test_urlize03(self): output =
k_safe("http://example.com?x=&amp;y="), }, ) self.assertEqual( output, '<a href="http://example.com/?x=&amp;y=" rel="nofollow">' "http://example.com/?x=&amp;y=</a> "
{ "filepath": "tests/template_tests/filter_tests/test_urlize.py", "language": "python", "file_size": 19922, "cut_index": 1331, "middle_length": 229 }
ngo.test.utils import override_settings from django.utils.safestring import mark_safe from ..utils import setup class UrlizetruncTests(SimpleTestCase): @setup( { "urlizetrunc01": ( '{% autoescape off %}{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}' "{% endaut...
"http://example.com/x=&amp;y=" rel="nofollow">http://…</a> ' "&quot;Safe&quot; " '<a href="http://example.com?x=&amp;y=" rel="nofollow">http://…</a>', ) @setup({"urlizetrunc02": '{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc
afe" http://example.com/x=&y=', "b": mark_safe("&quot;Safe&quot; http://example.com?x=&amp;y="), }, ) self.assertEqual( output, '"Unsafe" ' '<a href=
{ "filepath": "tests/template_tests/filter_tests/test_urlizetrunc.py", "language": "python", "file_size": 3674, "cut_index": 614, "middle_length": 229 }
jango.template.defaultfilters import wordcount from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class WordcountTests(SimpleTestCase): @setup( { "wordcount01": ( "{% autoescape off %}{{ a|wordcount }} {{ b|wordcount ...
"wordcount02", {"a": "a & b", "b": mark_safe("a &amp; b")} ) self.assertEqual(output, "3 3") class FunctionTests(SimpleTestCase): def test_empty_string(self): self.assertEqual(wordcount(""), 0) def test_count_on
"b": mark_safe("a &amp; b")} ) self.assertEqual(output, "3 3") @setup({"wordcount02": "{{ a|wordcount }} {{ b|wordcount }}"}) def test_wordcount02(self): output = self.engine.render_to_string(
{ "filepath": "tests/template_tests/filter_tests/test_wordcount.py", "language": "python", "file_size": 1236, "cut_index": 518, "middle_length": 229 }
.utils.functional import lazystr from django.utils.safestring import mark_safe from ..utils import setup class WordwrapTests(SimpleTestCase): @setup( { "wordwrap01": ( '{% autoescape off %}{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}' "{% endautoescape %}" ...
": mark_safe("a & b")} ) self.assertEqual(output, "a &amp;\nb a &\nb") class FunctionTests(SimpleTestCase): def test_wrap(self): self.assertEqual( wordwrap( "this is a long paragraph of text that re
sertEqual(output, "a &\nb a &\nb") @setup({"wordwrap02": '{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}'}) def test_wordwrap02(self): output = self.engine.render_to_string( "wordwrap02", {"a": "a & b", "b
{ "filepath": "tests/template_tests/filter_tests/test_wordwrap.py", "language": "python", "file_size": 4481, "cut_index": 614, "middle_length": 229 }
template.defaultfilters import yesno from django.test import SimpleTestCase from ..utils import setup class YesNoTests(SimpleTestCase): @setup({"t": '{{ var|yesno:"yup,nup,mup" }} {{ var|yesno }}'}) def test_true(self): output = self.engine.render_to_string("t", {"var": True}) self.assertEqua...
guments(self): self.assertEqual( yesno(False, "certainly,get out of town,perhaps"), "get out of town" ) def test_none_two_arguments(self): self.assertEqual(yesno(None, "certainly,get out of town"), "get out of town"
e), "no") def test_none(self): self.assertEqual(yesno(None), "maybe") def test_true_arguments(self): self.assertEqual(yesno(True, "certainly,get out of town,perhaps"), "certainly") def test_false_ar
{ "filepath": "tests/template_tests/filter_tests/test_yesno.py", "language": "python", "file_size": 1318, "cut_index": 524, "middle_length": 229 }
gTests(SimpleTestCase): @setup({"autoescape-tag01": "{% autoescape off %}hello{% endautoescape %}"}) def test_autoescape_tag01(self): output = self.engine.render_to_string("autoescape-tag01") self.assertEqual(output, "hello") @setup({"autoescape-tag02": "{% autoescape off %}{{ first }}{% en...
{"first": "<b>hello</b>"} ) self.assertEqual(output, "&lt;b&gt;hello&lt;/b&gt;") # Autoescape disabling and enabling nest in a predictable way. @setup( { "autoescape-tag04": ( "{% autoescape off
al(output, "<b>hello</b>") @setup({"autoescape-tag03": "{% autoescape on %}{{ first }}{% endautoescape %}"}) def test_autoescape_tag03(self): output = self.engine.render_to_string( "autoescape-tag03",
{ "filepath": "tests/template_tests/syntax_tests/test_autoescape.py", "language": "python", "file_size": 6535, "cut_index": 716, "middle_length": 229 }
ort os from unittest import TestCase from django.template import Engine from .utils import TEMPLATE_DIR class OriginTestCase(TestCase): def setUp(self): self.engine = Engine(dirs=[TEMPLATE_DIR]) def test_origin_compares_equal(self): a = self.engine.get_template("index.html") b = sel...
rigin, b.origin) # Use assertIs() to test __eq__/__ne__. self.assertIs(a.origin == b.origin, False) self.assertIs(a.origin != b.origin, True) def test_repr(self): a = self.engine.get_template("index.html") name
assertIs(a.origin != b.origin, False) def test_origin_compares_not_equal(self): a = self.engine.get_template("first/test.html") b = self.engine.get_template("second/test.html") self.assertNotEqual(a.o
{ "filepath": "tests/template_tests/test_origin.py", "language": "python", "file_size": 1111, "cut_index": 515, "middle_length": 229 }
test_processor(request): return {"processors": "yes"} test_processor_name = "template_tests.test_response.test_processor" # A test middleware that installs a temporary URLConf def custom_urlconf_middleware(get_response): def middleware(request): request.urlconf = "template_tests.alternate_urls" ...
self.assertEqual(response.content, b"First template\n") templates = ["foo.html", "second/test.html", "first/test.html"] response = SimpleTemplateResponse(templates) response.render() self.assertEqual(response.content, b
["django"].from_string(template) return SimpleTemplateResponse(template, *args, **kwargs) def test_template_resolving(self): response = SimpleTemplateResponse("first/test.html") response.render()
{ "filepath": "tests/template_tests/test_response.py", "language": "python", "file_size": 14427, "cut_index": 921, "middle_length": 229 }
rg = str class TemplateTestMixin: def _engine(self, **kwargs): return Engine(debug=self.debug_engine, **kwargs) def test_string_origin(self): template = self._engine().from_string("string template") self.assertEqual(template.origin.name, UNKNOWN_SOURCE) self.assertIsNone(templ...
eMatch): t.render(c) def test_url_reverse_view_name(self): """ #19827 -- url tag should keep original stack trace when reraising exception. """ t = self._engine().from_string("{% url will_not_match %
" #9005 -- url tag shouldn't require settings.SETTINGS_MODULE to be set. """ t = self._engine().from_string("{% url will_not_match %}") c = Context() with self.assertRaises(NoRevers
{ "filepath": "tests/template_tests/tests.py", "language": "python", "file_size": 9441, "cut_index": 921, "middle_length": 229 }
s import override_settings from django.utils.safestring import mark_safe ROOT = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_DIR = os.path.join(ROOT, "templates") def setup(templates, *args, test_once=False, debug_only=False): """ Runs test method multiple times in the following order: debug ...
tests make use of an inclusion tag # add this in here for simplicity templates["inclusion.html"] = "{{ result }}" loaders = [ ( "django.template.loaders.cached.Loader", [ ("django.template.loade
True False True True Use test_once=True to test deprecation warnings since the message won't be displayed multiple times. """ for arg in args: templates.update(arg) # numerous
{ "filepath": "tests/template_tests/utils.py", "language": "python", "file_size": 4109, "cut_index": 614, "middle_length": 229 }
template.defaultfilters import addslashes from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class AddslashesTests(SimpleTestCase): @setup( { "addslashes01": ( "{% autoescape off %}{{ a|addslashes }} {{ b|addslashes }...
ring( "addslashes02", {"a": "<a>'", "b": mark_safe("<a>'")} ) self.assertEqual(output, r"&lt;a&gt;\&#x27; <a>\'") class FunctionTests(SimpleTestCase): def test_quotes(self): self.assertEqual( addslashes
"b": mark_safe("<a>'")} ) self.assertEqual(output, r"<a>\' <a>\'") @setup({"addslashes02": "{{ a|addslashes }} {{ b|addslashes }}"}) def test_addslashes02(self): output = self.engine.render_to_st
{ "filepath": "tests/template_tests/filter_tests/test_addslashes.py", "language": "python", "file_size": 1332, "cut_index": 524, "middle_length": 229 }
impleTestCase from ..utils import SafeClass, UnsafeClass, setup class AutoescapeStringfilterTests(SimpleTestCase): """ Filters decorated with stringfilter still respect is_safe. """ @setup({"autoescape-stringfilter01": "{{ unsafe|capfirst }}"}) def test_autoescape_stringfilter01(self): o...
to_string( "autoescape-stringfilter02", {"unsafe": UnsafeClass()} ) self.assertEqual(output, "You & me") @setup({"autoescape-stringfilter03": "{{ safe|capfirst }}"}) def test_autoescape_stringfilter03(self): out
"autoescape-stringfilter02": ( "{% autoescape off %}{{ unsafe|capfirst }}{% endautoescape %}" ) } ) def test_autoescape_stringfilter02(self): output = self.engine.render_
{ "filepath": "tests/template_tests/filter_tests/test_autoescape.py", "language": "python", "file_size": 1566, "cut_index": 537, "middle_length": 229 }
template.defaultfilters import center from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class CenterTests(SimpleTestCase): @setup( { "center01": ( '{% autoescape off %}.{{ a|center:"5" }}. .{{ b|center:"5" }}.' ...
center02", {"a": "a&b", "b": mark_safe("a&b")} ) self.assertEqual(output, ". a&amp;b . . a&b .") class FunctionTests(SimpleTestCase): def test_center(self): self.assertEqual(center("test", 6), " test ") def test_non_strin
a&b")} ) self.assertEqual(output, ". a&b . . a&b .") @setup({"center02": '.{{ a|center:"5" }}. .{{ b|center:"5" }}.'}) def test_center02(self): output = self.engine.render_to_string( "
{ "filepath": "tests/template_tests/filter_tests/test_center.py", "language": "python", "file_size": 1439, "cut_index": 524, "middle_length": 229 }
import SimpleTestCase from django.utils import timezone, translation from ..utils import setup from .timezone_utils import TimezoneTestCase class DateTests(TimezoneTestCase): @setup({"date01": '{{ d|date:"m" }}'}) def test_date01(self): output = self.engine.render_to_string("date01", {"d": datetime(2...
ion.override("fr"): output = self.engine.render_to_string( "date02_l10n", {"d": datetime(2008, 1, 1)} ) self.assertEqual(output, "1 janvier 2008") @setup({"date03": '{{ d|date:"m" }}'}) def test_date
08, 1, 1)}) self.assertEqual(output, "Jan. 1, 2008") @setup({"date02_l10n": "{{ d|date }}"}) def test_date02_l10n(self): """Without arg, the active language's DATE_FORMAT is used.""" with translat
{ "filepath": "tests/template_tests/filter_tests/test_date.py", "language": "python", "file_size": 3252, "cut_index": 614, "middle_length": 229 }
TestCase class User: password = "abc" _private = "private" @property def test_property(self): return "cde" def test_method(self): """This is just a test method.""" class FunctionTests(SimpleTestCase): def test_property_resolver(self): user = User() dict_dat...
uld not get called. ("a.b2.test_method", dict_data, user.test_method), ("a.b3.0", dict_data, "result2"), (0, list_data, "a"), ] for arg, data, expected_value in tests: with self.subTest(arg=ar
list_data = ["a", "b", "c"] tests = [ ("a.b1.c", dict_data, "result1"), ("a.b2.password", dict_data, "abc"), ("a.b2.test_property", dict_data, "cde"), # The method sho
{ "filepath": "tests/template_tests/filter_tests/test_dictsort.py", "language": "python", "file_size": 4167, "cut_index": 614, "middle_length": 229 }
reversed from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_sort(self): sorted_dicts = dictsortreversed( [ {"age": 23, "name": "Barbara-Ann"}, {"age": 63, "name": "Ra Ra Rasputin"}, {"name": "Jonny B Goode", "age...
("c", "string"), ("b", "foo")] expected = [("c", "string"), ("b", "foo"), ("a", "42")] self.assertEqual(dictsortreversed(data, 0), expected) def test_sort_list_of_tuple_like_dicts(self): data = [ {"0": "a", "1": "4
"Ra Ra Rasputin")], [("age", 23), ("name", "Barbara-Ann")], [("age", 18), ("name", "Jonny B Goode")], ], ) def test_sort_list_of_tuples(self): data = [("a", "42"),
{ "filepath": "tests/template_tests/filter_tests/test_dictsortreversed.py", "language": "python", "file_size": 2125, "cut_index": 563, "middle_length": 229 }
_filter from django.test import SimpleTestCase from django.utils.functional import lazy from ..utils import setup class EscapejsTests(SimpleTestCase): @setup({"escapejs01": "{{ a|escapejs }}"}) def test_escapejs01(self): output = self.engine.render_to_string( "escapejs01", {"a": "testing\...
"escapejs02", {"a": "testing\r\njavascript 'string\" <b>escaping</b>"} ) self.assertEqual( output, "testing\\u000D\\u000Ajavascript " "\\u0027string\\u0022 \\u003Cb\\u003E" "escaping\\u003C/
3E" "escaping\\u003C/b\\u003E", ) @setup({"escapejs02": "{% autoescape off %}{{ a|escapejs }}{% endautoescape %}"}) def test_escapejs02(self): output = self.engine.render_to_string(
{ "filepath": "tests/template_tests/filter_tests/test_escapejs.py", "language": "python", "file_size": 2460, "cut_index": 563, "middle_length": 229 }
m django.template.defaultfilters import first from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class FirstTests(SimpleTestCase): @setup({"first01": "{{ a|first }} {{ b|first }}"}) def test_first01(self): output = self.engine.render_to_stri...
[mark_safe("a&b"), "x"]} ) self.assertEqual(output, "a&b a&b") class FunctionTests(SimpleTestCase): def test_list(self): self.assertEqual(first([0, 1, 2]), 0) def test_empty_string(self): self.assertEqual(first(""
"{% autoescape off %}{{ a|first }} {{ b|first }}{% endautoescape %}" ) } ) def test_first02(self): output = self.engine.render_to_string( "first02", {"a": ["a&b", "x"], "b":
{ "filepath": "tests/template_tests/filter_tests/test_first.py", "language": "python", "file_size": 1080, "cut_index": 515, "middle_length": 229 }
mport mark_safe from django.utils.version import PYPY from ..utils import setup class FloatformatTests(SimpleTestCase): @setup( { "floatformat01": ( "{% autoescape off %}{{ a|floatformat }} {{ b|floatformat }}" "{% endautoescape %}" ) } ...
2")} ) self.assertEqual(output, "1.4 1.4") class FunctionTests(SimpleTestCase): def test_inputs(self): self.assertEqual(floatformat(7.7), "7.7") self.assertEqual(floatformat(7.0), "7") self.assertEqual(floatfor
"1.4 1.4") @setup({"floatformat02": "{{ a|floatformat }} {{ b|floatformat }}"}) def test_floatformat02(self): output = self.engine.render_to_string( "floatformat02", {"a": "1.42", "b": mark_safe("1.4
{ "filepath": "tests/template_tests/filter_tests/test_floatformat.py", "language": "python", "file_size": 8700, "cut_index": 716, "middle_length": 229 }
ls.safestring import mark_safe from ..utils import setup class JoinTests(SimpleTestCase): @setup({"join01": '{{ a|join:", " }}'}) def test_join01(self): output = self.engine.render_to_string("join01", {"a": ["alpha", "beta & me"]}) self.assertEqual(output, "alpha, beta &amp; me") @setup(...
tEqual(output, "alpha &amp; beta &amp; me") @setup({"join04": '{% autoescape off %}{{ a|join:" &amp; " }}{% endautoescape %}'}) def test_join04(self): output = self.engine.render_to_string("join04", {"a": ["alpha", "beta & me"]}) s
self.assertEqual(output, "alpha, beta & me") @setup({"join03": '{{ a|join:" &amp; " }}'}) def test_join03(self): output = self.engine.render_to_string("join03", {"a": ["alpha", "beta & me"]}) self.asser
{ "filepath": "tests/template_tests/filter_tests/test_join.py", "language": "python", "file_size": 3626, "cut_index": 614, "middle_length": 229 }
.test import SimpleTestCase from ..utils import setup class JsonScriptTests(SimpleTestCase): @setup({"json-tag01": '{{ value|json_script:"test_id" }}'}) def test_basic(self): output = self.engine.render_to_string( "json-tag01", {"value": {"a": "testing\r\njson 'string\" <b>escaping</b>"}}...
pt>", ) @setup({"json-tag02": "{{ value|json_script }}"}) def test_without_id(self): output = self.engine.render_to_string("json-tag02", {"value": {}}) self.assertEqual(output, '<script type="application/json">{}</script>')
u003Eescaping\\u003C/b\\u003E"}' "</scri
{ "filepath": "tests/template_tests/filter_tests/test_json_script.py", "language": "python", "file_size": 832, "cut_index": 523, "middle_length": 52 }
om django.test import SimpleTestCase class NodelistTest(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine() super().setUpClass() def test_for(self): template = self.engine.from_string("{% for i in 1 %}{{ a }}{% endfor %}") vars = template.nodelist.get_...
t.get_nodes_by_type(VariableNode) self.assertEqual(len(vars), 1) class TextNodeTest(SimpleTestCase): def test_textnode_repr(self): engine = Engine() for temptext, reprtext in [ ("Hello, world!", "<TextNode: 'Hello,
delist.get_nodes_by_type(VariableNode) self.assertEqual(len(vars), 1) def test_ifchanged(self): template = self.engine.from_string("{% ifchanged x %}{{ a }}{% endifchanged %}") vars = template.nodelis
{ "filepath": "tests/template_tests/test_nodelist.py", "language": "python", "file_size": 3103, "cut_index": 614, "middle_length": 229 }
te.base import ( FilterExpression, Lexer, Parser, Token, TokenType, Variable, VariableDoesNotExist, ) from django.template.defaultfilters import register as filter_library from django.test import SimpleTestCase from django.utils.version import PY314 class ParserTests(SimpleTestCase): d...
= Token(TokenType.BLOCK, "some text") self.assertEqual(repr(token), '<Block token: "some text...">') parser = Parser([token], builtins=[filter_library]) self.assertEqual( repr(parser), '<Parser tokens=[<Block
lue|yesno:_("yes,no")' ) split = token.split_contents() self.assertEqual( split, ["sometag", '_("Page not found")', 'value|yesno:_("yes,no")'] ) def test_repr(self): token
{ "filepath": "tests/template_tests/test_parser.py", "language": "python", "file_size": 9081, "cut_index": 716, "middle_length": 229 }
s_patterns = [ # Test urls for testing reverse lookups path("", views.index, name="index"), re_path(r"^client/([0-9,]+)/$", views.client, name="client"), re_path( r"^client/(?P<id>[0-9]+)/(?P<action>[^/]+)/$", views.client_action, name="client_action", ), re_path( ...
de strings are permitted everywhere. re_path(r"^Юникод/(\w+)/$", views.client2, name="метка_оператора"), re_path(r"^Юникод/(?P<tag>\S+)/$", views.client2, name="метка_оператора_2"), # Test urls for namespaces and current_app path("ns1/", in
ent"), ] urlpatterns = ns_patterns + [ # Unico
{ "filepath": "tests/template_tests/urls.py", "language": "python", "file_size": 1018, "cut_index": 582, "middle_length": 52 }
emplate.defaultfilters import add from django.test import SimpleTestCase from django.utils.translation import gettext_lazy from ..utils import setup class AddTests(SimpleTestCase): """ Tests for #11687 and #16676 """ @setup({"add01": '{{ i|add:"5" }}'}) def test_add01(self): output = sel...
.assertEqual(output, "") @setup({"add04": '{{ i|add:"16" }}'}) def test_add04(self): output = self.engine.render_to_string("add04", {"i": "not_an_int"}) self.assertEqual(output, "not_an_int16") @setup({"add05": "{{ l1|add:l2 }
nder_to_string("add02", {"i": 2000}) self.assertEqual(output, "") @setup({"add03": "{{ i|add:16 }}"}) def test_add03(self): output = self.engine.render_to_string("add03", {"i": "not_an_int"}) self
{ "filepath": "tests/template_tests/filter_tests/test_add.py", "language": "python", "file_size": 2305, "cut_index": 563, "middle_length": 229 }
django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class CutTests(SimpleTestCase): @setup( { "cut01": ( '{% autoescape off %}{{ a|cut:"x" }} {{ b|cut:"x" }}{% endautoescape %}' ) } ) def test_c...
mp;y") @setup( { "cut03": ( '{% autoescape off %}{{ a|cut:"&" }} {{ b|cut:"&" }}{% endautoescape %}' ) } ) def test_cut03(self): output = self.engine.render_to_string(
t02": '{{ a|cut:"x" }} {{ b|cut:"x" }}'}) def test_cut02(self): output = self.engine.render_to_string( "cut02", {"a": "x&y", "b": mark_safe("x&amp;y")} ) self.assertEqual(output, "&amp;y &a
{ "filepath": "tests/template_tests/filter_tests/test_cut.py", "language": "python", "file_size": 2625, "cut_index": 563, "middle_length": 229 }
impleTestCase from django.utils.safestring import mark_safe from ..utils import setup class EscapeseqTests(SimpleTestCase): """ The "escapeseq" filter works the same whether autoescape is on or off, and has no effect on strings already marked as safe. """ @setup( { "escapeseq...
eq_autoescape_off": ( '{% autoescape off %}{{ a|escapeseq|join:", " }}' " -- " '{{ b|escapeseq|join:", "}}{% endautoescape %}' ) } ) def test_autoescape_off(self): output =
"escapeseq_basic", {"a": ["x&y", "<p>"], "b": [mark_safe("x&y"), mark_safe("<p>")]}, ) self.assertEqual(output, "x&amp;y, &lt;p&gt; -- x&y, <p>") @setup( { "escapes
{ "filepath": "tests/template_tests/filter_tests/test_escapeseq.py", "language": "python", "file_size": 1907, "cut_index": 537, "middle_length": 229 }
format from django.test import SimpleTestCase from django.utils import translation class FunctionTests(SimpleTestCase): def test_formats(self): tests = [ (0, "0\xa0bytes"), (1, "1\xa0byte"), (1023, "1023\xa0bytes"), (1024, "1.0\xa0KB"), (10 * 102...
"2000.0\xa0PB"), (complex(1, -1), "0\xa0bytes"), ("", "0\xa0bytes"), ("\N{GREEK SMALL LETTER ALPHA}", "0\xa0bytes"), ] for value, expected in tests: with self.subTest(value=value):
4.0\xa0MB"), (1024 * 1024 * 1024, "1.0\xa0GB"), (1024 * 1024 * 1024 * 1024, "1.0\xa0TB"), (1024 * 1024 * 1024 * 1024 * 1024, "1.0\xa0PB"), (1024 * 1024 * 1024 * 1024 * 1024 * 2000,
{ "filepath": "tests/template_tests/filter_tests/test_filesizeformat.py", "language": "python", "file_size": 2428, "cut_index": 563, "middle_length": 229 }
tils import setup class LastTests(SimpleTestCase): @setup({"last01": "{{ a|last }} {{ b|last }}"}) def test_last01(self): output = self.engine.render_to_string( "last01", {"a": ["x", "a&b"], "b": ["x", mark_safe("a&b")]} ) self.assertEqual(output, "a&amp;b a&b") @setup...
) self.assertEqual(output, "a&b a&b") @setup({"empty_list": "{% autoescape off %}{{ a|last }}{% endautoescape %}"}) def test_empty_list(self): output = self.engine.render_to_string("empty_list", {"a": []}) self.assertE
"a": ["x", "a&b"], "b": ["x", mark_safe("a&b")]}
{ "filepath": "tests/template_tests/filter_tests/test_last.py", "language": "python", "file_size": 931, "cut_index": 606, "middle_length": 52 }
late_name)), ): engine.get_template(template_name) def test_full_template_from_loader(self): template = engine.get_template("partial_examples.html") rendered = template.render({}) # Check the partial was rendered twice self.assertEqual(2, rendered.count(...
mplate_name, "not_there.html") def test_partials_use_cached_loader_when_configured(self): template_dir = os.path.join(os.path.dirname(__file__), "templates") backend = DjangoTemplates( { "NAME": "django",
ctx: engine.get_template("not_there.html#not-a-partial") exception = ctx.exception self.assertGreater(len(exception.tried), 0) origin, _ = exception.tried[0] self.assertEqual(origin.te
{ "filepath": "tests/template_tests/test_partials.py", "language": "python", "file_size": 21595, "cut_index": 1331, "middle_length": 229 }
from django.template.defaultfilters import capfirst from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class CapfirstTests(SimpleTestCase): @setup( { "capfirst01": ( "{% autoescape off %}{{ a|capfirst }} {{ b|capfirst...
g( "capfirst02", {"a": "fred>", "b": mark_safe("fred&gt;")} ) self.assertEqual(output, "Fred&gt; Fred&gt;") class FunctionTests(SimpleTestCase): def test_capfirst(self): self.assertEqual(capfirst("hello world"), "H
"b": mark_safe("fred&gt;")} ) self.assertEqual(output, "Fred> Fred&gt;") @setup({"capfirst02": "{{ a|capfirst }} {{ b|capfirst }}"}) def test_capfirst02(self): output = self.engine.render_to_strin
{ "filepath": "tests/template_tests/filter_tests/test_capfirst.py", "language": "python", "file_size": 1010, "cut_index": 512, "middle_length": 229 }
from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class DefaultTests(SimpleTestCase): """ Literal string arguments to the default filter are always treated as safe strings, regardless of the auto-escaping state. Note: we have to use {"a": ...
utput = self.engine.render_to_string("default02", {"a": ""}) self.assertEqual(output, "x<") @setup({"default03": '{{ a|default:"x<" }}'}) def test_default03(self): output = self.engine.render_to_string("default03", {"a": mark_safe(
utput = self.engine.render_to_string("default01", {"a": ""}) self.assertEqual(output, "x<") @setup({"default02": '{% autoescape off %}{{ a|default:"x<" }}{% endautoescape %}'}) def test_default02(self): o
{ "filepath": "tests/template_tests/filter_tests/test_default.py", "language": "python", "file_size": 2225, "cut_index": 563, "middle_length": 229 }
ultfilters import iriencode, urlencode from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class IriencodeTests(SimpleTestCase): """ Ensure iriencode keeps safe strings. """ @setup({"iriencode01": "{{ url|iriencode }}"}) def test_irienco...
) @setup({"iriencode03": "{{ url|iriencode }}"}) def test_iriencode03(self): output = self.engine.render_to_string( "iriencode03", {"url": mark_safe("?test=1&me=2")} ) self.assertEqual(output, "?test=1&me=2")
autoescape off %}{{ url|iriencode }}{% endautoescape %}"} ) def test_iriencode02(self): output = self.engine.render_to_string("iriencode02", {"url": "?test=1&me=2"}) self.assertEqual(output, "?test=1&me=2"
{ "filepath": "tests/template_tests/filter_tests/test_iriencode.py", "language": "python", "file_size": 1631, "cut_index": 537, "middle_length": 229 }
t IfParser class SmartIfTests(unittest.TestCase): def assertCalcEqual(self, expected, tokens): self.assertEqual(expected, IfParser(tokens).parse().eval({})) # We only test things here that are difficult to test elsewhere # Many other tests are found in the main tests for builtin template tags ...
repr(var)) self.assertTrue(var.eval({})) def test_in(self): list_ = [1, 2, 3] self.assertCalcEqual(True, [1, "in", list_]) self.assertCalcEqual(False, [1, "in", None]) self.assertCalcEqual(False, [None, "in", li
rtTrue(var.eval({})) self.assertFalse(IfParser(["not", True]).parse().eval({})) def test_or(self): var = IfParser([True, "or", False]).parse() self.assertEqual("(or (literal True) (literal False))",
{ "filepath": "tests/template_tests/test_smartif.py", "language": "python", "file_size": 2187, "cut_index": 563, "middle_length": 229 }
ort setup class ChainingTests(SimpleTestCase): """ Chaining safeness-preserving filters should not alter the safe status. """ @setup({"chaining01": '{{ a|capfirst|center:"7" }}.{{ b|capfirst|center:"7" }}'}) def test_chaining01(self): output = self.engine.render_to_string( "ch...
haining02", {"a": "a < b", "b": mark_safe("a < b")} ) self.assertEqual(output, " A < b . A < b ") # Using a filter that forces a string back to unsafe: @setup({"chaining03": '{{ a|cut:"b"|capfirst }}.{{ b|cut:"b"|capfirst }}'})
scape off %}{{ a|capfirst|center:"7" }}.' '{{ b|capfirst|center:"7" }}{% endautoescape %}' ) } ) def test_chaining02(self): output = self.engine.render_to_string( "c
{ "filepath": "tests/template_tests/filter_tests/test_chaining.py", "language": "python", "file_size": 4418, "cut_index": 614, "middle_length": 229 }
ango.utils.safestring import SafeData from ..utils import setup class ForceEscapeTests(SimpleTestCase): """ Force_escape is applied immediately. It can be used to provide double-escaping, for example. """ @setup( { "force-escape01": ( "{% autoescape off %}{{ a...
put, "x&amp;y") @setup( { "force-escape03": ( "{% autoescape off %}{{ a|force_escape|force_escape }}" "{% endautoescape %}" ) } ) def test_force_escape03(self): ou
.assertEqual(output, "x&amp;y") @setup({"force-escape02": "{{ a|force_escape }}"}) def test_force_escape02(self): output = self.engine.render_to_string("force-escape02", {"a": "x&y"}) self.assertEqual(out
{ "filepath": "tests/template_tests/filter_tests/test_force_escape.py", "language": "python", "file_size": 3150, "cut_index": 614, "middle_length": 229 }
block first %}2{% endblock %}{% block second %}4{% endblock %}", "inheritance03": "{% extends 'inheritance02' %}", "inheritance04": "{% extends 'inheritance01' %}", "inheritance05": "{% extends 'inheritance02' %}", "inheritance06": "{% extends foo %}", "inheritance07": "{% extends 'inheritance01' %...
ck first %}2{% endblock %}", "inheritance13": "{% extends 'inheritance02' %}" "{% block first %}a{% endblock %}{% block second %}b{% endblock %}", "inheritance14": ( "{% extends 'inheritance01' %}{% block newblock %}NO DISPLAY{% endbloc
ce10": "{% extends 'inheritance04' %} ", "inheritance11": "{% extends 'inheritance04' %}" "{% block first %}2{% endblock %}{% block second %}4{% endblock %}", "inheritance12": "{% extends 'inheritance07' %}{% blo
{ "filepath": "tests/template_tests/syntax_tests/test_extends.py", "language": "python", "file_size": 17141, "cut_index": 921, "middle_length": 229 }
rt TemplateSyntaxError from django.test import SimpleTestCase from ..utils import setup class FilterTagTests(SimpleTestCase): @setup({"filter01": "{% filter upper %}{% endfilter %}"}) def test_filter01(self): output = self.engine.render_to_string("filter01") self.assertEqual(output, "") ...
": "{% filter cut:remove %}djangospam{% endfilter %}"}) def test_filter04(self): output = self.engine.render_to_string("filter04", {"remove": "spam"}) self.assertEqual(output, "django") @setup({"filter05": "{% filter safe %}fail{%
) @setup({"filter03": "{% filter upper|lower %}django{% endfilter %}"}) def test_filter03(self): output = self.engine.render_to_string("filter03") self.assertEqual(output, "django") @setup({"filter04
{ "filepath": "tests/template_tests/syntax_tests/test_filter_tag.py", "language": "python", "file_size": 1794, "cut_index": 537, "middle_length": 229 }
rt TemplateSyntaxError from django.test import SimpleTestCase from ..utils import setup class VerbatimTagTests(SimpleTestCase): @setup({"verbatim-tag01": "{% verbatim %}{{bare }}{% endverbatim %}"}) def test_verbatim_tag01(self): output = self.engine.render_to_string("verbatim-tag01") self....
elf.engine.render_to_string("verbatim-tag03") self.assertEqual(output, "It's the {% verbatim %} tag") @setup( { "verbatim-tag04": ( "{% verbatim %}{% verbatim %}{% endverbatim %}{% endverbatim %}"
g("verbatim-tag02") self.assertEqual(output, "{% endif %}") @setup( {"verbatim-tag03": "{% verbatim %}It's the {% verbatim %} tag{% endverbatim %}"} ) def test_verbatim_tag03(self): output = s
{ "filepath": "tests/template_tests/syntax_tests/test_verbatim.py", "language": "python", "file_size": 1821, "cut_index": 537, "middle_length": 229 }
platetags.custom"} @setup({"widthratio01": "{% widthratio a b 0 %}"}) def test_widthratio01(self): output = self.engine.render_to_string("widthratio01", {"a": 50, "b": 100}) self.assertEqual(output, "0") @setup({"widthratio02": "{% widthratio a b 100 %}"}) def test_widthratio02(self): ...
output = self.engine.render_to_string("widthratio04", {"a": 50, "b": 100}) self.assertEqual(output, "50") @setup({"widthratio05": "{% widthratio a b 100 %}"}) def test_widthratio05(self): output = self.engine.render_to_strin
thratio03(self): output = self.engine.render_to_string("widthratio03", {"a": 0, "b": 100}) self.assertEqual(output, "0") @setup({"widthratio04": "{% widthratio a b 100 %}"}) def test_widthratio04(self):
{ "filepath": "tests/template_tests/syntax_tests/test_width_ratio.py", "language": "python", "file_size": 6571, "cut_index": 716, "middle_length": 229 }
m django.template.defaulttags import WithNode from django.test import SimpleTestCase from ..utils import setup class WithTagTests(SimpleTestCase): at_least_with_one_msg = "'with' expected at least one variable assignment" @setup({"with01": "{% with key=dict.key %}{{ key }}{% endwith %}"}) def test_with0...
{% with key=dict.key %}" "{{ key }}-{{ dict.key }}-{{ key }}" "{% endwith %}{{ key }}" } ) def test_with02(self): output = self.engine.render_to_string("with02", {"dict": {"key": 50}}) if self.engine.
{% endwith %}"}) def test_legacywith01(self): output = self.engine.render_to_string("legacywith01", {"dict": {"key": 50}}) self.assertEqual(output, "50") @setup( { "with02": "{{ key }}
{ "filepath": "tests/template_tests/syntax_tests/test_with.py", "language": "python", "file_size": 2641, "cut_index": 563, "middle_length": 229 }
"{% endblocktranslate %}", "{% endblocktrans %}" ) for name, template in templates.items() } ) tags = { "blocktrans": blocktrans_setup, "blocktranslate": blocktranslate_setup, } def decorator(func): @wraps(func) def inner(sel...
"django.templatetags.i18n"} @setup( { "i18n03": ( "{% load i18n %}{% blocktranslate %}{{ anton }}{% endblocktranslate %}" ) } ) def test_i18n03(self): """simple translation of a v
p_func(partial(func, tag_name=tag_name))(self) else: setup_func(func)(self) return inner return decorator class I18nBlockTransTagTests(SimpleTestCase): libraries = {"i18n":
{ "filepath": "tests/template_tests/syntax_tests/i18n/test_blocktranslate.py", "language": "python", "file_size": 31959, "cut_index": 1331, "middle_length": 229 }
utils import translation from ...utils import setup class I18nFiltersTests(SimpleTestCase): libraries = { "custom": "template_tests.templatetags.custom", "i18n": "django.templatetags.i18n", } @setup( { "i18n32": '{% load i18n %}{{ "hu"|language_name }} ' '...
rian Magyar False maďarsky") @setup( { "i18n33": "{% load i18n %}" "{{ langcode|language_name }} {{ langcode|language_name_local }} " "{{ langcode|language_bidi }} {{ langcode|language_name_translated }}"
ring("i18n32") self.assertEqual(output, "Hungarian Magyar False Hungarian") with translation.override("cs"): output = self.engine.render_to_string("i18n32") self.assertEqual(output, "Hunga
{ "filepath": "tests/template_tests/syntax_tests/i18n/test_filters.py", "language": "python", "file_size": 2122, "cut_index": 563, "middle_length": 229 }
t SimpleTestCase from ...utils import setup class GetAvailableLanguagesTagTests(SimpleTestCase): libraries = {"i18n": "django.templatetags.i18n"} @setup( { "i18n12": "{% load i18n %}" "{% get_available_languages as langs %}{% for lang in langs %}" '{% if lang.0 ==...
languages a langs %}"}) def test_no_as_var(self): msg = ( "'get_available_languages' requires 'as variable' (got " "['get_available_languages', 'a', 'langs'])" ) with self.assertRaisesMessage(TemplateSynt
up({"syntax_i18n": "{% load i18n %}{% get_available_
{ "filepath": "tests/template_tests/syntax_tests/i18n/test_get_available_languages.py", "language": "python", "file_size": 961, "cut_index": 582, "middle_length": 52 }
rt TemplateSyntaxError from django.test import SimpleTestCase from django.utils import translation from ...utils import setup class I18nGetLanguageInfoTagTests(SimpleTestCase): libraries = { "custom": "template_tests.templatetags.custom", "i18n": "django.templatetags.i18n", } # retrievin...
"i18n29": "{% load i18n %}" "{% get_language_info for LANGUAGE_CODE as l %}" "{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}" } ) def test_i18n29(self): output = self.engine.render_to_string(
al }} bidi={{ l.bidi }}" } ) def test_i18n28_2(self): output = self.engine.render_to_string("i18n28_2") self.assertEqual(output, "de: German/Deutsch bidi=False") @setup( {
{ "filepath": "tests/template_tests/syntax_tests/i18n/test_get_language_info.py", "language": "python", "file_size": 1928, "cut_index": 537, "middle_length": 229 }
m django.test import SimpleTestCase from django.utils import translation from ...utils import setup class GetLanguageInfoListTests(SimpleTestCase): libraries = { "custom": "template_tests.templatetags.custom", "i18n": "django.templatetags.i18n", } @setup( { "i18n30": ...
: Norwegian/norsk bidi=False; " ) @setup( { "i18n31": "{% load i18n %}" "{% get_language_info_list for langcodes as langs %}" "{% for l in langs %}{{ l.code }}: {{ l.name }}/" "{{ l.name_
}}; {% endfor %}" } ) def test_i18n30(self): output = self.engine.render_to_string("i18n30", {"langcodes": ["it", "no"]}) self.assertEqual( output, "it: Italian/italiano bidi=False; no
{ "filepath": "tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py", "language": "python", "file_size": 2518, "cut_index": 563, "middle_length": 229 }
port setup as base_setup from .base import MultipleLocaleActivationTestCase, extended_locale_paths def setup(templates, *args, **kwargs): translate_setup = base_setup(templates, *args, **kwargs) trans_setup = base_setup( { name: template.replace("{% translate ", "{% trans ") fo...
, tag_name=tag_name))(self) else: setup_func(func)(self) return inner return decorator class I18nTransTagTests(SimpleTestCase): libraries = {"i18n": "django.templatetags.i18n"} @setup({"i18n01":
def inner(self, *args): signature = inspect.signature(func) for tag_name, setup_func in tags.items(): if "tag_name" in signature.parameters: setup_func(partial(func
{ "filepath": "tests/template_tests/syntax_tests/i18n/test_translate.py", "language": "python", "file_size": 12194, "cut_index": 921, "middle_length": 229 }
import translation from ...utils import setup from .base import MultipleLocaleActivationTestCase class MultipleLocaleActivationTests(MultipleLocaleActivationTestCase): def test_single_locale_activation(self): """ Simple baseline behavior with one locale for all the supported i18n constru...
tion.override("nl"): self.assertEqual(t.render(Context({})), "nee") def test_multiple_locale_filter_deactivate(self): with translation.override("de", deactivate=True): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,m
ession def test_multiple_locale_filter(self): with translation.override("de"): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") with translation.override(self._old_language), transla
{ "filepath": "tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py", "language": "python", "file_size": 4354, "cut_index": 614, "middle_length": 229 }
ses a decorator (@mark_safe).""" return '<div data-name="%s"></div>' % value @register.simple_block_tag def div(content, id="test"): return format_html("<div id='{}'>{}</div>", id, content) @register.simple_block_tag(end_name="divend") def div_custom_end(content): return format_html("<div>{}</div>", con...
no_params __doc__""" return "no_params - Expected result" no_params.anything = "Expected no_params __dict__" @register.simple_tag def one_param(arg): """Expected one_param __doc__""" return "one_param - Expected result: %s" % arg one_par
tespace in filter arguments (see #19882).""" return value @register.simple_tag(takes_context=True) def context_stack_length(context): return len(context.dicts) @register.simple_tag def no_params(): """Expected
{ "filepath": "tests/template_tests/templatetags/custom.py", "language": "python", "file_size": 9402, "cut_index": 921, "middle_length": 229 }
__doc__""" return {"result": "inclusion_no_params - Expected result"} inclusion_no_params.anything = "Expected inclusion_no_params __dict__" @register.inclusion_tag(engine.get_template("inclusion.html")) def inclusion_no_params_from_template(): """Expected inclusion_no_params_from_template __doc__""" re...
usion_one_param __dict__" @register.inclusion_tag(engine.get_template("inclusion.html")) def inclusion_one_param_from_template(arg): """Expected inclusion_one_param_from_template __doc__""" return {"result": "inclusion_one_param_from_template - E
inclusion_tag("inclusion.html") def inclusion_one_param(arg): """Expected inclusion_one_param __doc__""" return {"result": "inclusion_one_param - Expected result: %s" % arg} inclusion_one_param.anything = "Expected incl
{ "filepath": "tests/template_tests/templatetags/inclusion.py", "language": "python", "file_size": 8436, "cut_index": 716, "middle_length": 229 }
SQL reserved names Need to use a reserved SQL name as a column name or table name? Need to include a hyphen in a column or table name? No problem. Django quotes names appropriately behind the scenes, so your database won't complain about reserved-name usage. """ from django.db import models class Thing(models.Model...
s.CharField(max_length=1) having = models.CharField(max_length=1) where = models.DateField(max_length=1) has_hyphen = models.CharField(max_length=1, db_column="has-hyphen") class Meta: db_table = "select" def __str__(self):
alter = model
{ "filepath": "tests/reserved_names/models.py", "language": "python", "file_size": 815, "cut_index": 522, "middle_length": 14 }
from .models import Thing class ReservedNameTests(TestCase): def generate(self): day1 = datetime.date(2005, 1, 1) Thing.objects.create( when="a", join="b", like="c", drop="d", alter="e", having="f", where=day1, ...
like="c", drop="d", alter="e", having="f", where=day1, has_hyphen="h", ) self.assertEqual(t.when, "a") day2 = datetime.date(2006, 2, 2) u = Thing.obje
, alter="l", having="m", where=day2, ) def test_simple(self): day1 = datetime.date(2005, 1, 1) t = Thing.objects.create( when="a", join="b",
{ "filepath": "tests/reserved_names/tests.py", "language": "python", "file_size": 2048, "cut_index": 563, "middle_length": 229 }
rom django.db import models class Entity(models.Model): pass class Country(Entity): name = models.CharField(max_length=30) class EUCountry(Country): join_date = models.DateField() class City(models.Model): name = models.CharField(max_length=30) country = models.ForeignKey(Country, models.CAS...
name = models.CharField(max_length=30) born = models.ForeignKey(City, models.CASCADE, related_name="+") died = models.ForeignKey(City, models.CASCADE, related_name="+") class PersonProfile(models.Model): person = models.OneToOneField(Pers
proxy = True class CountryProxyProxy(CountryProxy): class Meta: proxy = True class CityCountryProxy(models.Model): country = models.ForeignKey(CountryProxyProxy, models.CASCADE) class Person(models.Model):
{ "filepath": "tests/select_for_update/models.py", "language": "python", "file_size": 1042, "cut_index": 513, "middle_length": 229 }