prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
6,
"srid": 4326,
}
)
self.assertEqual(rast.srid, 4326)
rast.srid = 3086
self.assertEqual(rast.srid, 3086)
def test_geotransform_and_friends(self):
# Assert correct values for file based raster
self.assertEqual(
self.rs.geotrans... | rtEqual(self.rs.scale.y, -100.0)
self.assertEqual(self.rs.skew, [0, 0])
self.assertEqual(self.rs.skew.x, 0)
self.assertEqual(self.rs.skew.y, 0)
# Create in-memory rasters and change gtvalues
rsmem = GDALRaster(JSON_R | tEqual(self.rs.origin.x, 511700.4680706557)
self.assertEqual(self.rs.origin.y, 435103.3771231986)
self.assertEqual(self.rs.scale, [100.0, -100.0])
self.assertEqual(self.rs.scale.x, 100.0)
self.asse | {
"filepath": "tests/gis_tests/gdal_tests/test_raster.py",
"language": "python",
"file_size": 35282,
"cut_index": 2151,
"middle_length": 229
} |
patial Reference examples
srlist = (
TestSRS(
'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,'
'AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],'
'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",'
'0.0174532925199433,... | 4326"),
"spheroid": ("EPSG", "7030"),
},
attr=(
("DATUM", "WGS_1984"),
(("SPHEROID", 1), "6378137"),
("primem|authority", "EPSG"),
),
),
TestSRS(
'PROJCS["NAD83 / Texas | l=False,
lin_name="unknown",
ang_name="degree",
lin_units=1.0,
ang_units=0.0174532925199,
auth={
None: ("EPSG", "4326"), # Top-level authority.
"GEOGCS": ("EPSG", " | {
"filepath": "tests/gis_tests/gdal_tests/test_srs.py",
"language": "python",
"file_size": 15789,
"cut_index": 921,
"middle_length": 229
} |
django.test.utils import modify_settings
from ..test_data import TEST_DATA
from .models import AllOGRFields
@skipUnlessDBFeature("supports_inspectdb")
class InspectDbTests(TestCase):
def test_geom_columns(self):
"""
Test the geo-enabled inspectdb command.
"""
out = StringIO()
... | tIn("geom = models.GeometryField(", output)
self.assertIn("point = models.GeometryField(", output)
@skipUnlessDBFeature("supports_3d_storage")
def test_3d_columns(self):
out = StringIO()
call_command(
"inspe | if connection.features.supports_geometry_field_introspection:
self.assertIn("geom = models.PolygonField()", output)
self.assertIn("point = models.PointField()", output)
else:
self.asser | {
"filepath": "tests/gis_tests/inspectapp/tests.py",
"language": "python",
"file_size": 9680,
"cut_index": 921,
"middle_length": 229
} |
b import models
class SimpleModel(models.Model):
class Meta:
abstract = True
class Location(SimpleModel):
point = models.PointField()
def __str__(self):
return self.point.wkt
class City(SimpleModel):
name = models.CharField(max_length=50)
state = models.CharField(max_length=2)... | city = models.ForeignKey(City, models.CASCADE)
center1 = models.PointField()
# Throwing a curveball w/`db_column` here.
center2 = models.PointField(srid=2276, db_column="mycenter")
border1 = models.PolygonField()
border2 = models.Pol |
class DirectoryEntry(SimpleModel):
listing_text = models.CharField(max_length=50)
location = models.ForeignKey(AugmentedLocation, models.CASCADE)
class Parcel(SimpleModel):
name = models.CharField(max_length=30)
| {
"filepath": "tests/gis_tests/relatedapp/models.py",
"language": "python",
"file_size": 1604,
"cut_index": 537,
"middle_length": 229
} |
y("id")
# RemovedInDjango70Warning: when the deprecation ends, the below
# queryset can be removed.
with ignore_warnings(
category=RemovedInDjango70Warning,
message=r"Calling select_related\(\) with no arguments is deprecated\.",
):
qs2 = City.objects.... | qs):
nm, st, lon, lat = ref
self.assertEqual(nm, c.name)
self.assertEqual(st, c.state)
self.assertAlmostEqual(lon, c.location.point.x, 6)
self.assertAlmostEqual(lat, c.location | ra", "TX", -97.516111, 33.058333),
("Roswell", "NM", -104.528056, 33.387222),
("Kecksburg", "PA", -79.460734, 40.18476),
)
for qs in (qs1, qs2, qs3):
for ref, c in zip(cities, | {
"filepath": "tests/gis_tests/relatedapp/tests.py",
"language": "python",
"file_size": 19328,
"cut_index": 1331,
"middle_length": 229
} |
(max_length=25)
class Meta:
abstract = True
def __str__(self):
return self.name
class State(NamedModel):
pass
class County(NamedModel):
state = models.ForeignKey(State, models.CASCADE)
mpoly = models.MultiPolygonField(srid=4269, null=True) # Multipolygon in NAD83
class Count... | ):
length = models.DecimalField(max_digits=6, decimal_places=2)
path = models.LineStringField()
class Meta:
app_label = "layermap"
# Same as `City` above, but for testing model inheritance.
class CityBase(NamedModel):
population | n = models.IntegerField()
density = models.DecimalField(max_digits=7, decimal_places=1)
dt = models.DateField()
point = models.PointField()
class Meta:
app_label = "layermap"
class Interstate(NamedModel | {
"filepath": "tests/gis_tests/layermap/models.py",
"language": "python",
"file_size": 3060,
"cut_index": 614,
"middle_length": 229
} |
es" / "counties.shp"
inter_shp = shp_path / "interstates" / "interstates.shp"
invalid_shp = shp_path / "invalid" / "emptypoints.shp"
has_nulls_geojson = shp_path / "has_nulls" / "has_nulls.geojson"
# Dictionaries to hold what's expected in the county shapefile.
NAMES = ["Bexar", "Galveston", "Harris", "Honolulu", "Pue... | bad2["name"] = "Nombre"
# Nonexistent geographic field type.
bad3 = copy(city_mapping)
bad3["point"] = "CURVE"
# Incrementing through the bad mapping dictionaries and
# ensuring that a LayerMapError is rais | ng LayerMapping initialization."
# Model field that does not exist.
bad1 = copy(city_mapping)
bad1["foobar"] = "FooField"
# Shapefile field that does not exist.
bad2 = copy(city_mapping)
| {
"filepath": "tests/gis_tests/layermap/tests.py",
"language": "python",
"file_size": 18359,
"cut_index": 1331,
"middle_length": 229
} |
mport feeds
from .models import City
class TestGeoRSS1(feeds.Feed):
link = "/city/"
title = "Test GeoDjango Cities"
def items(self):
return City.objects.all()
def item_link(self, item):
return "/city/%s/" % item.pk
def item_geometry(self, item):
return item.point
clas... | # Returning a simple tuple for the geometry.
return item.point.x, item.point.y
class TestGeoAtom1(TestGeoRSS1):
feed_type = feeds.GeoAtom1Feed
class TestGeoAtom2(TestGeoRSS2):
feed_type = feeds.GeoAtom1Feed
def geometry(self, o | # calling `City.objects.aggregate(Extent())` -- we can't do that call
# here because `Extent` is not implemented for MySQL/Oracle.
return (-123.30, -41.32, 174.78, 48.46)
def item_geometry(self, item):
| {
"filepath": "tests/gis_tests/geoapp/feeds.py",
"language": "python",
"file_size": 1809,
"cut_index": 537,
"middle_length": 229
} |
ils import gisfield_may_be_null
class NamedModel(models.Model):
name = models.CharField(max_length=30)
class Meta:
abstract = True
def __str__(self):
return self.name
class Country(NamedModel):
mpoly = models.MultiPolygonField() # SRID, by default, is 4326
class CountryWebMercat... | PolygonField(
null=gisfield_may_be_null
) # Allowing NULL geometries here.
class Meta:
app_label = "geoapp"
class Track(NamedModel):
line = models.LineStringField()
class MultiFields(NamedModel):
city = models.ForeignK | model from City
class PennsylvaniaCity(City):
county = models.CharField(max_length=30)
founded = models.DateTimeField(null=True)
class Meta:
app_label = "geoapp"
class State(NamedModel):
poly = models. | {
"filepath": "tests/gis_tests/geoapp/models.py",
"language": "python",
"file_size": 2489,
"cut_index": 563,
"middle_length": 229
} |
os import Point, Polygon
from django.db import connection
from django.db.models import Count, Min
from django.test import TestCase, skipUnlessDBFeature
from .models import City, ManyPointModel, MultiFields
class GeoExpressionsTests(TestCase):
fixtures = ["initial"]
def test_geometry_value_annotation(self):
... | ls_exact(p.transform(4326, clone=True), 10**-5))
self.assertEqual(point.srid, 4326)
@skipUnlessDBFeature("supports_geography")
def test_geography_value(self):
p = Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1)))
area = (
| transform")
def test_geometry_value_annotation_different_srid(self):
p = Point(1, 1, srid=32140)
point = City.objects.annotate(p=Value(p, GeometryField(srid=4326))).first().p
self.assertTrue(point.equa | {
"filepath": "tests/gis_tests/geoapp/test_expressions.py",
"language": "python",
"file_size": 3145,
"cut_index": 614,
"middle_length": 229
} |
Site
from django.test import TestCase, modify_settings, override_settings
from .models import City
@modify_settings(INSTALLED_APPS={"append": "django.contrib.sites"})
@override_settings(ROOT_URLCONF="gis_tests.geoapp.urls")
class GeoFeedTest(TestCase):
fixtures = ["initial"]
@classmethod
def setUpTestDa... | `GEOSGeometry` in `item_geometry`
doc1 = minidom.parseString(self.client.get("/feeds/rss1/").content)
# Uses a 2-tuple in `item_geometry`
doc2 = minidom.parseString(self.client.get("/feeds/rss2/").content)
feed1, feed2 = doc | actual = {n.nodeName for n in elem.childNodes}
expected = set(expected)
self.assertEqual(actual, expected)
def test_geofeed_rss(self):
"Tests geographic feeds using GeoRSS over RSSv2."
# Uses | {
"filepath": "tests/gis_tests/geoapp/test_feeds.py",
"language": "python",
"file_size": 4448,
"cut_index": 614,
"middle_length": 229
} |
,-123.30519600,48.46261100],'
'"coordinates":[-123.305196,48.462611]}'
)
chicago_json = json.loads(
'{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},'
'"bbox":[-87.65018,41.85039,-87.65018,41.85039],'
'"coordinates":[-87.65018,41.85... | -87.650175, 41.850385]
# Precision argument should only be an integer
with self.assertRaises(TypeError):
City.objects.annotate(geojson=functions.AsGeoJSON("point", precision="foo"))
# Reference queries and values.
| atures.unsupported_geojson_options:
del chicago_json["bbox"]
del victoria_json["bbox"]
if "precision" in connection.features.unsupported_geojson_options:
chicago_json["coordinates"] = [ | {
"filepath": "tests/gis_tests/geoapp/test_functions.py",
"language": "python",
"file_size": 39403,
"cut_index": 2151,
"middle_length": 229
} |
o.db import connection
from django.db.models import Index
from django.test import TransactionTestCase
from django.test.utils import isolate_apps
from .models import City
class SchemaIndexesTests(TransactionTestCase):
available_apps = []
models = [City]
def get_indexes(self, table):
with connecti... | return connection.introspection.supports_spatial_index(cursor, table)
elif connection.ops.oracle:
# Spatial indexes in Meta.indexes are not supported by the Oracle
# backend (see #31252).
return False
r | me, constraint in constraints.items()
if constraint["index"]
}
def has_spatial_indexes(self, table):
if connection.ops.mysql:
with connection.cursor() as cursor:
| {
"filepath": "tests/gis_tests/geoapp/test_indexes.py",
"language": "python",
"file_size": 2804,
"cut_index": 563,
"middle_length": 229
} |
.shortcuts import render_to_kmz
from django.db.models import Count, Min
from django.test import TestCase, skipUnlessDBFeature
from ..utils import skipUnlessGISLookup
from .models import City, PennsylvaniaCity, State, Truth
class GeoRegressionTests(TestCase):
fixtures = ["initial"]
def test_update(self):
... | 6)
City.objects.filter(name="Pueblo").update(point=bak)
pueblo.refresh_from_db()
self.assertAlmostEqual(bak.y, pueblo.point.y, 6)
self.assertAlmostEqual(bak.x, pueblo.point.x, 6)
def test_kmz(self):
"Testing `r | City.objects.filter(name="Pueblo").update(point=pueblo.point)
pueblo.refresh_from_db()
self.assertAlmostEqual(bak.y + 0.005, pueblo.point.y, 6)
self.assertAlmostEqual(bak.x + 0.005, pueblo.point.x, | {
"filepath": "tests/gis_tests/geoapp/test_regress.py",
"language": "python",
"file_size": 4039,
"cut_index": 614,
"middle_length": 229
} |
rializers
from django.test import TestCase
from .models import City, MultiFields, PennsylvaniaCity
class GeoJSONSerializerTests(TestCase):
fixtures = ["initial"]
def test_builtin_serializers(self):
"""
'geojson' should be listed in available serializers.
"""
all_formats = set... | e", "features"])
self.assertEqual(geodata["type"], "FeatureCollection")
self.assertEqual(len(geodata["features"]), len(City.objects.all()))
self.assertEqual(geodata["features"][0]["geometry"]["type"], "Point")
self.assertEqu | public_formats)
def test_serialization_base(self):
geojson = serializers.serialize("geojson", City.objects.order_by("name"))
geodata = json.loads(geojson)
self.assertEqual(list(geodata.keys()), ["typ | {
"filepath": "tests/gis_tests/geoapp/test_serializers.py",
"language": "python",
"file_size": 4551,
"cut_index": 614,
"middle_length": 229
} |
import minidom
from django.conf import settings
from django.contrib.sites.models import Site
from django.test import TestCase, modify_settings, override_settings
from .models import City, Country
@modify_settings(
INSTALLED_APPS={"append": ["django.contrib.sites", "django.contrib.sitemaps"]}
)
@override_setting... | )
def test_geositemap_kml(self):
"Tests KML/KMZ geographic sitemaps."
for kml_type in ("kml", "kmz"):
doc = minidom.parseString(
self.client.get("/sitemaps/%s.xml" % kml_type).content
)
| .save()
def assertChildNodes(self, elem, expected):
"Taken from syndication/tests.py."
actual = {n.nodeName for n in elem.childNodes}
expected = set(expected)
self.assertEqual(actual, expected | {
"filepath": "tests/gis_tests/geoapp/test_sitemaps.py",
"language": "python",
"file_size": 2724,
"cut_index": 563,
"middle_length": 229
} |
GeometryCollectionModel,
Lines,
MinusOneSRID,
MultiFields,
NonConcreteModel,
PennsylvaniaCity,
Points,
State,
ThreeDimensionalFeature,
Track,
)
class GeoModelTest(TestCase):
fixtures = ["initial"]
def test_fixtures(self):
"Testing geographic model initializati... | ullCity", point=pnt)
nullcity.save()
# Making sure TypeError is thrown when trying to set with an
# incompatible type.
for bad in [5, 2.0, LineString((0, 0), (1, 1))]:
with self.assertRaisesMessage(TypeError, " | self.assertEqual(2, State.objects.count())
def test_proxy(self):
"Testing Lazy-Geometry support (using the GeometryProxy)."
# Testing on a Point
pnt = Point(0, 0)
nullcity = City(name="N | {
"filepath": "tests/gis_tests/geoapp/tests.py",
"language": "python",
"file_size": 33600,
"cut_index": 1331,
"middle_length": 229
} |
django.contrib.gis import views as gis_views
from django.contrib.gis.sitemaps import views as gis_sitemap_views
from django.contrib.sitemaps import views as sitemap_views
from django.urls import path
from .feeds import feed_dict
from .sitemaps import sitemaps
urlpatterns = [
path("feeds/<path:url>/", gis_views.fe... | ld_name>.kml",
gis_sitemap_views.kml,
name="django.contrib.gis.sitemaps.views.kml",
),
path(
"sitemaps/kml/<label>/<model>/<field_name>.kmz",
gis_sitemap_views.kmz,
name="django.contrib.gis.sitemaps.views.kmz | >/<model>/<fie | {
"filepath": "tests/gis_tests/geoapp/urls.py",
"language": "python",
"file_size": 799,
"cut_index": 517,
"middle_length": 14
} |
contrib.gis.db import models
from ..utils import gisfield_may_be_null
class NamedModel(models.Model):
name = models.CharField(max_length=30)
class Meta:
abstract = True
def __str__(self):
return self.name
class SouthTexasCity(NamedModel):
"City model on projected coordinate system... | allowed_distance = models.FloatField(default=0.5)
ref_point = models.PointField(null=True)
class CensusZipcode(NamedModel):
"Model for a few South Texas ZIP codes (in original Census NAD83)."
poly = models.PolygonField(srid=4269)
class S | ey feet are the units."
point = models.PointField(srid=2278)
class AustraliaCity(NamedModel):
"City model for Australia, using WGS84."
point = models.PointField()
radius = models.IntegerField(default=10000)
| {
"filepath": "tests/gis_tests/distapp/models.py",
"language": "python",
"file_size": 1407,
"cut_index": 524,
"middle_length": 229
} |
elf):
# A point we are testing distances with -- using a WGS84
# coordinate that'll be implicitly transformed to that to
# the coordinate system of the field, EPSG:32140 (Texas South Central
# w/units in meters)
self.stx_pnt = GEOSGeometry(
"POINT (-95.370401017314293... | self.assertEqual(9, SouthTexasCityFt.objects.count())
self.assertEqual(11, AustraliaCity.objects.count())
self.assertEqual(4, SouthTexasZipcode.objects.count())
self.assertEqual(4, CensusZipcode.objects.count())
self.assertE | .name for c in qs]
cities.sort()
return cities
def test_init(self):
"""
Test initialization of distance models.
"""
self.assertEqual(9, SouthTexasCity.objects.count())
| {
"filepath": "tests/gis_tests/distapp/tests.py",
"language": "python",
"file_size": 31446,
"cut_index": 1331,
"middle_length": 229
} |
b import models
class NamedModel(models.Model):
name = models.CharField(max_length=30)
class Meta:
abstract = True
def __str__(self):
return self.name
class City3D(NamedModel):
point = models.PointField(dim=3)
pointg = models.PointField(dim=3, geography=True)
class Meta:
... | = models.LineStringField(dim=3, srid=32140)
class Meta:
required_db_features = {"supports_3d_storage"}
class Polygon2D(NamedModel):
poly = models.PolygonField(srid=32140)
class Polygon3D(NamedModel):
poly = models.PolygonField(dim | ingField(dim=3, srid=4269)
class Meta:
required_db_features = {"supports_3d_storage"}
class InterstateProj2D(NamedModel):
line = models.LineStringField(srid=32140)
class InterstateProj3D(NamedModel):
line | {
"filepath": "tests/gis_tests/geo3d/models.py",
"language": "python",
"file_size": 1545,
"cut_index": 537,
"middle_length": 229
} |
ty3D,
Interstate2D,
Interstate3D,
InterstateProj2D,
InterstateProj3D,
MultiPoint3D,
Point2D,
Point3D,
Polygon2D,
Polygon3D,
)
data_path = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "data"))
city_file = os.path.join(data_path, "cities", "cities.shp")
vrt_file = os... | 235060, 38.971823, 251)),
("Chicago", (-87.650175, 41.850385, 181)),
("Victoria", (-123.305196, 48.462611, 15)),
)
# Reference mapping of city name to its altitude (Z value).
city_dict = {name: coords for name, coords in city_data}
# 3D freeway d | 74, 18)),
("Dallas", (-96.801611, 32.782057, 147)),
("Oklahoma City", (-97.521157, 34.464642, 380)),
("Wellington", (174.783117, -41.315268, 14)),
("Pueblo", (-104.609252, 38.255001, 1433)),
("Lawrence", (-95. | {
"filepath": "tests/gis_tests/geo3d/tests.py",
"language": "python",
"file_size": 14005,
"cut_index": 921,
"middle_length": 229
} |
harField(max_length=30)
class Meta:
abstract = True
def __str__(self):
return self.name
class City(NamedModel):
point = models.PointField(geography=True)
class Meta:
app_label = "geogapp"
class CityUnique(NamedModel):
point = models.PointField(geography=True, unique=Tr... | gonField(geography=True)
class County(NamedModel):
state = models.CharField(max_length=20)
mpoly = models.MultiPolygonField(geography=True)
class Meta:
app_label = "geogapp"
def __str__(self):
return " County, ".join([se | dels.CharField(max_length=10)
poly = models.Poly | {
"filepath": "tests/gis_tests/geogapp/models.py",
"language": "python",
"file_size": 936,
"cut_index": 606,
"middle_length": 52
} |
D
from django.core.exceptions import ValidationError
from django.db import NotSupportedError, connection
from django.db.models.functions import Cast
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from django.test.utils import CaptureQueriesContext
from ..utils import FuncTestMixin
from .models... | ography fields."
z = Zipcode.objects.get(code="77002")
cities1 = list(
City.objects.filter(point__distance_lte=(z.poly, D(mi=500)))
.order_by("name")
.values_list("name", flat=True)
)
citi | self.assertEqual(8, City.objects.count())
@skipUnlessDBFeature("supports_distances_lookups", "supports_distance_geodetic")
def test02_distance_lookup(self):
"Testing distance lookup support on non-point ge | {
"filepath": "tests/gis_tests/geogapp/tests.py",
"language": "python",
"file_size": 8075,
"cut_index": 716,
"middle_length": 229
} |
test_str(self):
self.assertEqual(
str(MediaAsset("path/to/css")),
"http://media.example.com/static/path/to/css",
)
self.assertEqual(
str(MediaAsset("http://media.other.com/path/to/css")),
"http://media.other.com/path/to/css",
)
def tes... |
asset = MediaAsset("http://media.other.com/path/to/css")
self.assertEqual(asset.path, "http://media.other.com/path/to/css")
asset = MediaAsset("https://secure.other.com/path/to/css")
self.assertEqual(asset.path, "https://s | ),
"MediaAsset('http://media.other.com/path/to/css')",
)
def test_path(self):
asset = MediaAsset("path/to/css")
self.assertEqual(asset.path, "http://media.example.com/static/path/to/css")
| {
"filepath": "tests/forms_tests/tests/test_media.py",
"language": "python",
"file_size": 40771,
"cut_index": 2151,
"middle_length": 229
} |
ort SimpleUploadedFile
class TestFieldWithValidators(TestCase):
def test_all_errors_get_reported(self):
class UserForm(forms.Form):
full_name = forms.CharField(
max_length=50,
validators=[
validators.validate_integer,
vali... | ength=50,
validators=[
validators.RegexValidator(
regex="^[a-z]*$",
message="Letters only.",
flags=re.IGNORECASE,
)
| lidator(
regex="^[a-zA-Z]*$",
message="Letters only.",
)
],
)
ignore_case_string = forms.CharField(
max_l | {
"filepath": "tests/forms_tests/tests/test_validators.py",
"language": "python",
"file_size": 6837,
"cut_index": 716,
"middle_length": 229
} |
class Meta:
exclude = ["multi_choice"]
model = ChoiceFieldModel
class EmptyCharLabelChoiceForm(ModelForm):
class Meta:
model = ChoiceModel
fields = ["name", "choice"]
class EmptyIntegerLabelChoiceForm(ModelForm):
class Meta:
model = ChoiceModel
fields = [... | eld has blank=True and is saved with no data,
a queryset is returned.
"""
option = ChoiceOptionModel.objects.create(name="default")
form = OptionalMultiChoiceModelForm(
{"multi_choice_optional": "", "multi_choice |
file1 = FileField()
class TestTicket14567(TestCase):
"""
The return values of ModelMultipleChoiceFields are QuerySets
"""
def test_empty_queryset_return(self):
"""
If a model's ManyToManyFi | {
"filepath": "tests/forms_tests/tests/tests.py",
"language": "python",
"file_size": 19501,
"cut_index": 1331,
"middle_length": 229
} |
_URLCONF="context_processors.urls",
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
],
... | # We should have the request object in the template.
response = self.client.get(url)
self.assertContains(response, "Have request")
# Test is_secure.
response = self.client.get(url)
self.assertContains(response, "Not | est_attributes(self):
"""
The request object is available in the template and that its
attributes can't be overridden by GET and POST parameters (#3828).
"""
url = "/request_attrs/"
| {
"filepath": "tests/context_processors/tests.py",
"language": "python",
"file_size": 5413,
"cut_index": 716,
"middle_length": 229
} |
set."
# Input that doesn't specify the SRID is assumed to be in the SRID
# of the input field.
fld = forms.GeometryField(srid=4326)
geom = fld.clean("POINT(5 23)")
self.assertEqual(4326, geom.srid)
# Making the field in a different SRID from that of the geometry, and
... | .
cleaned_geom = fld.clean(
"SRID=3857;POINT (-10615777.40976205 3473169.895707852)"
)
self.assertEqual(cleaned_geom.srid, 32140)
self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol))
def test_null(sel | racy.
tol = 1
xform_geom = GEOSGeometry(
"POINT (951640.547328465 4219369.26171664)", srid=32140
)
# The cleaned geometry is transformed to 32140 (the widget map_srid is
# 3857) | {
"filepath": "tests/gis_tests/test_geoforms.py",
"language": "python",
"file_size": 21557,
"cut_index": 1331,
"middle_length": 229
} |
nection, models
from django.test import SimpleTestCase
from .utils import FuncTestMixin
def test_mutation(raises=True):
def wrapper(mutation_func):
def test(test_case_instance, *args, **kwargs):
class TestFunc(models.Func):
output_field = models.IntegerField()
... | or, msg):
getattr(TestFunc(), "as_" + connection.vendor)(None, None)
else:
getattr(TestFunc(), "as_" + connection.vendor)(None, None)
return test
return wrapper
class FuncTestMixinTests(FuncTe | mutation_func(self)
return "", ()
if raises:
msg = "TestFunc Func was mutated during compilation."
with test_case_instance.assertRaisesMessage(AssertionErr | {
"filepath": "tests/gis_tests/test_gis_tests_utils.py",
"language": "python",
"file_size": 1558,
"cut_index": 537,
"middle_length": 229
} |
o.contrib.gis.ptr import CPointerBase
from django.test import SimpleTestCase
class CPointerBaseTests(SimpleTestCase):
def test(self):
destructor_mock = mock.Mock()
class NullPointerException(Exception):
pass
class FakeGeom1(CPointerBase):
null_ptr_exception_class ... | 3))
fg2.ptr = None
# Because pointers have been set to NULL, an exception is raised on
# access. Raising an exception is preferable to a segmentation fault
# that commonly occurs when a C method is given a NULL reference.
| 2 = FakeGeom2()
# These assignments are OK. None is allowed because it's equivalent
# to the NULL pointer.
fg1.ptr = fg1.ptr_type()
fg1.ptr = None
fg2.ptr = fg2.ptr_type(ctypes.c_float(5.2 | {
"filepath": "tests/gis_tests/test_ptr.py",
"language": "python",
"file_size": 2398,
"cut_index": 563,
"middle_length": 229
} |
import (
CharField,
Form,
JSONField,
Textarea,
TextInput,
ValidationError,
)
from django.test import SimpleTestCase
class JSONFieldTest(SimpleTestCase):
def test_valid(self):
field = JSONField()
value = field.clean('{"a": "b"}')
self.assertEqual(value, {"a": "b"})
... | self.assertEqual(field.prepare_value({"a": "b"}), '{"a": "b"}')
self.assertEqual(field.prepare_value(None), "null")
self.assertEqual(field.prepare_value("foo"), '"foo"')
self.assertEqual(field.prepare_value("你好,世界"), '"你好,世界"')
| field = JSONField()
with self.assertRaisesMessage(ValidationError, "Enter a valid JSON."):
field.clean("{some badly formed: json}")
def test_prepare_value(self):
field = JSONField()
| {
"filepath": "tests/forms_tests/field_tests/test_jsonfield.py",
"language": "python",
"file_size": 4900,
"cut_index": 614,
"middle_length": 229
} |
ectMultiple,
SplitDateTimeField,
SplitDateTimeWidget,
TextInput,
)
from django.test import SimpleTestCase
beatles = (("J", "John"), ("P", "Paul"), ("G", "George"), ("R", "Ringo"))
class PartiallyRequiredField(MultiValueField):
def compress(self, data_list):
return ",".join(data_list) if data_... | Multiple(choices=beatles),
SplitDateTimeWidget(),
)
super().__init__(widgets, attrs)
def decompress(self, value):
if value:
data = value.split(",")
return [
data[0],
| _all_fields=False,
widget=MultiWidget(widgets=[TextInput(), TextInput()]),
)
class ComplexMultiWidget(MultiWidget):
def __init__(self, attrs=None):
widgets = (
TextInput(),
Select | {
"filepath": "tests/forms_tests/field_tests/test_multivaluefield.py",
"language": "python",
"file_size": 7406,
"cut_index": 716,
"middle_length": 229
} |
leTestCase
from . import FormFieldAssertionsMixin
class NullBooleanFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
def test_nullbooleanfield_clean(self):
f = NullBooleanField()
self.assertIsNone(f.clean(""))
self.assertTrue(f.clean(True))
self.assertFalse(f.clean(False))
... | put (#7753).
class HiddenNullBooleanForm(Form):
hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True)
hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False)
f = HiddenNullBooleanForm( | )
self.assertIsNone(f.clean("hello"))
self.assertTrue(f.clean("true"))
self.assertFalse(f.clean("false"))
def test_nullbooleanfield_2(self):
# The internal value is preserved if using HiddenIn | {
"filepath": "tests/forms_tests/field_tests/test_nullbooleanfield.py",
"language": "python",
"file_size": 3617,
"cut_index": 614,
"middle_length": 229
} |
ase
class SlugFieldTest(SimpleTestCase):
def test_slugfield_normalization(self):
f = SlugField()
self.assertEqual(f.clean(" aa-bb-cc "), "aa-bb-cc")
def test_slugfield_unicode_normalization(self):
f = SlugField(allow_unicode=True)
self.assertEqual(f.clean("a"), "a")
... | self.assertEqual(f.clean("foo-ıç-bar"), "foo-ıç-bar")
def test_empty_value(self):
f = SlugField(required=False)
self.assertEqual(f.clean(""), "")
self.assertEqual(f.clean(None), "")
f = SlugField(required=False, empty_v | self.assertEqual(f.clean("ıçğüş"), "ıçğüş")
| {
"filepath": "tests/forms_tests/field_tests/test_slugfield.py",
"language": "python",
"file_size": 1011,
"cut_index": 582,
"middle_length": 52
} |
itDateTimeField
from django.forms.widgets import SplitDateTimeWidget
from django.test import SimpleTestCase
class SplitDateTimeFieldTest(SimpleTestCase):
def test_splitdatetimefield_1(self):
f = SplitDateTimeField()
self.assertIsInstance(f.widget, SplitDateTimeWidget)
self.assertEqual(
... | of values.'"):
f.clean("hello")
with self.assertRaisesMessage(
ValidationError, "'Enter a valid date.', 'Enter a valid time.'"
):
f.clean(["hello", "there"])
with self.assertRaisesMessage(Validati | field is required.'"):
f.clean(None)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean("")
with self.assertRaisesMessage(ValidationError, "'Enter a list | {
"filepath": "tests/forms_tests/field_tests/test_splitdatetimefield.py",
"language": "python",
"file_size": 3868,
"cut_index": 614,
"middle_length": 229
} |
pleChoiceField
from django.test import SimpleTestCase
class TypedMultipleChoiceFieldTest(SimpleTestCase):
def test_typedmultiplechoicefield_1(self):
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
self.assertEqual([1], f.clean(["1"]))
msg = "'Select a valid choice... | can also cause weirdness: be careful (bool(-1) == True,
# remember)
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool)
self.assertEqual([True], f.clean(["-1"]))
def test_typedmultiplechoicefield_4(self): | ferent coercion, same validation.
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float)
self.assertEqual([1.0], f.clean(["1"]))
def test_typedmultiplechoicefield_3(self):
# This | {
"filepath": "tests/forms_tests/field_tests/test_typedmultiplechoicefield.py",
"language": "python",
"file_size": 3696,
"cut_index": 614,
"middle_length": 229
} |
uuid
from django.core.exceptions import ValidationError
from django.forms import UUIDField
from django.test import SimpleTestCase
class UUIDFieldTest(SimpleTestCase):
def test_uuidfield_1(self):
field = UUIDField()
value = field.clean("550e8400e29b41d4a716446655440000")
self.assertEqual(... | ld.clean(None))
def test_uuidfield_3(self):
field = UUIDField()
with self.assertRaisesMessage(ValidationError, "Enter a valid UUID."):
field.clean("550e8400")
def test_uuidfield_4(self):
field = UUIDField()
| ")
self.assertEqual(value, uuid.UUID("550e8400e29b41d4a716446655440000"))
def test_uuidfield_2(self):
field = UUIDField(required=False)
self.assertIsNone(field.clean(""))
self.assertIsNone(fie | {
"filepath": "tests/forms_tests/field_tests/test_uuidfield.py",
"language": "python",
"file_size": 1155,
"cut_index": 518,
"middle_length": 229
} |
irst_name" aria-describedby="id_first_name_error"></div>'
'<div><label for="id_last_name">Last name:</label>'
'<ul class="errorlist" id="id_last_name_error"><li>This field is required.'
'</li></ul><input type="text" name="last_name" aria-invalid="true" '
'required id="id_... | p.as_table(),
"""<tr><th><label for="id_first_name">First name:</label></th><td>
<ul class="errorlist" id="id_first_name_error"><li>This field is required.</li></ul>
<input type="text" name="first_name" id="id_first_name" aria-invalid="true" | is required.'
'</li></ul><input type="text" name="birthday" aria-invalid="true" required '
'id="id_birthday" aria-describedby="id_birthday_error"></div>',
)
self.assertHTMLEqual(
| {
"filepath": "tests/forms_tests/tests/test_forms.py",
"language": "python",
"file_size": 239497,
"cut_index": 7068,
"middle_length": 229
} |
,
)
from django.test import SimpleTestCase
from django.utils import translation
from django.utils.translation import gettext_lazy
from . import jinja2_tests
class FormsI18nTests(SimpleTestCase):
def test_lazy_labels(self):
class SomeForm(Form):
username = CharField(max_length=10, label=gettex... | self.assertHTMLEqual(
f.as_p(),
'<p><label for="id_username">Benutzername:</label>'
'<input id="id_username" type="text" name="username" maxlength="10" '
"required></p>",
| type="text" name="username" maxlength="10" '
"required></p>",
)
# Translations are done at rendering time, so multi-lingual apps can
# define forms.
with translation.override("de"):
| {
"filepath": "tests/forms_tests/tests/test_i18n.py",
"language": "python",
"file_size": 6103,
"cut_index": 716,
"middle_length": 229
} |
port unittest
from django.forms.renderers import (
BaseRenderer,
DjangoTemplates,
Jinja2,
TemplatesSetting,
)
from django.test import SimpleTestCase
try:
import jinja2
except ImportError:
jinja2 = None
class SharedTests:
expected_widget_dir = "templates"
def test_installed_apps_temp... | idget.html",
)
)
self.assertEqual(tpl.origin.name, expected_path)
class BaseTemplateRendererTests(SimpleTestCase):
def test_get_renderer(self):
with self.assertRaisesMessage(
NotImplementedError, "subcl | orms_tests/custom_widget.html")
expected_path = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
"..",
self.expected_widget_dir + "/forms_tests/custom_w | {
"filepath": "tests/forms_tests/tests/test_renderers.py",
"language": "python",
"file_size": 1442,
"cut_index": 524,
"middle_length": 229
} |
settings
from django.urls import reverse
from ..models import Article
@override_settings(ROOT_URLCONF="forms_tests.urls")
class LiveWidgetTests(AdminSeleniumTestCase):
available_apps = ["forms_tests"] + AdminSeleniumTestCase.available_apps
def test_textarea_trailing_newlines(self):
"""
A rou... | everse("article_form", args=[article.pk])
)
with self.wait_page_loaded():
self.selenium.find_element(By.ID, "submit").click()
article = Article.objects.get(pk=article.pk)
self.assertEqual(article.content, "\r\nTs | f.selenium.get(
self.live_server_url + r | {
"filepath": "tests/forms_tests/tests/test_widgets.py",
"language": "python",
"file_size": 922,
"cut_index": 606,
"middle_length": 52
} |
contrib.gis.db.models import GeometryField
from django.contrib.gis.db.models.sql import AreaField, DistanceField
from django.test import SimpleTestCase
class FieldsTests(SimpleTestCase):
def test_area_field_deepcopy(self):
field = AreaField(None)
self.assertEqual(copy.deepcopy(field), field)
... | =4067,
dim=3,
geography=True,
extent=(
50199.4814,
6582464.0358,
-50000.0,
761274.6247,
7799839.8902,
50000.0,
) | struct_empty(self):
field = GeometryField()
*_, kwargs = field.deconstruct()
self.assertEqual(kwargs, {"srid": 4326})
def test_deconstruct_values(self):
field = GeometryField(
srid | {
"filepath": "tests/gis_tests/test_fields.py",
"language": "python",
"file_size": 1553,
"cut_index": 537,
"middle_length": 229
} |
django.test import SimpleTestCase
class DistanceTest(SimpleTestCase):
"Testing the Distance object"
def test_init(self):
"Testing initialization from valid units"
d = Distance(m=100)
self.assertEqual(d.m, 100)
d1, d2, d3 = D(m=100), D(meter=100), D(metre=100)
for d in... | f test_init_invalid(self):
"Testing initialization from invalid units"
with self.assertRaises(AttributeError):
D(banana=100)
def test_init_invalid_area_only_units(self):
with self.assertRaises(AttributeError):
| 1, y2, y3):
self.assertEqual(d.yd, 100)
mm1, mm2 = D(millimeter=1000), D(MiLLiMeTeR=1000)
for d in (mm1, mm2):
self.assertEqual(d.m, 1.0)
self.assertEqual(d.mm, 1000.0)
de | {
"filepath": "tests/gis_tests/test_measure.py",
"language": "python",
"file_size": 8529,
"cut_index": 716,
"middle_length": 229
} |
ort cached_property
test_srs = (
{
"srid": 4326,
"auth_name": ("EPSG", True),
"auth_srid": 4326,
# Only the beginning, because there are differences depending on
# installed libs
"srtext": 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84"',
"proj_re": (
... | "[\s+]",
"",
"""
GEOGCS["WGS 84",
DATUM["WGS_1984",
SPHEROID["WGS 84",6378137,298.257223563,
AUTHORITY["EPSG","7030"]],
AUTHORITY["EPSG","6326"]],
PRIMEM["Greenwich",0,
AUTHORITY[" | d": False,
"spatialite": True,
# From proj's "cs2cs -le" and Wikipedia (semi-minor only)
"ellipsoid": (6378137.0, 6356752.3, 298.257223563),
"eprec": (1, 1, 9),
"wkt": re.sub(
r | {
"filepath": "tests/gis_tests/test_spatialrefsys.py",
"language": "python",
"file_size": 6136,
"cut_index": 716,
"middle_length": 229
} |
ValidationError
from django.forms import TimeField
from django.test import SimpleTestCase
from . import FormFieldAssertionsMixin
class TimeFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
def test_timefield_1(self):
f = TimeField()
self.assertEqual(datetime.time(14, 25), f.clean(datetime.tim... | ime.'"):
f.clean("1:24 p.m.")
def test_timefield_2(self):
f = TimeField(input_formats=["%I:%M %p"])
self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25)))
self.assertEqual(datetime.time(14, 25, 59), | atetime.time(14, 25, 59), f.clean("14:25:59"))
with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
f.clean("hello")
with self.assertRaisesMessage(ValidationError, "'Enter a valid t | {
"filepath": "tests/forms_tests/field_tests/test_timefield.py",
"language": "python",
"file_size": 2035,
"cut_index": 563,
"middle_length": 229
} |
" required>')
def test_urlfield_widget_max_min_length(self):
f = URLField(min_length=15, max_length=20)
self.assertEqual("http://example.com", f.clean("http://example.com"))
self.assertWidgetRendersTo(
f,
'<input id="id_f" type="url" name="f" maxlength="20" '
... | test_urlfield_clean(self):
f = URLField(required=False)
tests = [
("http://localhost", "http://localhost"),
("http://example.com", "http://example.com"),
("http://example.com/test", "http://example.com/t | f.clean("http://f.com")
msg = "'Ensure this value has at most 20 characters (it has 37).'"
with self.assertRaisesMessage(ValidationError, msg):
f.clean("http://abcdefghijklmnopqrstuvwxyz.com")
def | {
"filepath": "tests/forms_tests/field_tests/test_urlfield.py",
"language": "python",
"file_size": 10370,
"cut_index": 921,
"middle_length": 229
} |
hoiceField,
RegexField,
SplitDateTimeField,
TimeField,
URLField,
utils,
)
from django.template import Context, Template
from django.test import SimpleTestCase, TestCase
from django.utils.safestring import mark_safe
from ..models import ChoiceModel
class AssertFormErrorsMixin:
def assertFormEr... | TH %(limit_value)s",
"max_length": "LENGTH %(show_value)s, MAX LENGTH %(limit_value)s",
}
f = CharField(min_length=5, max_length=10, error_messages=e)
self.assertFormErrors(["REQUIRED"], f.clean, "")
self.assertF | ages, expected)
class FormsErrorMessagesTestCase(SimpleTestCase, AssertFormErrorsMixin):
def test_charfield(self):
e = {
"required": "REQUIRED",
"min_length": "LENGTH %(show_value)s, MIN LENG | {
"filepath": "tests/forms_tests/tests/test_error_messages.py",
"language": "python",
"file_size": 13450,
"cut_index": 921,
"middle_length": 229
} |
ss FormsUtilsTestCase(SimpleTestCase):
# Tests for forms/utils.py module.
def test_flatatt(self):
###########
# flatatt #
###########
self.assertEqual(flatatt({"id": "header"}), ' id="header"')
self.assertEqual(
flatatt({"class": "news", "title": "Read this"... |
self.assertEqual(
flatatt({"class": "news", "title": "Read this", "required": False}),
' class="news" title="Read this"',
)
self.assertEqual(flatatt({"class": None}), "")
self.assertEqual(flatatt({}) | ="news" required="required" title="Read this"',
)
self.assertEqual(
flatatt({"class": "news", "title": "Read this", "required": True}),
' class="news" title="Read this" required',
) | {
"filepath": "tests/forms_tests/tests/test_utils.py",
"language": "python",
"file_size": 10934,
"cut_index": 921,
"middle_length": 229
} |
t GEOSGeometry
from django.test import SimpleTestCase, override_settings
if HAS_GEOIP2:
import geoip2
from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception
def build_geoip_path(*parts):
return pathlib.Path(__file__).parent.joinpath("data/geoip2", *parts).resolve()
@skipUnless(HAS_GEOIP2, "GeoI... | ected_city = {
"accuracy_radius": 100,
"city": "Boxford",
"continent_code": "EU",
"continent_name": "Europe",
"country_code": "GB",
"country_name": "United Kingdom",
"is_in_european_union": False,
| v4_str = "2.125.160.216"
ipv6_str = "::ffff:027d:a0d8"
ipv4_addr = ipaddress.ip_address(ipv4_str)
ipv6_addr = ipaddress.ip_address(ipv6_str)
query_values = (fqdn, ipv4_str, ipv6_str, ipv4_addr, ipv6_addr)
exp | {
"filepath": "tests/gis_tests/test_geoip2.py",
"language": "python",
"file_size": 9018,
"cut_index": 716,
"middle_length": 229
} |
jango.test import SimpleTestCase
class MultipleChoiceFieldTest(SimpleTestCase):
def test_multiplechoicefield_1(self):
f = MultipleChoiceField(choices=[("1", "One"), ("2", "Two")])
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean("")
with self... | a list of values.'"):
f.clean("hello")
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean([])
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
| self.assertEqual(["1", "2"], f.clean(["1", "2"]))
self.assertEqual(["1", "2"], f.clean([1, "2"]))
self.assertEqual(["1", "2"], f.clean((1, "2")))
with self.assertRaisesMessage(ValidationError, "'Enter | {
"filepath": "tests/forms_tests/field_tests/test_multiplechoicefield.py",
"language": "python",
"file_size": 4363,
"cut_index": 614,
"middle_length": 229
} |
get_blank_choice_label
from django.forms import TypedChoiceField
from django.test import SimpleTestCase
class TypedChoiceFieldTest(SimpleTestCase):
def test_typedchoicefield_1(self):
f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
self.assertEqual(1, f.clean("1"))
msg = "... | cause weirdness: be careful (bool(-1) == True,
# remember)
f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool)
self.assertTrue(f.clean("-1"))
def test_typedchoicefield_4(self):
# Even more weirdness: if | # Different coercion, same validation.
f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float)
self.assertEqual(1.0, f.clean("1"))
def test_typedchoicefield_3(self):
# This can also | {
"filepath": "tests/forms_tests/field_tests/test_typedchoicefield.py",
"language": "python",
"file_size": 3736,
"cut_index": 614,
"middle_length": 229
} |
d to hold reference geometry
for the GEOS and GDAL tests.
"""
import json
import os
from django.utils.functional import cached_property
# Path where reference test data is located.
TEST_DATA = os.path.join(os.path.dirname(__file__), "data")
def tuplize(seq):
"Turn all nested sequences to tuples in given sequen... | t__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
class TestDS(TestObj):
"""
Object for testing GDAL data sources.
"""
def __init__(self, name, *, ext="shp", **kwargs):
# Shapefi | (k): v for k, v in d.items()}
def get_ds_file(name, ext):
return os.path.join(TEST_DATA, name, name + ".%s" % ext)
class TestObj:
"""
Base testing object, turns keyword args into attributes.
"""
def __ini | {
"filepath": "tests/gis_tests/test_data.py",
"language": "python",
"file_size": 2499,
"cut_index": 563,
"middle_length": 229
} |
l(
str(formset),
"""<input type="hidden" name="choices-TOTAL_FORMS" value="1">
<input type="hidden" name="choices-INITIAL_FORMS" value="0">
<input type="hidden" name="choices-MIN_NUM_FORMS" value="0">
<input type="hidden" name="choices-MAX_NUM_FORMS" value="1000">
<div>Choice:<input type="text" ... | formset = self.make_choiceformset([("Calexico", "100")])
self.assertTrue(formset.is_valid())
self.assertEqual(
[form.cleaned_data for form in formset.forms],
[{"votes": 100, "choice": "Calexico"}],
)
| method, and a cleaned_data or errors attribute depending on whether
# all the forms passed validation. However, unlike a Form, cleaned_data
# and errors will be a list of dicts rather than a single dict.
| {
"filepath": "tests/forms_tests/tests/test_formsets.py",
"language": "python",
"file_size": 80140,
"cut_index": 3790,
"middle_length": 229
} |
django.test import SimpleTestCase
class RegexFieldTest(SimpleTestCase):
def test_regexfield_1(self):
f = RegexField("^[0-9][A-F][0-9]$")
self.assertEqual("2A2", f.clean("2A2"))
self.assertEqual("3F3", f.clean("3F3"))
with self.assertRaisesMessage(ValidationError, "'Enter a valid v... | d("^[0-9][A-F][0-9]$", required=False)
self.assertEqual("2A2", f.clean("2A2"))
self.assertEqual("3F3", f.clean("3F3"))
with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"):
f.clean("3G3")
self | ionError, "'Enter a valid value.'"):
f.clean("2A2 ")
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean("")
def test_regexfield_2(self):
f = RegexFiel | {
"filepath": "tests/forms_tests/field_tests/test_regexfield.py",
"language": "python",
"file_size": 3573,
"cut_index": 614,
"middle_length": 229
} |
trib.gis.geos.coordseq import GEOSCoordSeq
from django.contrib.gis.geos.libgeos import geos_version_tuple
from django.test import SimpleTestCase
class GEOSCoordSeqTest(SimpleTestCase):
def test_getitem(self):
coord_seq = LineString([(x, x) for x in range(2)]).coord_seq
for i in (0, 1):
... | ("POINT ZM (1 2 3 4)")
coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
self.assertIs(coord_seq.hasm, True)
geom = GEOSGeometry("POINT Z (1 2 3)")
coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
self. |
with self.assertRaisesMessage(IndexError, msg):
coord_seq[i]
@skipIf(geos_version_tuple() < (3, 14), "GEOS M support requires 3.14+")
def test_has_m(self):
geom = GEOSGeometry | {
"filepath": "tests/gis_tests/geos_tests/test_coordseq.py",
"language": "python",
"file_size": 6194,
"cut_index": 716,
"middle_length": 229
} |
from . import PostgreSQLTestCase
from .models import (
HStoreModel,
IntegerArrayModel,
NestedIntegerArrayModel,
NullableIntegerArrayModel,
OffByOneModel,
OtherTypesArrayModel,
RangesModel,
)
try:
from django.db.backends.postgresql.psycopg_any import DateRange, NumericRange
except Impo... | umericRange(lower=1, upper=10)),
(
RangesModel,
"dates",
None,
DateRange(lower=date.today(), upper=date.today()),
),
(OtherTypesArrayModel, "ips", [], ["1.2 | 2, 3]),
(NullableIntegerArrayModel, "field", [1, 2, 3], None),
(NestedIntegerArrayModel, "field", [], [[1, 2, 3]]),
(HStoreModel, "field", {}, {1: 2}),
(RangesModel, "ints", None, N | {
"filepath": "tests/postgres_tests/test_bulk_update.py",
"language": "python",
"file_size": 1870,
"cut_index": 537,
"middle_length": 229
} |
.introspection.get_constraints(cursor, table)
def test_check_constraint_range_value(self):
constraint_name = "ints_between"
self.assertNotIn(
constraint_name, self.get_constraints(RangesModel._meta.db_table)
)
constraint = CheckConstraint(
condition=Q(ints__c... | .objects.create(ints=(10, 30))
def test_check_constraint_array_contains(self):
constraint = CheckConstraint(
condition=Q(field__contains=[1]),
name="array_contains",
)
msg = f"Constraint “{constraint.nam | self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table))
with self.assertRaises(IntegrityError), transaction.atomic():
RangesModel.objects.create(ints=(20, 50))
RangesModel | {
"filepath": "tests/postgres_tests/test_constraints.py",
"language": "python",
"file_size": 55848,
"cut_index": 2151,
"middle_length": 229
} |
uuid
from datetime import datetime
from time import sleep
from django.contrib.postgres.functions import RandomUUID, TransactionNow
from . import PostgreSQLTestCase
from .models import NowTestModel, UUIDTestModel
class TestTransactionNow(PostgreSQLTestCase):
def test_transaction_now(self):
"""
T... | ()
m2.refresh_from_db()
self.assertIsInstance(m1.when, datetime)
self.assertEqual(m1.when, m2.when)
class TestRandomUUID(PostgreSQLTestCase):
def test_random_uuid(self):
m1 = UUIDTestModel.objects.create()
m2 | NowTestModel.objects.create()
NowTestModel.objects.filter(id=m1.id).update(when=TransactionNow())
sleep(0.1)
NowTestModel.objects.filter(id=m2.id).update(when=TransactionNow())
m1.refresh_from_db | {
"filepath": "tests/postgres_tests/test_functions.py",
"language": "python",
"file_size": 1246,
"cut_index": 518,
"middle_length": 229
} |
d=value)
instance.save()
reloaded = HStoreModel.objects.get()
self.assertEqual(reloaded.field, value)
def test_null(self):
instance = HStoreModel(field=None)
instance.save()
reloaded = HStoreModel.objects.get()
self.assertIsNone(reloaded.field)
def test_... | d=value)
instance = HStoreModel.objects.get()
self.assertEqual(instance.field, expected_value)
instance = HStoreModel.objects.get(field__a=1)
self.assertEqual(instance.field, expected_value)
instance = HStoreModel. | .field, value)
def test_key_val_cast_to_string(self):
value = {"a": 1, "b": "B", 2: "c", "ï": "ê"}
expected_value = {"a": "1", "b": "B", "2": "c", "ï": "ê"}
instance = HStoreModel.objects.create(fiel | {
"filepath": "tests/postgres_tests/test_hstore.py",
"language": "python",
"file_size": 17637,
"cut_index": 1331,
"middle_length": 229
} |
]{6}_%s" % self.index_class.suffix
)
def test_deconstruction_no_customization(self):
index = self.index_class(
fields=["title"], name="test_title_%s" % self.index_class.suffix
)
path, args, kwargs = index.deconstruct()
self.assertEqual(
path, "django.... | e=name)
path, args, kwargs = index.deconstruct()
self.assertEqual(
path,
f"django.contrib.postgres.indexes.{self.index_class.__name__}",
)
self.assertEqual(args, (Lower("title"),))
self.assert | est_title_%s" % self.index_class.suffix},
)
def test_deconstruction_with_expressions_no_customization(self):
name = f"test_title_{self.index_class.suffix}"
index = self.index_class(Lower("title"), nam | {
"filepath": "tests/postgres_tests/test_indexes.py",
"language": "python",
"file_size": 32967,
"cut_index": 1331,
"middle_length": 229
} |
sys
from . import PostgreSQLSimpleTestCase
class PostgresIntegrationTests(PostgreSQLSimpleTestCase):
def test_check(self):
test_environ = os.environ.copy()
if "DJANGO_SETTINGS_MODULE" in test_environ:
del test_environ["DJANGO_SETTINGS_MODULE"]
test_environ["PYTHONPATH"] = os.p... | "integration_settings",
],
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
cwd=os.path.dirname(__file__),
env=test_environ,
encoding="utf-8",
)
self.assertEqual(resu | eck",
"--settings",
| {
"filepath": "tests/postgres_tests/test_integration.py",
"language": "python",
"file_size": 892,
"cut_index": 547,
"middle_length": 52
} |
from django.core.management import call_command
from . import PostgreSQLTestCase
class InspectDBTests(PostgreSQLTestCase):
def assertFieldsInModel(self, model, field_outputs):
out = StringIO()
call_command(
"inspectdb",
table_name_filter=lambda tn: tn.startswith(model),
... | = django.contrib.postgres.fields.BigIntegerRangeField("
"blank=True, null=True)",
"decimals = django.contrib.postgres.fields.DecimalRangeField("
"blank=True, null=True)",
"timestamps = django. | self.assertFieldsInModel(
"postgres_tests_rangesmodel",
[
"ints = django.contrib.postgres.fields.IntegerRangeField(blank=True, "
"null=True)",
"bigints | {
"filepath": "tests/postgres_tests/test_introspection.py",
"language": "python",
"file_size": 1676,
"cut_index": 537,
"middle_length": 229
} |
on,
CreateCollation,
CreateExtension,
RemoveCollation,
RemoveIndexConcurrently,
ValidateConstraint,
)
except ImportError:
pass
@unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests.")
@modify_settings(INSTALLED_APPS={"append": "migrations"})... | e AddIndexConcurrently operation cannot be executed inside "
"a transaction (set atomic = False on the migration)."
)
with self.assertRaisesMessage(NotSupportedError, msg):
with connection.schema_editor(atomic=True) | est_model(self.app_label)
new_state = project_state.clone()
operation = AddIndexConcurrently(
"Pony",
Index(fields=["pink"], name="pony_pink_idx"),
)
msg = (
"Th | {
"filepath": "tests/postgres_tests/test_operations.py",
"language": "python",
"file_size": 30469,
"cut_index": 1331,
"middle_length": 229
} |
stance = Model(field=value)
self.assertEqual(instance.get_field_display(), display)
def test_discrete_range_fields_unsupported_default_bounds(self):
discrete_range_types = [
pg_fields.BigIntegerRangeField,
pg_fields.IntegerRangeField,
pg_fields.DateRangeF... | pg_fields.DateTimeRangeField,
]
for field_type in continuous_range_types:
field = field_type(choices=[((51, 100), "51-100")], default_bounds="[]")
self.assertEqual(field.default_bounds, "[]")
def test_in | , msg):
field_type(choices=[((51, 100), "51-100")], default_bounds="[]")
def test_continuous_range_fields_default_bounds(self):
continuous_range_types = [
pg_fields.DecimalRangeField,
| {
"filepath": "tests/postgres_tests/test_ranges.py",
"language": "python",
"file_size": 43599,
"cut_index": 2151,
"middle_length": 229
} |
d and his bowels unplugged, "
"And his nostrils ripped and his bottom burned off,"
"And his --"
),
]
cls.verses = [
Line.objects.create(
scene=cls.robin,
character=cls.minstrel,
dialogue=verse,
... | jects.create(name="Duck")
cls.bedemir0 = Line.objects.create(
scene=cls.witch_scene,
character=bedemir,
dialogue="We shall use my larger scales!",
dialogue_config="english",
)
cls.bed | "Sir Bedemir's Castle"
)
bedemir = Character.objects.create(name="Bedemir")
crowd = Character.objects.create(name="Crowd")
witch = Character.objects.create(name="Witch")
duck = Character.ob | {
"filepath": "tests/postgres_tests/test_search.py",
"language": "python",
"file_size": 37523,
"cut_index": 2151,
"middle_length": 229
} |
db import connection
from . import PostgreSQLTestCase
try:
from django.contrib.postgres.signals import (
get_citext_oids,
get_hstore_oids,
register_type_handlers,
)
except ImportError:
pass # psycopg isn't installed.
class OIDTests(PostgreSQLTestCase):
def assertOIDs(self, o... | Queries(0):
get_citext_oids(connection.alias)
def test_hstore_values(self):
oids, array_oids = get_hstore_oids(connection.alias)
self.assertOIDs(oids)
self.assertOIDs(array_oids)
def test_citext_values(self):
| get_hstore_oids(connection.alias)
with self.assertNumQueries(0):
get_hstore_oids(connection.alias)
def test_citext_cache(self):
get_citext_oids(connection.alias)
with self.assertNum | {
"filepath": "tests/postgres_tests/test_signals.py",
"language": "python",
"file_size": 1361,
"cut_index": 524,
"middle_length": 229
} |
res.search import (
TrigramDistance,
TrigramSimilarity,
TrigramStrictWordDistance,
TrigramStrictWordSimilarity,
TrigramWordDistance,
TrigramWordSimilarity,
)
except ImportError:
pass
class TrigramTest(PostgreSQLTestCase):
Model = CharFieldModel
@classme... | "],
transform=lambda instance: instance.field,
)
def test_trigram_word_search(self):
obj = self.Model.objects.create(
field="Gumby rides on the path of Middlesbrough",
)
self.assertSequenceEqual( | cls.Model(field="Dog sat on rug."),
]
)
def test_trigram_search(self):
self.assertQuerySetEqual(
self.Model.objects.filter(field__trigram_similar="Mathew"),
["Matthew | {
"filepath": "tests/postgres_tests/test_trigram.py",
"language": "python",
"file_size": 5941,
"cut_index": 716,
"middle_length": 229
} |
tgreSQLTestCase
from .models import CharFieldModel, TextFieldModel
class UnaccentTest(PostgreSQLTestCase):
Model = CharFieldModel
@classmethod
def setUpTestData(cls):
cls.Model.objects.bulk_create(
[
cls.Model(field="àéÖ"),
cls.Model(field="aeO"),
... | e the case
since unaccent implements the Transform API)
"""
self.assertQuerySetEqual(
self.Model.objects.filter(field__unaccent__iexact="aeO"),
["àéÖ", "aeO", "aeo"],
transform=lambda instance: in | ["àéÖ", "aeO"],
transform=lambda instance: instance.field,
ordered=False,
)
def test_unaccent_chained(self):
"""
Unaccent can be used chained with a lookup (which should b | {
"filepath": "tests/postgres_tests/test_unaccent.py",
"language": "python",
"file_size": 2653,
"cut_index": 563,
"middle_length": 229
} |
t django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="IntegerArrayDefaultModel",
fields=[
(
"id",
m... | ),
),
(
"field",
django.contrib.postgres.fields.ArrayField(models.IntegerField()),
),
],
options={},
bases=(models.Model,),
| {
"filepath": "tests/postgres_tests/array_default_migrations/0001_initial.py",
"language": "python",
"file_size": 799,
"cut_index": 517,
"middle_length": 14
} | |
rom unittest import mock
from django.db import migrations
try:
from django.contrib.postgres.operations import (
BloomExtension,
BtreeGinExtension,
BtreeGistExtension,
CITextExtension,
CreateExtension,
HStoreExtension,
TrigramExtension,
UnaccentExtens... | (),
BtreeGistExtension(),
CITextExtension(),
# Ensure CreateExtension quotes extension names by creating one with a
# dash in its name.
CreateExtension("uuid-ossp"),
HStoreExtension(),
TrigramExtensio | mock.Mock()
HStoreExtension = mock.Mock()
TrigramExtension = mock.Mock()
UnaccentExtension = mock.Mock()
class Migration(migrations.Migration):
operations = [
BloomExtension(),
BtreeGinExtension | {
"filepath": "tests/postgres_tests/migrations/0001_setup_extensions.py",
"language": "python",
"file_size": 1038,
"cut_index": 513,
"middle_length": 229
} |
),
("field", ArrayField(models.CharField(max_length=10))),
],
options={
"required_db_vendor": "postgresql",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="DateTimeArrayModel",
fields... | )),
("times", ArrayField(models.TimeField())),
],
options={
"required_db_vendor": "postgresql",
},
bases=(models.Model,),
),
migrations.CreateModel(
| auto_created=True,
primary_key=True,
),
),
("datetimes", ArrayField(models.DateTimeField())),
("dates", ArrayField(models.DateField() | {
"filepath": "tests/postgres_tests/migrations/0002_create_test_models.py",
"language": "python",
"file_size": 19467,
"cut_index": 1331,
"middle_length": 229
} |
django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="CharTextArrayIndexModel",
fields=[
(
"id",
mod... | ),
),
("char2", models.CharField(max_length=11, db_index=True)),
(
"text",
django.contrib.postgres.fields.ArrayField(
models.T | ),
),
(
"char",
django.contrib.postgres.fields.ArrayField(
models.CharField(max_length=10), db_index=True, size=100
| {
"filepath": "tests/postgres_tests/array_index_migrations/0001_initial.py",
"language": "python",
"file_size": 1162,
"cut_index": 518,
"middle_length": 229
} |
sys
import unittest
from django.apps import apps
from django.core.management import ManagementUtility
from django.test.utils import captured_stdout
class BashCompletionTests(unittest.TestCase):
"""
Testing the Python level bash completion code.
This requires setting up the environment as if we got passed... | t_str):
"""
Set the environment and the list of command line arguments.
This sets the bash variables $COMP_WORDS and $COMP_CWORD. The former is
an array consisting of the individual words in the current command
line | Down(self):
if self.old_DJANGO_AUTO_COMPLETE:
os.environ["DJANGO_AUTO_COMPLETE"] = self.old_DJANGO_AUTO_COMPLETE
else:
del os.environ["DJANGO_AUTO_COMPLETE"]
def _user_input(self, inpu | {
"filepath": "tests/bash_completion/tests.py",
"language": "python",
"file_size": 3911,
"cut_index": 614,
"middle_length": 229
} |
db import models
class User(models.Model):
username = models.CharField(max_length=12, unique=True)
serial = models.IntegerField()
class UserSite(models.Model):
user = models.ForeignKey(User, models.CASCADE, to_field="username")
data = models.IntegerField()
class UserProfile(models.Model):
user... | to_field="user")
network = models.IntegerField()
identifier = models.IntegerField()
class Place(models.Model):
name = models.CharField(max_length=50)
class Restaurant(Place):
pass
class Manager(models.Model):
restaurant = models. | ,
models.CASCADE,
to_field="username",
primary_key=True,
)
favorite_number = models.IntegerField()
class ProfileNetwork(models.Model):
profile = models.ForeignKey(UserProfile, models.CASCADE, | {
"filepath": "tests/model_formsets_regress/models.py",
"language": "python",
"file_size": 1350,
"cut_index": 524,
"middle_length": 229
} |
rove
# you can create a form with no data
form = Form()
form_set = FormSet(instance=User())
# Now create a new User and UserSite instance
data = {
"serial": "1",
"username": "apollo13",
"usersite_set-TOTAL_FORMS": "1",
"usersite_se... | valid():
form_set.save()
usersite = UserSite.objects.values()
self.assertEqual(usersite[0]["data"], 10)
self.assertEqual(usersite[0]["user_id"], "apollo13")
else:
self.fail("Errors found o | form = Form(data)
if form.is_valid():
user = form.save()
else:
self.fail("Errors found on form:%s" % form_set)
form_set = FormSet(data, instance=user)
if form_set.is_ | {
"filepath": "tests/model_formsets_regress/tests.py",
"language": "python",
"file_size": 21354,
"cut_index": 1331,
"middle_length": 229
} |
Factory()
def setUp(self):
request_started.disconnect(close_old_connections)
self.addCleanup(request_started.connect, close_old_connections)
async def test_get_asgi_application(self):
"""
get_asgi_application() returns a functioning ASGI callable.
"""
applicatio... | self.assertEqual(response_start["status"], 200)
self.assertEqual(
set(response_start["headers"]),
{
(b"Content-Length", b"12"),
(b"Content-Type", b"text/html; charset=utf-8"),
|
await communicator.send_input({"type": "http.request"})
# Read the response.
response_start = await communicator.receive_output()
self.assertEqual(response_start["type"], "http.response.start")
| {
"filepath": "tests/asgi/tests.py",
"language": "python",
"file_size": 43527,
"cut_index": 2151,
"middle_length": 229
} |
eading
import time
from django.http import FileResponse, HttpResponse, StreamingHttpResponse
from django.urls import path
from django.views.decorators.csrf import csrf_exempt
def hello(request):
name = request.GET.get("name") or "World"
return HttpResponse("Hello %s!" % name)
def hello_with_delay(request):... | nc_waiter(request):
with sync_waiter.lock:
sync_waiter.active_threads.add(threading.current_thread())
sync_waiter.barrier.wait(timeout=0.5)
return hello(request)
@csrf_exempt
def post_echo(request):
if request.GET.get("echo"):
| get("HTTP_REFERER") or "",
content_type=request.META.get("CONTENT_TYPE"),
)
def hello_cookie(request):
response = HttpResponse("Hello World!")
response.set_cookie("key", "value")
return response
def sy | {
"filepath": "tests/asgi/urls.py",
"language": "python",
"file_size": 1841,
"cut_index": 537,
"middle_length": 229
} |
th(__file__).parent.absolute()
EXTRA_TEMPLATES_DIR = ROOT / "templates_extra"
@override_settings(
INSTALLED_APPS=["template_tests"],
TEMPLATES=[
{
"BACKEND": "django.template.backends.dummy.TemplateStrings",
"APP_DIRS": True,
},
{
"BACKEND": "django.... | },
},
],
)
class TemplateReloadTests(SimpleTestCase):
@mock.patch("django.template.autoreload.reset_loaders")
def test_template_changed(self, mock_reset):
template_path = Path(__file__).parent / "templates" / "index.ht | ext_processors.request",
],
"loaders": [
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
],
| {
"filepath": "tests/template_tests/test_autoreloader.py",
"language": "python",
"file_size": 6109,
"cut_index": 716,
"middle_length": 229
} |
able, VariableDoesNotExist
from django.template.base import DebugLexer, Lexer, TokenType
from django.test import SimpleTestCase
from django.utils.translation import gettext_lazy
class LexerTestMixin:
template_string = (
"text\n"
"{% if test %}{{ varvalue }}{% endif %}"
"{#comment {{not a v... | kenType.TEXT, "end text", 2, (85, 93)),
]
def test_tokenize(self):
tokens = self.lexer_class(self.template_string).tokenize()
token_tuples = [
(t.token_type, t.contents, t.lineno, t.position) for t in tokens
]
| Type.BLOCK, "if test", 2, (5, 18)),
(TokenType.VAR, "varvalue", 2, (18, 32)),
(TokenType.BLOCK, "endif", 2, (32, 43)),
(TokenType.COMMENT, "comment {{not a var}} {%not a block%}", 2, (43, 85)),
(To | {
"filepath": "tests/template_tests/test_base.py",
"language": "python",
"file_size": 2835,
"cut_index": 563,
"middle_length": 229
} |
cls.engine = Engine()
super().setUpClass()
def test_callable(self):
class Doodad:
def __init__(self, value):
self.num_calls = 0
self.value = value
def __call__(self):
self.num_calls += 1
return {"the_v... | oodad has been called
self.assertEqual(my_doodad.num_calls, 1)
# But we can access keys on the dict that's returned
# by ``__call__``, instead.
t = self.engine.from_string("{{ my_doodad.the_value }}")
self.assertEqu | _call__`` will be invoked first, yielding a dictionary
# without a key ``value``.
t = self.engine.from_string("{{ my_doodad.value }}")
self.assertEqual(t.render(c), "")
# We can confirm that the d | {
"filepath": "tests/template_tests/test_callables.py",
"language": "python",
"file_size": 6218,
"cut_index": 716,
"middle_length": 229
} |
c = Context({"a": 1, "b": "xyzzy"})
self.assertEqual(c["a"], 1)
self.assertEqual(c.push(), {})
c["a"] = 2
self.assertEqual(c["a"], 2)
self.assertEqual(c.get("a"), 2)
self.assertEqual(c.pop(), {"a": 2})
self.assertEqual(c["a"], 1)
self.assertEqual(c.ge... | : 1})
with c.update({}):
c["a"] = 2
self.assertEqual(c["a"], 2)
self.assertEqual(c["a"], 1)
with c.update({"a": 3}):
self.assertEqual(c["a"], 3)
self.assertEqual(c["a"], 1)
def test_ | ssertEqual(c["a"], 2)
self.assertEqual(c["a"], 1)
with c.push(a=3):
self.assertEqual(c["a"], 3)
self.assertEqual(c["a"], 1)
def test_update_context_manager(self):
c = Context({"a" | {
"filepath": "tests/template_tests/test_context.py",
"language": "python",
"file_size": 9878,
"cut_index": 921,
"middle_length": 229
} |
ed result"),
("{% load custom %}{% one_param 37 %}", "one_param - Expected result: 37"),
(
"{% load custom %}{% explicit_no_context 37 %}",
"explicit_no_context - Expected result: 37",
),
(
"{% load custom %}{% no_params_wit... | 42",
),
(
"{% load custom %}{% simple_keyword_only_param kwarg=37 %}",
"simple_keyword_only_param - Expected result: 37",
),
(
"{% load custom %}{% simple_keywo | "params_and_context - Expected result (context value: 42): 37",
),
(
"{% load custom %}{% simple_two_params 37 42 %}",
"simple_two_params - Expected result: 37, | {
"filepath": "tests/template_tests/test_custom.py",
"language": "python",
"file_size": 37895,
"cut_index": 2151,
"middle_length": 229
} |
from django.template.engine import Engine
from django.test import SimpleTestCase, override_settings
from .utils import ROOT, TEMPLATE_DIR
OTHER_DIR = os.path.join(ROOT, "other_templates")
class EngineTest(SimpleTestCase):
def test_repr_empty(self):
engine = Engine()
self.assertEqual(
... | def test_repr(self):
engine = Engine(
dirs=[TEMPLATE_DIR],
context_processors=["django.template.context_processors.debug"],
debug=True,
loaders=["django.template.loaders.filesystem.Loader"],
| ] "
"string_if_invalid='' file_charset='utf-8' builtins=["
"'django.template.defaulttags', 'django.template.defaultfilters', "
"'django.template.loader_tags'] autoescape=True>",
)
| {
"filepath": "tests/template_tests/test_engine.py",
"language": "python",
"file_size": 5050,
"cut_index": 614,
"middle_length": 229
} |
cursive_templates")
class ExtendsBehaviorTests(SimpleTestCase):
def test_normal_extend(self):
engine = Engine(dirs=[os.path.join(RECURSIVE, "fs")])
template = engine.get_template("one.html")
output = template.render(Context({}))
self.assertEqual(output.strip(), "three two one")
... | /recursive")
def test_extend_missing(self):
engine = Engine(dirs=[os.path.join(RECURSIVE, "fs")])
template = engine.get_template("extend-missing.html")
with self.assertRaises(TemplateDoesNotExist) as e:
template.ren | .path.join(RECURSIVE, "fs3"),
]
)
template = engine.get_template("recursive.html")
output = template.render(Context({}))
self.assertEqual(output.strip(), "fs3/recursive fs2/recursive fs | {
"filepath": "tests/template_tests/test_extends.py",
"language": "python",
"file_size": 7707,
"cut_index": 716,
"middle_length": 229
} |
mpleTestCase
from .utils import ROOT
RELATIVE = os.path.join(ROOT, "relative_templates")
class ExtendsRelativeBehaviorTests(SimpleTestCase):
def test_normal_extend(self):
engine = Engine(dirs=[RELATIVE])
template = engine.get_template("one.html")
output = template.render(Context({}))
... | t_template("dir1/one.html")
output = template.render(Context({}))
self.assertEqual(output.strip(), "three two one dir1 one")
def test_dir1_extend1(self):
engine = Engine(dirs=[RELATIVE])
template = engine.get_template(" | ")
output = template.render(Context({"tmpl": "./two.html"}))
self.assertEqual(output.strip(), "three two one")
def test_dir1_extend(self):
engine = Engine(dirs=[RELATIVE])
template = engine.ge | {
"filepath": "tests/template_tests/test_extends_relative.py",
"language": "python",
"file_size": 4455,
"cut_index": 614,
"middle_length": 229
} |
strationTests(SimpleTestCase):
def setUp(self):
self.library = Library()
def test_filter(self):
@self.library.filter
def func():
return ""
self.assertEqual(self.library.filters["func"], func)
def test_filter_parens(self):
@self.library.filter()
... | l(self.library.filters["name"], func)
def test_filter_call(self):
def func():
return ""
self.library.filter("name", func)
self.assertEqual(self.library.filters["name"], func)
def test_filter_invalid(self):
| return ""
self.assertEqual(self.library.filters["name"], func)
def test_filter_name_kwarg(self):
@self.library.filter(name="name")
def func():
return ""
self.assertEqua | {
"filepath": "tests/template_tests/test_library.py",
"language": "python",
"file_size": 6673,
"cut_index": 716,
"middle_length": 229
} |
Engine(
dirs=[TEMPLATE_DIR],
loaders=[
(
"django.template.loaders.cached.Loader",
[
"django.template.loaders.filesystem.Loader",
],
),
],
)
def test_get_te... | self.assertEqual(cache["index.html"], template)
# Run a second time from cache
template = self.engine.get_template("index.html")
self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, "index.html"))
self.assertE | te.origin.template_name, "index.html")
self.assertEqual(
template.origin.loader, self.engine.template_loaders[0].loaders[0]
)
cache = self.engine.template_loaders[0].get_template_cache
| {
"filepath": "tests/template_tests/test_loaders.py",
"language": "python",
"file_size": 10643,
"cut_index": 921,
"middle_length": 229
} |
import (
LinearRing,
LineString,
MultiPoint,
Point,
Polygon,
fromstr,
)
from django.test import SimpleTestCase
def api_get_distance(x):
return x.distance(Point(-200, -200))
def api_get_buffer(x):
return x.buffer(10)
def api_get_geom_typeid(x):
return x.geom_typeid
def api_get... | et_area(x):
return x.area
def api_get_length(x):
return x.length
geos_function_tests = [
val
for name, val in vars().items()
if hasattr(val, "__call__") and name.startswith("api_get_")
]
class GEOSMutationTest(SimpleTestCase):
| ple(x):
return x.simple
def api_get_ring(x):
return x.ring
def api_get_boundary(x):
return x.boundary
def api_get_convex_hull(x):
return x.convex_hull
def api_get_extent(x):
return x.extent
def api_g | {
"filepath": "tests/gis_tests/geos_tests/test_geos_mutation.py",
"language": "python",
"file_size": 6942,
"cut_index": 716,
"middle_length": 229
} |
self._list = self._mytype(i_list)
super().__init__(*args, **kwargs)
def __len__(self):
return len(self._list)
def __str__(self):
return str(self._list)
def __repr__(self):
return repr(self._list)
def _set_list(self, length, items):
# this would work:
... | list[index] = value
def nextRange(length):
nextRange.start += 100
return range(nextRange.start, nextRange.start + length)
nextRange.start = 0
class ListMixinTest(SimpleTestCase):
"""
Tests base class ListMixin by comparing a list clon | v
self._list = self._mytype(itemList)
def _get_single_external(self, index):
return self._list[index]
class UserListB(UserListA):
_mytype = list
def _set_single(self, index, value):
self._ | {
"filepath": "tests/gis_tests/geos_tests/test_mutable_list.py",
"language": "python",
"file_size": 17120,
"cut_index": 921,
"middle_length": 229
} |
o.db import migrations
from django.db.models import deletion
class Migration(migrations.Migration):
dependencies = [
("rasterapp", "0001_setup_extensions"),
]
operations = [
migrations.CreateModel(
name="RasterModel",
fields=[
(
... |
srid=4326,
verbose_name="A Verbose Raster Name",
),
),
(
"rastprojected",
models.fields.RasterField(
| verbose_name="ID",
),
),
(
"rast",
models.fields.RasterField(
blank=True,
null=True, | {
"filepath": "tests/gis_tests/rasterapp/migrations/0002_rastermodels.py",
"language": "python",
"file_size": 2165,
"cut_index": 563,
"middle_length": 229
} |
ture, skipUnlessDBFeature
try:
GeometryColumns = connection.ops.geometry_columns()
HAS_GEOMETRY_COLUMNS = True
except NotImplementedError:
HAS_GEOMETRY_COLUMNS = False
class OperationTestCase(TransactionTestCase):
available_apps = ["gis_tests.gis_migrations"]
get_opclass_query = """
SELEC... | )
super().tearDown()
@property
def has_spatial_indexes(self):
if connection.ops.mysql:
with connection.cursor() as cursor:
return connection.introspection.supports_spatial_index(
cur | ef tearDown(self):
# Delete table after testing
if hasattr(self, "current_state"):
self.apply_operations(
"gis", self.current_state, [migrations.DeleteModel("Neighborhood")]
| {
"filepath": "tests/gis_tests/gis_migrations/test_operations.py",
"language": "python",
"file_size": 16269,
"cut_index": 921,
"middle_length": 229
} |
in any serializable format (including JSON and XML). Fixtures
are identified by name, and are stored in either a directory named 'fixtures'
in the application directory, or in one of the directories named in the
``FIXTURE_DIRS`` setting.
"""
import uuid
from django.contrib.auth.models import Permission
from django.c... | gth=100, default="Default headline")
pub_date = models.DateTimeField()
class Meta:
ordering = ("-pub_date", "headline")
def __str__(self):
return self.headline
class Blog(models.Model):
name = models.CharField(max_length | harField(max_length=100)
description = models.TextField()
class Meta:
ordering = ("title",)
def __str__(self):
return self.title
class Article(models.Model):
headline = models.CharField(max_len | {
"filepath": "tests/fixtures/models.py",
"language": "python",
"file_size": 4480,
"cut_index": 614,
"middle_length": 229
} |
= []
def test_class_fixtures(self):
"There were no fixture objects installed"
self.assertEqual(Article.objects.count(), 0)
class DumpDataAssertMixin:
def _dumpdata_assert(
self,
args,
output,
format="json",
filename=None,
natural_foreign_keys=F... | ,
use_natural_foreign_keys=natural_foreign_keys,
use_natural_primary_keys=natural_primary_keys,
use_base_manager=use_base_manager,
exclude=exclude_list,
primary_keys=primary_keys,
)
| s.path.join(tempfile.gettempdir(), filename)
management.call_command(
"dumpdata",
*args,
format=format,
stdout=new_io,
stderr=new_io,
output=filename | {
"filepath": "tests/fixtures/tests.py",
"language": "python",
"file_size": 59386,
"cut_index": 2151,
"middle_length": 229
} |
ACHES={
"default": {
"BACKEND": "django.core.cache.backends.dummy.DummyCache",
}
}
)
class AsyncDummyCacheTests(SimpleTestCase):
async def test_simple(self):
"""Dummy cache backend ignores cache set calls."""
await cache.aset("key", "value")
self.assertIsNone(... | f.assertIsNone(await cache.aget("does_not_exist"))
self.assertEqual(await cache.aget("does_not_exist", "default"), "default")
async def test_aget_many(self):
"""aget_many() returns nothing for the dummy cache backend."""
await | f.assertIs(await cache.aadd("key", "new_value"), True)
self.assertIsNone(await cache.aget("key"))
async def test_non_existent(self):
"""Nonexistent keys aren't found in the dummy cache backend."""
sel | {
"filepath": "tests/cache/tests_async.py",
"language": "python",
"file_size": 7331,
"cut_index": 716,
"middle_length": 229
} |
ettings
from django.utils import translation
from .models import Album, Band, ReleaseEvent, VideoStream
class AlbumForm(forms.ModelForm):
class Meta:
model = Album
fields = ["band", "featuring"]
widgets = {
"band": AutocompleteSelect(
Album._meta.get_field("ban... | band").remote_field, admin.site
),
required=False,
)
class RequiredBandForm(forms.Form):
band = ModelChoiceField(
queryset=Album.objects.all(),
widget=AutocompleteSelect(
Album._meta.get_field("band").r | admin.site,
),
}
class NotRequiredBandForm(forms.Form):
band = ModelChoiceField(
queryset=Album.objects.all(),
widget=AutocompleteSelect(
Album._meta.get_field(" | {
"filepath": "tests/admin_widgets/test_autocomplete_widget.py",
"language": "python",
"file_size": 7070,
"cut_index": 716,
"middle_length": 229
} |
ield(Event, "link", widgets.AdminURLFieldWidget)
def test_IntegerField(self):
self.assertFormfield(Event, "min_age", widgets.AdminIntegerFieldWidget)
def test_CharField(self):
self.assertFormfield(Member, "name", widgets.AdminTextInputWidget)
def test_EmailField(self):
self.assert... | raw_id_fields=["main_band"],
)
def test_radio_fields_ForeignKey(self):
ff = self.assertFormfield(
Event,
"main_band",
widgets.AdminRadioSelect,
radio_fields={"main_band": admin.VERTI | ):
self.assertFormfield(Event, "main_band", forms.Select)
def test_raw_id_ForeignKey(self):
self.assertFormfield(
Event,
"main_band",
widgets.ForeignKeyRawIdWidget,
| {
"filepath": "tests/admin_widgets/tests.py",
"language": "python",
"file_size": 85744,
"cut_index": 3790,
"middle_length": 229
} |
.receivers),
)
def tearDown(self):
# All our signals got disconnected properly.
post_signals = (
len(signals.pre_save.receivers),
len(signals.post_save.receivers),
len(signals.pre_delete.receivers),
len(signals.post_delete.receivers),
... | signals.post_init.connect(post_init_callback)
p1 = Person(first_name="John", last_name="Doe")
self.assertEqual(data, [{}, p1])
def test_save_signals(self):
data = []
def pre_save_handler(signal, sender, instan | nit_callback(sender, args, **kwargs):
data.append(kwargs["kwargs"])
signals.pre_init.connect(pre_init_callback)
def post_init_callback(sender, instance, **kwargs):
data.append(instance)
| {
"filepath": "tests/signals/tests.py",
"language": "python",
"file_size": 29653,
"cut_index": 1331,
"middle_length": 229
} |
h are a way of specifying common
information inherited by the subclasses. They don't exist as a separate
model.
- non-abstract base classes (the default), which are models in their own
right with their own database tables and everything. Their subclasses
have references back to them, created... | b = models.CharField(max_length=50)
class Student(CommonInfo):
school_class = models.CharField(max_length=10)
class Meta:
pass
#
# Abstract base classes with related models
#
class Post(models.Model):
title = models.CharField(max | age = models.PositiveIntegerField()
class Meta:
abstract = True
ordering = ["name"]
def __str__(self):
return "%s %s" % (self.__class__.__name__, self.name)
class Worker(CommonInfo):
jo | {
"filepath": "tests/model_inheritance/models.py",
"language": "python",
"file_size": 4830,
"cut_index": 614,
"middle_length": 229
} |
he __str__() method, just as with normal Python
# subclassing. This is useful if you want to factor out common
# information for programming purposes, but still completely
# independent separate models at the database level.
w1 = Worker.objects.create(name="Fred", age=35, job="Quarry wor... | .objects.values("name"),
[
{"name": "Barney"},
{"name": "Fred"},
],
)
# Since Student does not subclass CommonInfo's Meta, it has the effect
# of completely overriding it. So | "Worker Fred")
self.assertEqual(str(s), "Student Pebbles")
# The children inherit the Meta class of their parents (if they don't
# specify their own).
self.assertSequenceEqual(
Worker | {
"filepath": "tests/model_inheritance/tests.py",
"language": "python",
"file_size": 24537,
"cut_index": 1331,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.