hash
stringlengths
64
64
content
stringlengths
0
1.51M
cd4ddae1cf4a576c94809930893ac7b277c232d546551bdd53a7532c4ad19553
import json from django.contrib.gis.geos import LinearRing, Point, Polygon from django.core import serializers 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(serializers.get_serializer_formats()) public_formats = set(serializers.get_public_serializer_formats()) self.assertIn("geojson", all_formats), self.assertIn("geojson", public_formats) def test_serialization_base(self): geojson = serializers.serialize("geojson", City.objects.order_by("name")) geodata = json.loads(geojson) self.assertEqual(len(geodata["features"]), len(City.objects.all())) self.assertEqual(geodata["features"][0]["geometry"]["type"], "Point") self.assertEqual(geodata["features"][0]["properties"]["name"], "Chicago") first_city = City.objects.order_by("name").first() self.assertEqual(geodata["features"][0]["properties"]["pk"], str(first_city.pk)) def test_geometry_field_option(self): """ When a model has several geometry fields, the 'geometry_field' option can be used to specify the field to use as the 'geometry' key. """ MultiFields.objects.create( city=City.objects.first(), name="Name", point=Point(5, 23), poly=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))), ) geojson = serializers.serialize("geojson", MultiFields.objects.all()) geodata = json.loads(geojson) self.assertEqual(geodata["features"][0]["geometry"]["type"], "Point") geojson = serializers.serialize( "geojson", MultiFields.objects.all(), geometry_field="poly" ) geodata = json.loads(geojson) self.assertEqual(geodata["features"][0]["geometry"]["type"], "Polygon") # geometry_field is considered even if not in fields (#26138). geojson = serializers.serialize( "geojson", MultiFields.objects.all(), geometry_field="poly", fields=("city",), ) geodata = json.loads(geojson) self.assertEqual(geodata["features"][0]["geometry"]["type"], "Polygon") def test_fields_option(self): """ The fields option allows to define a subset of fields to be present in the 'properties' of the generated output. """ PennsylvaniaCity.objects.create( name="Mansfield", county="Tioga", point="POINT(-77.071445 41.823881)" ) geojson = serializers.serialize( "geojson", PennsylvaniaCity.objects.all(), fields=("county", "point"), ) geodata = json.loads(geojson) self.assertIn("county", geodata["features"][0]["properties"]) self.assertNotIn("founded", geodata["features"][0]["properties"]) self.assertNotIn("pk", geodata["features"][0]["properties"]) def test_srid_option(self): geojson = serializers.serialize( "geojson", City.objects.order_by("name"), srid=2847 ) geodata = json.loads(geojson) coordinates = geodata["features"][0]["geometry"]["coordinates"] # Different PROJ versions use different transformations, all are # correct as having a 1 meter accuracy. self.assertAlmostEqual(coordinates[0], 1564802, -1) self.assertAlmostEqual(coordinates[1], 5613214, -1) def test_deserialization_exception(self): """ GeoJSON cannot be deserialized. """ with self.assertRaises(serializers.base.SerializerDoesNotExist): serializers.deserialize("geojson", "{}")
7f69d6947503b577a0e2980d87e9c997486dcd5d3fc66bdf6f2a733e8705fc4a
from django.contrib.gis.db import models from django.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 connection.cursor() as cursor: constraints = connection.introspection.get_constraints(cursor, table) return { name: constraint["columns"] for name, constraint in constraints.items() if constraint["index"] } def has_spatial_indexes(self, table): if connection.ops.mysql: with connection.cursor() as cursor: 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 return True def test_using_sql(self): if not connection.ops.postgis: self.skipTest("This is a PostGIS-specific test.") index = Index(fields=["point"]) editor = connection.schema_editor() self.assertIn( "%s USING " % editor.quote_name(City._meta.db_table), str(index.create_sql(City, editor)), ) @isolate_apps("gis_tests.geoapp") def test_namespaced_db_table(self): if not connection.ops.postgis: self.skipTest("PostGIS-specific test.") class SchemaCity(models.Model): point = models.PointField() class Meta: app_label = "geoapp" db_table = 'django_schema"."geoapp_schema_city' index = Index(fields=["point"]) editor = connection.schema_editor() create_index_sql = str(index.create_sql(SchemaCity, editor)) self.assertIn( "%s USING " % editor.quote_name(SchemaCity._meta.db_table), create_index_sql, ) self.assertIn( 'CREATE INDEX "geoapp_schema_city_point_9ed70651_id" ', create_index_sql, ) def test_index_name(self): if not self.has_spatial_indexes(City._meta.db_table): self.skipTest("Spatial indexes in Meta.indexes are not supported.") index_name = "custom_point_index_name" index = Index(fields=["point"], name=index_name) with connection.schema_editor() as editor: editor.add_index(City, index) indexes = self.get_indexes(City._meta.db_table) self.assertIn(index_name, indexes) self.assertEqual(indexes[index_name], ["point"]) editor.remove_index(City, index)
323a0ad8d1be76d2a064e61495919208f64b8fc88df58adbe322444f82de99b1
from 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.feed, {"feed_dict": feed_dict}), ] urlpatterns += [ path("sitemaps/<section>.xml", sitemap_views.sitemap, {"sitemaps": sitemaps}), ] urlpatterns += [ path( "sitemaps/kml/<label>/<model>/<field_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", ), ]
589a69db1b72ea1a2da1f88b2957b45e0c19b12bfc79e2c2aa150a21e0747313
from datetime import datetime from django.contrib.gis.db.models import Extent from django.contrib.gis.shortcuts import render_to_kmz from django.db.models import Count, Min from django.test import TestCase, skipUnlessDBFeature from .models import City, PennsylvaniaCity, State, Truth class GeoRegressionTests(TestCase): fixtures = ["initial"] def test_update(self): "Testing QuerySet.update() (#10411)." pueblo = City.objects.get(name="Pueblo") bak = pueblo.point.clone() pueblo.point.y += 0.005 pueblo.point.x += 0.005 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, 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 `render_to_kmz` with non-ASCII data. See #11624." name = "Åland Islands" places = [ { "name": name, "description": name, "kml": "<Point><coordinates>5.0,23.0</coordinates></Point>", } ] render_to_kmz("gis/kml/placemarks.kml", {"places": places}) @skipUnlessDBFeature("supports_extent_aggr") def test_extent(self): "Testing `extent` on a table with a single point. See #11827." pnt = City.objects.get(name="Pueblo").point ref_ext = (pnt.x, pnt.y, pnt.x, pnt.y) extent = City.objects.filter(name="Pueblo").aggregate(Extent("point"))[ "point__extent" ] for ref_val, val in zip(ref_ext, extent): self.assertAlmostEqual(ref_val, val, 4) def test_unicode_date(self): "Testing dates are converted properly, even on SpatiaLite. See #16408." founded = datetime(1857, 5, 23) PennsylvaniaCity.objects.create( name="Mansfield", county="Tioga", point="POINT(-77.071445 41.823881)", founded=founded, ) self.assertEqual( founded, PennsylvaniaCity.objects.datetimes("founded", "day")[0] ) self.assertEqual( founded, PennsylvaniaCity.objects.aggregate(Min("founded"))["founded__min"] ) def test_empty_count(self): "Testing that PostGISAdapter.__eq__ does check empty strings. See #13670." # contrived example, but need a geo lookup paired with an id__in lookup pueblo = City.objects.get(name="Pueblo") state = State.objects.filter(poly__contains=pueblo.point) cities_within_state = City.objects.filter(id__in=state) # .count() should not throw TypeError in __eq__ self.assertEqual(cities_within_state.count(), 1) @skipUnlessDBFeature("allows_group_by_lob") def test_defer_or_only_with_annotate(self): "Regression for #16409. Make sure defer() and only() work with annotate()" self.assertIsInstance( list(City.objects.annotate(Count("point")).defer("name")), list ) self.assertIsInstance( list(City.objects.annotate(Count("point")).only("name")), list ) def test_boolean_conversion(self): "Testing Boolean value conversion with the spatial backend, see #15169." t1 = Truth.objects.create(val=True) t2 = Truth.objects.create(val=False) val1 = Truth.objects.get(pk=t1.pk).val val2 = Truth.objects.get(pk=t2.pk).val # verify types -- shouldn't be 0/1 self.assertIsInstance(val1, bool) self.assertIsInstance(val2, bool) # verify values self.assertIs(val1, True) self.assertIs(val2, False)
a23f065c3943fe9fb869f4884210c1d6c1d4a34d86db20085375d24ff3f3c9bb
import zipfile from io import BytesIO from xml.dom 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_settings(ROOT_URLCONF="gis_tests.geoapp.urls") class GeoSitemapTest(TestCase): @classmethod def setUpTestData(cls): Site(id=settings.SITE_ID, domain="example.com", name="example.com").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) 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 ) # Ensuring the right sitemaps namespace is present. urlset = doc.firstChild self.assertEqual( urlset.getAttribute("xmlns"), "http://www.sitemaps.org/schemas/sitemap/0.9", ) urls = urlset.getElementsByTagName("url") self.assertEqual(2, len(urls)) # Should only be 2 sitemaps. for url in urls: self.assertChildNodes(url, ["loc"]) # Getting the relative URL since we don't have a real site. kml_url = ( url.getElementsByTagName("loc")[0] .childNodes[0] .data.split("http://example.com")[1] ) if kml_type == "kml": kml_doc = minidom.parseString(self.client.get(kml_url).content) elif kml_type == "kmz": # Have to decompress KMZ before parsing. buf = BytesIO(self.client.get(kml_url).content) with zipfile.ZipFile(buf) as zf: self.assertEqual(1, len(zf.filelist)) self.assertEqual("doc.kml", zf.filelist[0].filename) kml_doc = minidom.parseString(zf.read("doc.kml")) # Ensuring the correct number of placemarks are in the KML doc. if "city" in kml_url: model = City elif "country" in kml_url: model = Country self.assertEqual( model.objects.count(), len(kml_doc.getElementsByTagName("Placemark")), )
a9c57ea791635156a1df3a45760efd5a9e3c61e00e8179a79a99318e68d7f5d9
""" Tests for geography support in PostGIS """ import os from django.contrib.gis.db import models from django.contrib.gis.db.models.functions import Area, Distance from django.contrib.gis.measure import D from django.db import NotSupportedError, connection from django.db.models.functions import Cast from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from ..utils import FuncTestMixin from .models import City, County, Zipcode class GeographyTest(TestCase): fixtures = ["initial"] def test01_fixture_load(self): "Ensure geography features loaded properly." 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 geography 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) ) cities2 = list( City.objects.filter(point__dwithin=(z.poly, D(mi=500))) .order_by("name") .values_list("name", flat=True) ) for cities in [cities1, cities2]: self.assertEqual(["Dallas", "Houston", "Oklahoma City"], cities) def test04_invalid_operators_functions(self): """ Exceptions are raised for operators & functions invalid on geography fields. """ if not connection.ops.postgis: self.skipTest("This is a PostGIS-specific test.") # Only a subset of the geometry functions & operator are available # to PostGIS geography types. For more information, visit: # http://postgis.refractions.net/documentation/manual-1.5/ch08.html#PostGIS_GeographyFunctions z = Zipcode.objects.get(code="77002") # ST_Within not available. with self.assertRaises(ValueError): City.objects.filter(point__within=z.poly).count() # `@` operator not available. with self.assertRaises(ValueError): City.objects.filter(point__contained=z.poly).count() # Regression test for #14060, `~=` was never really implemented for PostGIS. htown = City.objects.get(name="Houston") with self.assertRaises(ValueError): City.objects.get(point__exact=htown.point) def test05_geography_layermapping(self): "Testing LayerMapping support on models with geography fields." # There is a similar test in `layermap` that uses the same data set, # but the County model here is a bit different. from django.contrib.gis.utils import LayerMapping # Getting the shapefile and mapping dictionary. shp_path = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "data") ) co_shp = os.path.join(shp_path, "counties", "counties.shp") co_mapping = { "name": "Name", "state": "State", "mpoly": "MULTIPOLYGON", } # Reference county names, number of polygons, and state names. names = ["Bexar", "Galveston", "Harris", "Honolulu", "Pueblo"] num_polys = [1, 2, 1, 19, 1] # Number of polygons for each. st_names = ["Texas", "Texas", "Texas", "Hawaii", "Colorado"] lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269, unique="name") lm.save(silent=True, strict=True) for c, name, num_poly, state in zip( County.objects.order_by("name"), names, num_polys, st_names ): self.assertEqual(4326, c.mpoly.srid) self.assertEqual(num_poly, len(c.mpoly)) self.assertEqual(name, c.name) self.assertEqual(state, c.state) class GeographyFunctionTests(FuncTestMixin, TestCase): fixtures = ["initial"] @skipUnlessDBFeature("supports_extent_aggr") def test_cast_aggregate(self): """ Cast a geography to a geometry field for an aggregate function that expects a geometry input. """ if not connection.features.supports_geography: self.skipTest("This test needs geography support") expected = ( -96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820, ) res = City.objects.filter(name__in=("Houston", "Dallas")).aggregate( extent=models.Extent(Cast("point", models.PointField())) ) for val, exp in zip(res["extent"], expected): self.assertAlmostEqual(exp, val, 4) @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic") def test_distance_function(self): """ Testing Distance() support on non-point geography fields. """ if connection.ops.oracle: ref_dists = [0, 4899.68, 8081.30, 9115.15] elif connection.ops.spatialite: if connection.ops.spatial_version < (5,): # SpatiaLite < 5 returns non-zero distance for polygons and points # covered by that polygon. ref_dists = [326.61, 4899.68, 8081.30, 9115.15] else: ref_dists = [0, 4899.68, 8081.30, 9115.15] else: ref_dists = [0, 4891.20, 8071.64, 9123.95] htown = City.objects.get(name="Houston") qs = Zipcode.objects.annotate( distance=Distance("poly", htown.point), distance2=Distance(htown.point, "poly"), ) for z, ref in zip(qs, ref_dists): self.assertAlmostEqual(z.distance.m, ref, 2) if connection.ops.postgis: # PostGIS casts geography to geometry when distance2 is calculated. ref_dists = [0, 4899.68, 8081.30, 9115.15] for z, ref in zip(qs, ref_dists): self.assertAlmostEqual(z.distance2.m, ref, 2) if not connection.ops.spatialite: # Distance function combined with a lookup. hzip = Zipcode.objects.get(code="77002") self.assertEqual(qs.get(distance__lte=0), hzip) @skipUnlessDBFeature("has_Area_function", "supports_area_geodetic") def test_geography_area(self): """ Testing that Area calculations work on geography columns. """ # SELECT ST_Area(poly) FROM geogapp_zipcode WHERE code='77002'; z = Zipcode.objects.annotate(area=Area("poly")).get(code="77002") # Round to the nearest thousand as possible values (depending on # the database and geolib) include 5439084, 5439100, 5439101. rounded_value = z.area.sq_m rounded_value -= z.area.sq_m % 1000 self.assertEqual(rounded_value, 5439000) @skipUnlessDBFeature("has_Area_function") @skipIfDBFeature("supports_area_geodetic") def test_geodetic_area_raises_if_not_supported(self): with self.assertRaisesMessage( NotSupportedError, "Area on geodetic coordinate systems not supported." ): Zipcode.objects.annotate(area=Area("poly")).get(code="77002")
a7e4036ad9d1152a8d63d7ddfef8bff37813189497b3d3cf5b9288c3ee9c8f87
from django.contrib.gis.db import models class NamedModel(models.Model): name = models.CharField(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 Zipcode(NamedModel): code = models.CharField(max_length=10) poly = models.PolygonField(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([self.name, self.state])
f8a4736676ee1427387b2d221babe0e9e3b047b32a75f4f82dfbbf486158067b
from django.contrib.gis import admin from django.contrib.gis.geos import Point from django.test import SimpleTestCase, ignore_warnings, override_settings from django.utils.deprecation import RemovedInDjango50Warning from .admin import UnmodifiableAdmin from .models import City, site @ignore_warnings(category=RemovedInDjango50Warning) @override_settings(ROOT_URLCONF="django.contrib.gis.tests.geoadmin.urls") class GeoAdminTest(SimpleTestCase): def test_ensure_geographic_media(self): geoadmin = site._registry[City] admin_js = geoadmin.media.render_js() self.assertTrue(any(geoadmin.openlayers_url in js for js in admin_js)) def test_olmap_OSM_rendering(self): delete_all_btn = ( '<a href="javascript:geodjango_point.clearFeatures()">Delete all Features' "</a>" ) original_geoadmin = site._registry[City] params = original_geoadmin.get_map_widget(City._meta.get_field("point")).params result = original_geoadmin.get_map_widget( City._meta.get_field("point") )().render("point", Point(-79.460734, 40.18476), params) self.assertIn( "geodjango_point.layers.base = " 'new OpenLayers.Layer.OSM("OpenStreetMap (Mapnik)");', result, ) self.assertIn(delete_all_btn, result) site.unregister(City) site.register(City, UnmodifiableAdmin) try: geoadmin = site._registry[City] params = geoadmin.get_map_widget(City._meta.get_field("point")).params result = geoadmin.get_map_widget(City._meta.get_field("point"))().render( "point", Point(-79.460734, 40.18476), params ) self.assertNotIn(delete_all_btn, result) finally: site.unregister(City) site.register(City, original_geoadmin.__class__) def test_olmap_WMS_rendering(self): geoadmin = admin.GeoModelAdmin(City, site) result = geoadmin.get_map_widget(City._meta.get_field("point"))().render( "point", Point(-79.460734, 40.18476) ) self.assertIn( 'geodjango_point.layers.base = new OpenLayers.Layer.WMS("OpenLayers WMS", ' '"http://vmap0.tiles.osgeo.org/wms/vmap0", ' "{layers: 'basic', format: 'image/jpeg'});", result, ) def test_olwidget_has_changed(self): """ Changes are accurately noticed by OpenLayersWidget. """ geoadmin = site._registry[City] form = geoadmin.get_changelist_form(None)() has_changed = form.fields["point"].has_changed initial = Point(13.4197458572965953, 52.5194108501149799, srid=4326) data_same = "SRID=3857;POINT(1493879.2754093995 6894592.019687599)" data_almost_same = "SRID=3857;POINT(1493879.2754093990 6894592.019687590)" data_changed = "SRID=3857;POINT(1493884.0527237 6894593.8111804)" self.assertTrue(has_changed(None, data_changed)) self.assertTrue(has_changed(initial, "")) self.assertFalse(has_changed(None, "")) self.assertFalse(has_changed(initial, data_same)) self.assertFalse(has_changed(initial, data_almost_same)) self.assertTrue(has_changed(initial, data_changed)) def test_olwidget_empty_string(self): geoadmin = site._registry[City] form = geoadmin.get_changelist_form(None)({"point": ""}) with self.assertNoLogs("django.contrib.gis", "ERROR"): output = str(form["point"]) self.assertInHTML( '<textarea id="id_point" class="vWKTField required" cols="150"' ' rows="10" name="point"></textarea>', output, ) def test_olwidget_invalid_string(self): geoadmin = site._registry[City] form = geoadmin.get_changelist_form(None)({"point": "INVALID()"}) with self.assertLogs("django.contrib.gis", "ERROR") as cm: output = str(form["point"]) self.assertInHTML( '<textarea id="id_point" class="vWKTField required" cols="150"' ' rows="10" name="point"></textarea>', output, ) self.assertEqual(len(cm.records), 1) self.assertEqual( cm.records[0].getMessage(), "Error creating geometry from value 'INVALID()' (String input " "unrecognized as WKT EWKT, and HEXEWKB.)", ) class DeprecationTests(SimpleTestCase): def test_warning(self): class DeprecatedOSMGeoAdmin(admin.OSMGeoAdmin): pass class DeprecatedGeoModelAdmin(admin.GeoModelAdmin): pass msg = ( "django.contrib.gis.admin.GeoModelAdmin and OSMGeoAdmin are " "deprecated in favor of django.contrib.admin.ModelAdmin and " "django.contrib.gis.admin.GISModelAdmin." ) with self.assertRaisesMessage(RemovedInDjango50Warning, msg): DeprecatedOSMGeoAdmin(City, site) with self.assertRaisesMessage(RemovedInDjango50Warning, msg): DeprecatedGeoModelAdmin(City, site)
b34c3d8fb1740521b46d7064b36610a472176d12f4cf8510fcf71e2e0d654f1c
from django.contrib.gis.db import models from django.test import ignore_warnings from django.utils.deprecation import RemovedInDjango50Warning from ..admin import admin class City(models.Model): name = models.CharField(max_length=30) point = models.PointField() class Meta: app_label = "geoadmini_deprecated" def __str__(self): return self.name site = admin.AdminSite(name="admin_gis") with ignore_warnings(category=RemovedInDjango50Warning): site.register(City, admin.OSMGeoAdmin)
cf6a87db61f2816df07eeb699bb05ec27872722c0c2c52cdb881fbea00da7ee4
from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", include(admin.site.urls)), ]
ef2991b43fa49fddfcb94ab9adb0077aea8f7ecc93e24f267664ff0ef871b16c
from django.core.management import call_command from 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 cursor: return connection.introspection.get_table_description(cursor, table) def assertTableExists(self, table): with connection.cursor() as cursor: self.assertIn(table, connection.introspection.table_names(cursor)) def assertTableNotExists(self, table): with connection.cursor() as cursor: self.assertNotIn(table, connection.introspection.table_names(cursor)) 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 are renamed resulting in unique constraint failure on geometry_columns (#23030). """ # The right tables exist self.assertTableExists("gis_migrations_neighborhood") self.assertTableExists("gis_migrations_household") self.assertTableExists("gis_migrations_family") if connection.features.supports_raster: self.assertTableExists("gis_migrations_heatmap") # Unmigrate models. call_command("migrate", "gis_migrations", "0001", verbosity=0) # All tables are gone self.assertTableNotExists("gis_migrations_neighborhood") self.assertTableNotExists("gis_migrations_household") self.assertTableNotExists("gis_migrations_family") if connection.features.supports_raster: self.assertTableNotExists("gis_migrations_heatmap") # Even geometry columns metadata try: GeoColumn = connection.ops.geometry_columns() except NotImplementedError: # Not all GIS backends have geometry columns model pass else: qs = GeoColumn.objects.filter( **{ "%s__in" % GeoColumn.table_name_col(): ["gis_neighborhood", "gis_household"] } ) self.assertEqual(qs.count(), 0) # Revert the "unmigration" call_command("migrate", "gis_migrations", verbosity=0)
d14e1cd33be1bf47cd90d9b8f4be0824657b01e45eee6f6938e142f841fd99a2
from unittest import skipUnless from django.contrib.gis.db.models import fields from django.contrib.gis.geos import MultiPolygon, Polygon from django.core.exceptions import ImproperlyConfigured from django.db import connection, migrations, models from django.db.migrations.migration import Migration from django.db.migrations.state import ProjectState from django.test import TransactionTestCase, skipIfDBFeature, 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 = """ SELECT opcname, c.relname FROM pg_opclass AS oc JOIN pg_index as i on oc.oid = ANY(i.indclass) JOIN pg_class as c on c.oid = i.indexrelid WHERE c.relname = %s """ def tearDown(self): # Delete table after testing if hasattr(self, "current_state"): self.apply_operations( "gis", self.current_state, [migrations.DeleteModel("Neighborhood")] ) super().tearDown() @property def has_spatial_indexes(self): if connection.ops.mysql: with connection.cursor() as cursor: return connection.introspection.supports_spatial_index( cursor, "gis_neighborhood" ) return True def get_table_description(self, table): with connection.cursor() as cursor: return connection.introspection.get_table_description(cursor, table) def assertColumnExists(self, table, column): self.assertIn(column, [c.name for c in self.get_table_description(table)]) def assertColumnNotExists(self, table, column): self.assertNotIn(column, [c.name for c in self.get_table_description(table)]) def apply_operations(self, app_label, project_state, operations): migration = Migration("name", app_label) migration.operations = operations with connection.schema_editor() as editor: return migration.apply(project_state, editor) def set_up_test_model(self, force_raster_creation=False): test_fields = [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100, unique=True)), ("geom", fields.MultiPolygonField(srid=4326)), ] if connection.features.supports_raster or force_raster_creation: test_fields += [("rast", fields.RasterField(srid=4326, null=True))] operations = [migrations.CreateModel("Neighborhood", test_fields)] self.current_state = self.apply_operations("gis", ProjectState(), operations) def assertGeometryColumnsCount(self, expected_count): self.assertEqual( GeometryColumns.objects.filter( **{ "%s__iexact" % GeometryColumns.table_name_col(): "gis_neighborhood", } ).count(), expected_count, ) def assertSpatialIndexExists(self, table, column, raster=False): with connection.cursor() as cursor: constraints = connection.introspection.get_constraints(cursor, table) if raster: self.assertTrue( any( "st_convexhull(%s)" % column in c["definition"] for c in constraints.values() if c["definition"] is not None ) ) else: self.assertIn([column], [c["columns"] for c in constraints.values()]) def alter_gis_model( self, migration_class, model_name, field_name, blank=False, field_class=None, field_class_kwargs=None, ): args = [model_name, field_name] if field_class: field_class_kwargs = field_class_kwargs or {"srid": 4326, "blank": blank} args.append(field_class(**field_class_kwargs)) operation = migration_class(*args) old_state = self.current_state.clone() operation.state_forwards("gis", self.current_state) with connection.schema_editor() as editor: operation.database_forwards("gis", editor, old_state, self.current_state) class OperationTests(OperationTestCase): def setUp(self): super().setUp() self.set_up_test_model() def test_add_geom_field(self): """ Test the AddField operation with a geometry-enabled column. """ self.alter_gis_model( migrations.AddField, "Neighborhood", "path", False, fields.LineStringField ) self.assertColumnExists("gis_neighborhood", "path") # Test GeometryColumns when available if HAS_GEOMETRY_COLUMNS: self.assertGeometryColumnsCount(2) # Test spatial indices when available if self.has_spatial_indexes: self.assertSpatialIndexExists("gis_neighborhood", "path") @skipUnless(HAS_GEOMETRY_COLUMNS, "Backend doesn't support GeometryColumns.") def test_geom_col_name(self): self.assertEqual( GeometryColumns.geom_col_name(), "column_name" if connection.ops.oracle else "f_geometry_column", ) @skipUnlessDBFeature("supports_raster") def test_add_raster_field(self): """ Test the AddField operation with a raster-enabled column. """ self.alter_gis_model( migrations.AddField, "Neighborhood", "heatmap", False, fields.RasterField ) self.assertColumnExists("gis_neighborhood", "heatmap") # Test spatial indices when available if self.has_spatial_indexes: self.assertSpatialIndexExists("gis_neighborhood", "heatmap", raster=True) def test_add_blank_geom_field(self): """ Should be able to add a GeometryField with blank=True. """ self.alter_gis_model( migrations.AddField, "Neighborhood", "path", True, fields.LineStringField ) self.assertColumnExists("gis_neighborhood", "path") # Test GeometryColumns when available if HAS_GEOMETRY_COLUMNS: self.assertGeometryColumnsCount(2) # Test spatial indices when available if self.has_spatial_indexes: self.assertSpatialIndexExists("gis_neighborhood", "path") @skipUnlessDBFeature("supports_raster") def test_add_blank_raster_field(self): """ Should be able to add a RasterField with blank=True. """ self.alter_gis_model( migrations.AddField, "Neighborhood", "heatmap", True, fields.RasterField ) self.assertColumnExists("gis_neighborhood", "heatmap") # Test spatial indices when available if self.has_spatial_indexes: self.assertSpatialIndexExists("gis_neighborhood", "heatmap", raster=True) def test_remove_geom_field(self): """ Test the RemoveField operation with a geometry-enabled column. """ self.alter_gis_model(migrations.RemoveField, "Neighborhood", "geom") self.assertColumnNotExists("gis_neighborhood", "geom") # Test GeometryColumns when available if HAS_GEOMETRY_COLUMNS: self.assertGeometryColumnsCount(0) @skipUnlessDBFeature("supports_raster") def test_remove_raster_field(self): """ Test the RemoveField operation with a raster-enabled column. """ self.alter_gis_model(migrations.RemoveField, "Neighborhood", "rast") self.assertColumnNotExists("gis_neighborhood", "rast") def test_create_model_spatial_index(self): if not self.has_spatial_indexes: self.skipTest("No support for Spatial indexes") self.assertSpatialIndexExists("gis_neighborhood", "geom") if connection.features.supports_raster: self.assertSpatialIndexExists("gis_neighborhood", "rast", raster=True) @skipUnlessDBFeature("supports_3d_storage") def test_add_3d_field_opclass(self): if not connection.ops.postgis: self.skipTest("PostGIS-specific test.") self.alter_gis_model( migrations.AddField, "Neighborhood", "point3d", field_class=fields.PointField, field_class_kwargs={"dim": 3}, ) self.assertColumnExists("gis_neighborhood", "point3d") self.assertSpatialIndexExists("gis_neighborhood", "point3d") with connection.cursor() as cursor: index_name = "gis_neighborhood_point3d_113bc868_id" cursor.execute(self.get_opclass_query, [index_name]) self.assertEqual( cursor.fetchall(), [("gist_geometry_ops_nd", index_name)], ) @skipUnlessDBFeature("can_alter_geometry_field", "supports_3d_storage") def test_alter_geom_field_dim(self): Neighborhood = self.current_state.apps.get_model("gis", "Neighborhood") p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) Neighborhood.objects.create(name="TestDim", geom=MultiPolygon(p1, p1)) # Add 3rd dimension. self.alter_gis_model( migrations.AlterField, "Neighborhood", "geom", False, fields.MultiPolygonField, field_class_kwargs={"srid": 4326, "dim": 3}, ) self.assertTrue(Neighborhood.objects.first().geom.hasz) # Rewind to 2 dimensions. self.alter_gis_model( migrations.AlterField, "Neighborhood", "geom", False, fields.MultiPolygonField, field_class_kwargs={"srid": 4326, "dim": 2}, ) self.assertFalse(Neighborhood.objects.first().geom.hasz) @skipUnlessDBFeature( "supports_column_check_constraints", "can_introspect_check_constraints" ) def test_add_check_constraint(self): Neighborhood = self.current_state.apps.get_model("gis", "Neighborhood") poly = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) constraint = models.CheckConstraint( check=models.Q(geom=poly), name="geom_within_constraint", ) Neighborhood._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(Neighborhood, constraint) with connection.cursor() as cursor: constraints = connection.introspection.get_constraints( cursor, Neighborhood._meta.db_table, ) self.assertIn("geom_within_constraint", constraints) @skipIfDBFeature("supports_raster") class NoRasterSupportTests(OperationTestCase): def test_create_raster_model_on_db_without_raster_support(self): msg = "Raster fields require backends with raster support." with self.assertRaisesMessage(ImproperlyConfigured, msg): self.set_up_test_model(force_raster_creation=True) def test_add_raster_field_on_db_without_raster_support(self): msg = "Raster fields require backends with raster support." with self.assertRaisesMessage(ImproperlyConfigured, msg): self.set_up_test_model() self.alter_gis_model( migrations.AddField, "Neighborhood", "heatmap", False, fields.RasterField, )
12cea9ff108f535d03d2d1342273aa6ca189f92e1e3987383720878b78df2dcd
# Copyright (c) 2008-2009 Aryeh Leib Taurog, http://www.aryehleib.com # All rights reserved. # # Modified from original contribution by Aryeh Leib Taurog, which was # released under the New BSD license. import unittest from django.contrib.gis.geos.mutable_list import ListMixin class UserListA(ListMixin): _mytype = tuple def __init__(self, i_list, *args, **kwargs): 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: # self._list = self._mytype(items) # but then we wouldn't be testing length parameter itemList = ["x"] * length for i, v in enumerate(items): itemList[i] = 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._list[index] = value def nextRange(length): nextRange.start += 100 return range(nextRange.start, nextRange.start + length) nextRange.start = 0 class ListMixinTest(unittest.TestCase): """ Tests base class ListMixin by comparing a list clone which is a ListMixin subclass with a real Python list. """ limit = 3 listType = UserListA def lists_of_len(self, length=None): if length is None: length = self.limit pl = list(range(length)) return pl, self.listType(pl) def limits_plus(self, b): return range(-self.limit - b, self.limit + b) def step_range(self): return [*range(-1 - self.limit, 0), *range(1, 1 + self.limit)] def test01_getslice(self): "Slice retrieval" pl, ul = self.lists_of_len() for i in self.limits_plus(1): self.assertEqual(pl[i:], ul[i:], "slice [%d:]" % (i)) self.assertEqual(pl[:i], ul[:i], "slice [:%d]" % (i)) for j in self.limits_plus(1): self.assertEqual(pl[i:j], ul[i:j], "slice [%d:%d]" % (i, j)) for k in self.step_range(): self.assertEqual( pl[i:j:k], ul[i:j:k], "slice [%d:%d:%d]" % (i, j, k) ) for k in self.step_range(): self.assertEqual(pl[i::k], ul[i::k], "slice [%d::%d]" % (i, k)) self.assertEqual(pl[:i:k], ul[:i:k], "slice [:%d:%d]" % (i, k)) for k in self.step_range(): self.assertEqual(pl[::k], ul[::k], "slice [::%d]" % (k)) def test02_setslice(self): "Slice assignment" def setfcn(x, i, j, k, L): x[i:j:k] = range(L) pl, ul = self.lists_of_len() for slen in range(self.limit + 1): ssl = nextRange(slen) ul[:] = ssl pl[:] = ssl self.assertEqual(pl, ul[:], "set slice [:]") for i in self.limits_plus(1): ssl = nextRange(slen) ul[i:] = ssl pl[i:] = ssl self.assertEqual(pl, ul[:], "set slice [%d:]" % (i)) ssl = nextRange(slen) ul[:i] = ssl pl[:i] = ssl self.assertEqual(pl, ul[:], "set slice [:%d]" % (i)) for j in self.limits_plus(1): ssl = nextRange(slen) ul[i:j] = ssl pl[i:j] = ssl self.assertEqual(pl, ul[:], "set slice [%d:%d]" % (i, j)) for k in self.step_range(): ssl = nextRange(len(ul[i:j:k])) ul[i:j:k] = ssl pl[i:j:k] = ssl self.assertEqual(pl, ul[:], "set slice [%d:%d:%d]" % (i, j, k)) sliceLen = len(ul[i:j:k]) with self.assertRaises(ValueError): setfcn(ul, i, j, k, sliceLen + 1) if sliceLen > 2: with self.assertRaises(ValueError): setfcn(ul, i, j, k, sliceLen - 1) for k in self.step_range(): ssl = nextRange(len(ul[i::k])) ul[i::k] = ssl pl[i::k] = ssl self.assertEqual(pl, ul[:], "set slice [%d::%d]" % (i, k)) ssl = nextRange(len(ul[:i:k])) ul[:i:k] = ssl pl[:i:k] = ssl self.assertEqual(pl, ul[:], "set slice [:%d:%d]" % (i, k)) for k in self.step_range(): ssl = nextRange(len(ul[::k])) ul[::k] = ssl pl[::k] = ssl self.assertEqual(pl, ul[:], "set slice [::%d]" % (k)) def test03_delslice(self): "Delete slice" for Len in range(self.limit): pl, ul = self.lists_of_len(Len) del pl[:] del ul[:] self.assertEqual(pl[:], ul[:], "del slice [:]") for i in range(-Len - 1, Len + 1): pl, ul = self.lists_of_len(Len) del pl[i:] del ul[i:] self.assertEqual(pl[:], ul[:], "del slice [%d:]" % (i)) pl, ul = self.lists_of_len(Len) del pl[:i] del ul[:i] self.assertEqual(pl[:], ul[:], "del slice [:%d]" % (i)) for j in range(-Len - 1, Len + 1): pl, ul = self.lists_of_len(Len) del pl[i:j] del ul[i:j] self.assertEqual(pl[:], ul[:], "del slice [%d:%d]" % (i, j)) for k in [*range(-Len - 1, 0), *range(1, Len)]: pl, ul = self.lists_of_len(Len) del pl[i:j:k] del ul[i:j:k] self.assertEqual( pl[:], ul[:], "del slice [%d:%d:%d]" % (i, j, k) ) for k in [*range(-Len - 1, 0), *range(1, Len)]: pl, ul = self.lists_of_len(Len) del pl[:i:k] del ul[:i:k] self.assertEqual(pl[:], ul[:], "del slice [:%d:%d]" % (i, k)) pl, ul = self.lists_of_len(Len) del pl[i::k] del ul[i::k] self.assertEqual(pl[:], ul[:], "del slice [%d::%d]" % (i, k)) for k in [*range(-Len - 1, 0), *range(1, Len)]: pl, ul = self.lists_of_len(Len) del pl[::k] del ul[::k] self.assertEqual(pl[:], ul[:], "del slice [::%d]" % (k)) def test04_get_set_del_single(self): "Get/set/delete single item" pl, ul = self.lists_of_len() for i in self.limits_plus(0): self.assertEqual(pl[i], ul[i], "get single item [%d]" % i) for i in self.limits_plus(0): pl, ul = self.lists_of_len() pl[i] = 100 ul[i] = 100 self.assertEqual(pl[:], ul[:], "set single item [%d]" % i) for i in self.limits_plus(0): pl, ul = self.lists_of_len() del pl[i] del ul[i] self.assertEqual(pl[:], ul[:], "del single item [%d]" % i) def test05_out_of_range_exceptions(self): "Out of range exceptions" def setfcn(x, i): x[i] = 20 def getfcn(x, i): return x[i] def delfcn(x, i): del x[i] pl, ul = self.lists_of_len() for i in (-1 - self.limit, self.limit): with self.assertRaises(IndexError): # 'set index %d' % i) setfcn(ul, i) with self.assertRaises(IndexError): # 'get index %d' % i) getfcn(ul, i) with self.assertRaises(IndexError): # 'del index %d' % i) delfcn(ul, i) def test06_list_methods(self): "List methods" pl, ul = self.lists_of_len() pl.append(40) ul.append(40) self.assertEqual(pl[:], ul[:], "append") pl.extend(range(50, 55)) ul.extend(range(50, 55)) self.assertEqual(pl[:], ul[:], "extend") pl.reverse() ul.reverse() self.assertEqual(pl[:], ul[:], "reverse") for i in self.limits_plus(1): pl, ul = self.lists_of_len() pl.insert(i, 50) ul.insert(i, 50) self.assertEqual(pl[:], ul[:], "insert at %d" % i) for i in self.limits_plus(0): pl, ul = self.lists_of_len() self.assertEqual(pl.pop(i), ul.pop(i), "popped value at %d" % i) self.assertEqual(pl[:], ul[:], "after pop at %d" % i) pl, ul = self.lists_of_len() self.assertEqual(pl.pop(), ul.pop(i), "popped value") self.assertEqual(pl[:], ul[:], "after pop") pl, ul = self.lists_of_len() def popfcn(x, i): x.pop(i) with self.assertRaises(IndexError): popfcn(ul, self.limit) with self.assertRaises(IndexError): popfcn(ul, -1 - self.limit) pl, ul = self.lists_of_len() for val in range(self.limit): self.assertEqual(pl.index(val), ul.index(val), "index of %d" % val) for val in self.limits_plus(2): self.assertEqual(pl.count(val), ul.count(val), "count %d" % val) for val in range(self.limit): pl, ul = self.lists_of_len() pl.remove(val) ul.remove(val) self.assertEqual(pl[:], ul[:], "after remove val %d" % val) def indexfcn(x, v): return x.index(v) def removefcn(x, v): return x.remove(v) with self.assertRaises(ValueError): indexfcn(ul, 40) with self.assertRaises(ValueError): removefcn(ul, 40) def test07_allowed_types(self): "Type-restricted list" pl, ul = self.lists_of_len() ul._allowed = int ul[1] = 50 ul[:2] = [60, 70, 80] def setfcn(x, i, v): x[i] = v with self.assertRaises(TypeError): setfcn(ul, 2, "hello") with self.assertRaises(TypeError): setfcn(ul, slice(0, 3, 2), ("hello", "goodbye")) def test08_min_length(self): "Length limits" pl, ul = self.lists_of_len(5) ul._minlength = 3 def delfcn(x, i): del x[:i] def setfcn(x, i): x[:i] = [] for i in range(len(ul) - ul._minlength + 1, len(ul)): with self.assertRaises(ValueError): delfcn(ul, i) with self.assertRaises(ValueError): setfcn(ul, i) del ul[: len(ul) - ul._minlength] ul._maxlength = 4 for i in range(0, ul._maxlength - len(ul)): ul.append(i) with self.assertRaises(ValueError): ul.append(10) def test09_iterable_check(self): "Error on assigning non-iterable to slice" pl, ul = self.lists_of_len(self.limit + 1) def setfcn(x, i, v): x[i] = v with self.assertRaises(TypeError): setfcn(ul, slice(0, 3, 2), 2) def test10_checkindex(self): "Index check" pl, ul = self.lists_of_len() for i in self.limits_plus(0): if i < 0: self.assertEqual( ul._checkindex(i), i + self.limit, "_checkindex(neg index)" ) else: self.assertEqual(ul._checkindex(i), i, "_checkindex(pos index)") for i in (-self.limit - 1, self.limit): with self.assertRaises(IndexError): ul._checkindex(i) def test_11_sorting(self): "Sorting" pl, ul = self.lists_of_len() pl.insert(0, pl.pop()) ul.insert(0, ul.pop()) pl.sort() ul.sort() self.assertEqual(pl[:], ul[:], "sort") mid = pl[len(pl) // 2] pl.sort(key=lambda x: (mid - x) ** 2) ul.sort(key=lambda x: (mid - x) ** 2) self.assertEqual(pl[:], ul[:], "sort w/ key") pl.insert(0, pl.pop()) ul.insert(0, ul.pop()) pl.sort(reverse=True) ul.sort(reverse=True) self.assertEqual(pl[:], ul[:], "sort w/ reverse") mid = pl[len(pl) // 2] pl.sort(key=lambda x: (mid - x) ** 2) ul.sort(key=lambda x: (mid - x) ** 2) self.assertEqual(pl[:], ul[:], "sort w/ key") def test_12_arithmetic(self): "Arithmetic" pl, ul = self.lists_of_len() al = list(range(10, 14)) self.assertEqual(list(pl + al), list(ul + al), "add") self.assertEqual(type(ul), type(ul + al), "type of add result") self.assertEqual(list(al + pl), list(al + ul), "radd") self.assertEqual(type(al), type(al + ul), "type of radd result") objid = id(ul) pl += al ul += al self.assertEqual(pl[:], ul[:], "in-place add") self.assertEqual(objid, id(ul), "in-place add id") for n in (-1, 0, 1, 3): pl, ul = self.lists_of_len() self.assertEqual(list(pl * n), list(ul * n), "mul by %d" % n) self.assertEqual(type(ul), type(ul * n), "type of mul by %d result" % n) self.assertEqual(list(n * pl), list(n * ul), "rmul by %d" % n) self.assertEqual(type(ul), type(n * ul), "type of rmul by %d result" % n) objid = id(ul) pl *= n ul *= n self.assertEqual(pl[:], ul[:], "in-place mul by %d" % n) self.assertEqual(objid, id(ul), "in-place mul by %d id" % n) pl, ul = self.lists_of_len() self.assertEqual(pl, ul, "cmp for equal") self.assertNotEqual(ul, pl + [2], "cmp for not equal") self.assertGreaterEqual(pl, ul, "cmp for gte self") self.assertLessEqual(pl, ul, "cmp for lte self") self.assertGreaterEqual(ul, pl, "cmp for self gte") self.assertLessEqual(ul, pl, "cmp for self lte") self.assertGreater(pl + [5], ul, "cmp") self.assertGreaterEqual(pl + [5], ul, "cmp") self.assertLess(pl, ul + [2], "cmp") self.assertLessEqual(pl, ul + [2], "cmp") self.assertGreater(ul + [5], pl, "cmp") self.assertGreaterEqual(ul + [5], pl, "cmp") self.assertLess(ul, pl + [2], "cmp") self.assertLessEqual(ul, pl + [2], "cmp") pl[1] = 20 self.assertGreater(pl, ul, "cmp for gt self") self.assertLess(ul, pl, "cmp for self lt") pl[1] = -20 self.assertLess(pl, ul, "cmp for lt self") self.assertGreater(ul, pl, "cmp for gt self") class ListMixinTestSingle(ListMixinTest): listType = UserListB
9cc1319193efb9d75526b1bbd2a60258d707725f299be4c9eb1d3d19dbbfe4b3
# Copyright (c) 2008-2009 Aryeh Leib Taurog, all rights reserved. # Modified from original contribution by Aryeh Leib Taurog, which was # released under the New BSD license. import unittest from django.contrib.gis.geos import ( LinearRing, LineString, MultiPoint, Point, Polygon, fromstr, ) 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_num_coords(x): return x.num_coords def api_get_centroid(x): return x.centroid def api_get_empty(x): return x.empty def api_get_valid(x): return x.valid def api_get_simple(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_get_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(unittest.TestCase): """ Tests Pythonic Mutability of Python GEOS geometry wrappers get/set/delitem on a slice, normal list methods """ def test00_GEOSIndexException(self): "Testing Geometry IndexError" p = Point(1, 2) for i in range(-2, 2): p._checkindex(i) with self.assertRaises(IndexError): p._checkindex(2) with self.assertRaises(IndexError): p._checkindex(-3) def test01_PointMutations(self): "Testing Point mutations" for p in (Point(1, 2, 3), fromstr("POINT (1 2 3)")): self.assertEqual( p._get_single_external(1), 2.0, "Point _get_single_external" ) # _set_single p._set_single(0, 100) self.assertEqual(p.coords, (100.0, 2.0, 3.0), "Point _set_single") # _set_list p._set_list(2, (50, 3141)) self.assertEqual(p.coords, (50.0, 3141.0), "Point _set_list") def test02_PointExceptions(self): "Testing Point exceptions" with self.assertRaises(TypeError): Point(range(1)) with self.assertRaises(TypeError): Point(range(4)) def test03_PointApi(self): "Testing Point API" q = Point(4, 5, 3) for p in (Point(1, 2, 3), fromstr("POINT (1 2 3)")): p[0:2] = [4, 5] for f in geos_function_tests: self.assertEqual(f(q), f(p), "Point " + f.__name__) def test04_LineStringMutations(self): "Testing LineString mutations" for ls in ( LineString((1, 0), (4, 1), (6, -1)), fromstr("LINESTRING (1 0,4 1,6 -1)"), ): self.assertEqual( ls._get_single_external(1), (4.0, 1.0), "LineString _get_single_external", ) # _set_single ls._set_single(0, (-50, 25)) self.assertEqual( ls.coords, ((-50.0, 25.0), (4.0, 1.0), (6.0, -1.0)), "LineString _set_single", ) # _set_list ls._set_list(2, ((-50.0, 25.0), (6.0, -1.0))) self.assertEqual( ls.coords, ((-50.0, 25.0), (6.0, -1.0)), "LineString _set_list" ) lsa = LineString(ls.coords) for f in geos_function_tests: self.assertEqual(f(lsa), f(ls), "LineString " + f.__name__) def test05_Polygon(self): "Testing Polygon mutations" for pg in ( Polygon( ((1, 0), (4, 1), (6, -1), (8, 10), (1, 0)), ((5, 4), (6, 4), (6, 3), (5, 4)), ), fromstr("POLYGON ((1 0,4 1,6 -1,8 10,1 0),(5 4,6 4,6 3,5 4))"), ): self.assertEqual( pg._get_single_external(0), LinearRing((1, 0), (4, 1), (6, -1), (8, 10), (1, 0)), "Polygon _get_single_external(0)", ) self.assertEqual( pg._get_single_external(1), LinearRing((5, 4), (6, 4), (6, 3), (5, 4)), "Polygon _get_single_external(1)", ) # _set_list pg._set_list( 2, ( ((1, 2), (10, 0), (12, 9), (-1, 15), (1, 2)), ((4, 2), (5, 2), (5, 3), (4, 2)), ), ) self.assertEqual( pg.coords, ( ((1.0, 2.0), (10.0, 0.0), (12.0, 9.0), (-1.0, 15.0), (1.0, 2.0)), ((4.0, 2.0), (5.0, 2.0), (5.0, 3.0), (4.0, 2.0)), ), "Polygon _set_list", ) lsa = Polygon(*pg.coords) for f in geos_function_tests: self.assertEqual(f(lsa), f(pg), "Polygon " + f.__name__) def test06_Collection(self): "Testing Collection mutations" points = ( MultiPoint(*map(Point, ((3, 4), (-1, 2), (5, -4), (2, 8)))), fromstr("MULTIPOINT (3 4,-1 2,5 -4,2 8)"), ) for mp in points: self.assertEqual( mp._get_single_external(2), Point(5, -4), "Collection _get_single_external", ) mp._set_list(3, map(Point, ((5, 5), (3, -2), (8, 1)))) self.assertEqual( mp.coords, ((5.0, 5.0), (3.0, -2.0), (8.0, 1.0)), "Collection _set_list" ) lsa = MultiPoint(*map(Point, ((5, 5), (3, -2), (8, 1)))) for f in geos_function_tests: self.assertEqual(f(lsa), f(mp), "MultiPoint " + f.__name__)
a013a85e76c702bbfdb9e894c8c2d94535121d956998c1854967fa9ea9a8bfaa
import binascii from django.contrib.gis.geos import ( GEOSGeometry, Point, Polygon, WKBReader, WKBWriter, WKTReader, WKTWriter, ) from django.contrib.gis.geos.libgeos import geos_version_tuple from django.test import SimpleTestCase class 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 geom in (g1, g2): self.assertEqual(ref, geom) # Should only accept string objects. with self.assertRaises(TypeError): wkt_r.read(1) with self.assertRaises(TypeError): wkt_r.read(memoryview(b"foo")) def test02_wktwriter(self): # Creating a WKTWriter instance, testing its ptr property. wkt_w = WKTWriter() with self.assertRaises(TypeError): wkt_w.ptr = WKTReader.ptr_type() ref = GEOSGeometry("POINT (5 23)") ref_wkt = "POINT (5.0000000000000000 23.0000000000000000)" self.assertEqual(ref_wkt, wkt_w.write(ref).decode()) def test_wktwriter_constructor_arguments(self): wkt_w = WKTWriter(dim=3, trim=True, precision=3) ref = GEOSGeometry("POINT (5.34562 23 1.5)") if geos_version_tuple() > (3, 10): ref_wkt = "POINT Z (5.346 23 1.5)" else: ref_wkt = "POINT Z (5.35 23 1.5)" self.assertEqual(ref_wkt, wkt_w.write(ref).decode()) def test03_wkbreader(self): # Creating a WKBReader instance wkb_r = WKBReader() hex = b"000000000140140000000000004037000000000000" wkb = memoryview(binascii.a2b_hex(hex)) ref = GEOSGeometry(hex) # read() should return a GEOSGeometry on either a hex string or # a WKB buffer. g1 = wkb_r.read(wkb) g2 = wkb_r.read(hex) for geom in (g1, g2): self.assertEqual(ref, geom) bad_input = (1, 5.23, None, False) for bad_wkb in bad_input: with self.assertRaises(TypeError): wkb_r.read(bad_wkb) def test04_wkbwriter(self): wkb_w = WKBWriter() # Representations of 'POINT (5 23)' in hex -- one normal and # the other with the byte order changed. g = GEOSGeometry("POINT (5 23)") hex1 = b"010100000000000000000014400000000000003740" wkb1 = memoryview(binascii.a2b_hex(hex1)) hex2 = b"000000000140140000000000004037000000000000" wkb2 = memoryview(binascii.a2b_hex(hex2)) self.assertEqual(hex1, wkb_w.write_hex(g)) self.assertEqual(wkb1, wkb_w.write(g)) # Ensuring bad byteorders are not accepted. for bad_byteorder in (-1, 2, 523, "foo", None): # Equivalent of `wkb_w.byteorder = bad_byteorder` with self.assertRaises(ValueError): wkb_w._set_byteorder(bad_byteorder) # Setting the byteorder to 0 (for Big Endian) wkb_w.byteorder = 0 self.assertEqual(hex2, wkb_w.write_hex(g)) self.assertEqual(wkb2, wkb_w.write(g)) # Back to Little Endian wkb_w.byteorder = 1 # Now, trying out the 3D and SRID flags. g = GEOSGeometry("POINT (5 23 17)") g.srid = 4326 hex3d = b"0101000080000000000000144000000000000037400000000000003140" wkb3d = memoryview(binascii.a2b_hex(hex3d)) hex3d_srid = ( b"01010000A0E6100000000000000000144000000000000037400000000000003140" ) wkb3d_srid = memoryview(binascii.a2b_hex(hex3d_srid)) # Ensuring bad output dimensions are not accepted for bad_outdim in (-1, 0, 1, 4, 423, "foo", None): with self.assertRaisesMessage( ValueError, "WKB output dimension must be 2 or 3" ): wkb_w.outdim = bad_outdim # Now setting the output dimensions to be 3 wkb_w.outdim = 3 self.assertEqual(hex3d, wkb_w.write_hex(g)) self.assertEqual(wkb3d, wkb_w.write(g)) # Telling the WKBWriter to include the srid in the representation. wkb_w.srid = True self.assertEqual(hex3d_srid, wkb_w.write_hex(g)) self.assertEqual(wkb3d_srid, wkb_w.write(g)) def test_wkt_writer_trim(self): wkt_w = WKTWriter() self.assertFalse(wkt_w.trim) self.assertEqual( wkt_w.write(Point(1, 1)), b"POINT (1.0000000000000000 1.0000000000000000)" ) wkt_w.trim = True self.assertTrue(wkt_w.trim) self.assertEqual(wkt_w.write(Point(1, 1)), b"POINT (1 1)") self.assertEqual(wkt_w.write(Point(1.1, 1)), b"POINT (1.1 1)") self.assertEqual( wkt_w.write(Point(1.0 / 3, 1)), b"POINT (0.3333333333333333 1)" ) wkt_w.trim = False self.assertFalse(wkt_w.trim) self.assertEqual( wkt_w.write(Point(1, 1)), b"POINT (1.0000000000000000 1.0000000000000000)" ) def test_wkt_writer_precision(self): wkt_w = WKTWriter() self.assertIsNone(wkt_w.precision) self.assertEqual( wkt_w.write(Point(1.0 / 3, 2.0 / 3)), b"POINT (0.3333333333333333 0.6666666666666666)", ) wkt_w.precision = 1 self.assertEqual(wkt_w.precision, 1) self.assertEqual(wkt_w.write(Point(1.0 / 3, 2.0 / 3)), b"POINT (0.3 0.7)") wkt_w.precision = 0 self.assertEqual(wkt_w.precision, 0) self.assertEqual(wkt_w.write(Point(1.0 / 3, 2.0 / 3)), b"POINT (0 1)") wkt_w.precision = None self.assertIsNone(wkt_w.precision) self.assertEqual( wkt_w.write(Point(1.0 / 3, 2.0 / 3)), b"POINT (0.3333333333333333 0.6666666666666666)", ) with self.assertRaisesMessage( AttributeError, "WKT output rounding precision must be " ): wkt_w.precision = "potato" def test_empty_point_wkb(self): p = Point(srid=4326) wkb_w = WKBWriter() wkb_w.srid = False with self.assertRaisesMessage( ValueError, "Empty point is not representable in WKB." ): wkb_w.write(p) with self.assertRaisesMessage( ValueError, "Empty point is not representable in WKB." ): wkb_w.write_hex(p) wkb_w.srid = True for byteorder, hex in enumerate( [ b"0020000001000010E67FF80000000000007FF8000000000000", b"0101000020E6100000000000000000F87F000000000000F87F", ] ): wkb_w.byteorder = byteorder self.assertEqual(wkb_w.write_hex(p), hex) self.assertEqual(GEOSGeometry(wkb_w.write_hex(p)), p) self.assertEqual(wkb_w.write(p), memoryview(binascii.a2b_hex(hex))) self.assertEqual(GEOSGeometry(wkb_w.write(p)), p) def test_empty_polygon_wkb(self): p = Polygon(srid=4326) p_no_srid = Polygon() wkb_w = WKBWriter() wkb_w.srid = True for byteorder, hexes in enumerate( [ (b"000000000300000000", b"0020000003000010E600000000"), (b"010300000000000000", b"0103000020E610000000000000"), ] ): wkb_w.byteorder = byteorder for srid, hex in enumerate(hexes): wkb_w.srid = srid self.assertEqual(wkb_w.write_hex(p), hex) self.assertEqual( GEOSGeometry(wkb_w.write_hex(p)), p if srid else p_no_srid ) self.assertEqual(wkb_w.write(p), memoryview(binascii.a2b_hex(hex))) self.assertEqual(GEOSGeometry(wkb_w.write(p)), p if srid else p_no_srid)
64f1fcd9ad8209e49533741c89ce91948cee16141cb36944619778f8a1488ddb
from django.contrib.gis.geos import LineString 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): with self.subTest(i): self.assertEqual(coord_seq[i], (i, i)) for i in (-3, 10): msg = "invalid GEOS Geometry index: %s" % i with self.subTest(i): with self.assertRaisesMessage(IndexError, msg): coord_seq[i]
5194a7a63a84b37e8b31061583799131175f04684f29e560bbe4cf147c0630a8
import ctypes import itertools import json import pickle import random from binascii import a2b_hex from io import BytesIO from unittest import mock, skipIf from django.contrib.gis import gdal from django.contrib.gis.geos import ( GeometryCollection, GEOSException, GEOSGeometry, LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, fromfile, fromstr, ) from django.contrib.gis.geos.libgeos import geos_version_tuple from django.contrib.gis.shortcuts import numpy from django.template import Context from django.template.engine import Engine from django.test import SimpleTestCase from ..test_data import TestDataMixin class GEOSTest(SimpleTestCase, TestDataMixin): def test_wkt(self): "Testing WKT output." for g in self.geometries.wkt_out: geom = fromstr(g.wkt) if geom.hasz: self.assertEqual(g.ewkt, geom.wkt) def test_wkt_invalid(self): msg = "String input unrecognized as WKT EWKT, and HEXEWKB." with self.assertRaisesMessage(ValueError, msg): fromstr("POINT(٠٠١ ٠)") with self.assertRaisesMessage(ValueError, msg): fromstr("SRID=٧٥٨٣;POINT(100 0)") def test_hex(self): "Testing HEX output." for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) self.assertEqual(g.hex, geom.hex.decode()) def test_hexewkb(self): "Testing (HEX)EWKB output." # For testing HEX(EWKB). ogc_hex = b"01010000000000000000000000000000000000F03F" ogc_hex_3d = b"01010000800000000000000000000000000000F03F0000000000000040" # `SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(0 1)', 4326));` hexewkb_2d = b"0101000020E61000000000000000000000000000000000F03F" # `SELECT ST_AsHEXEWKB(ST_GeomFromEWKT('SRID=4326;POINT(0 1 2)'));` hexewkb_3d = ( b"01010000A0E61000000000000000000000000000000000F03F0000000000000040" ) pnt_2d = Point(0, 1, srid=4326) pnt_3d = Point(0, 1, 2, srid=4326) # OGC-compliant HEX will not have SRID value. self.assertEqual(ogc_hex, pnt_2d.hex) self.assertEqual(ogc_hex_3d, pnt_3d.hex) # HEXEWKB should be appropriate for its dimension -- have to use an # a WKBWriter w/dimension set accordingly, else GEOS will insert # garbage into 3D coordinate if there is none. self.assertEqual(hexewkb_2d, pnt_2d.hexewkb) self.assertEqual(hexewkb_3d, pnt_3d.hexewkb) self.assertIs(GEOSGeometry(hexewkb_3d).hasz, True) # Same for EWKB. 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.wkt_out: geom = fromstr(tg.wkt) kml = getattr(tg, "kml", False) if kml: self.assertEqual(kml, geom.kml) def test_errors(self): "Testing the Error handlers." # string-based for err in self.geometries.errors: with self.assertRaises((GEOSException, ValueError)): fromstr(err.wkt) # Bad WKB with self.assertRaises(GEOSException): GEOSGeometry(memoryview(b"0")) class NotAGeometry: pass # Some other object with self.assertRaises(TypeError): GEOSGeometry(NotAGeometry()) # None with self.assertRaises(TypeError): GEOSGeometry(None) def test_wkb(self): "Testing WKB output." for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) wkb = geom.wkb self.assertEqual(wkb.hex().upper(), g.hex) def test_create_hex(self): "Testing creation from HEX." for g in self.geometries.hex_wkt: geom_h = GEOSGeometry(g.hex) # we need to do this so decimal places get normalized geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt) def test_create_wkb(self): "Testing creation from WKB." for g in self.geometries.hex_wkt: wkb = memoryview(bytes.fromhex(g.hex)) geom_h = GEOSGeometry(wkb) # we need to do this so decimal places get normalized geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt) def test_ewkt(self): "Testing EWKT." srids = (-1, 32140) for srid in srids: for p in self.geometries.polygons: ewkt = "SRID=%d;%s" % (srid, p.wkt) poly = fromstr(ewkt) self.assertEqual(srid, poly.srid) self.assertEqual(srid, poly.shell.srid) self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export def test_json(self): "Testing GeoJSON input/output (via GDAL)." for g in self.geometries.json_geoms: geom = GEOSGeometry(g.wkt) if not hasattr(g, "not_equal"): # Loading jsons to prevent decimal differences self.assertEqual(json.loads(g.json), json.loads(geom.json)) self.assertEqual(json.loads(g.json), json.loads(geom.geojson)) self.assertEqual(GEOSGeometry(g.wkt, 4326), GEOSGeometry(geom.json)) def test_json_srid(self): geojson_data = { "type": "Point", "coordinates": [2, 49], "crs": { "type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::4322"}, }, } self.assertEqual( GEOSGeometry(json.dumps(geojson_data)), Point(2, 49, srid=4322) ) def test_fromfile(self): "Testing the fromfile() factory." ref_pnt = GEOSGeometry("POINT(5 23)") wkt_f = BytesIO() wkt_f.write(ref_pnt.wkt.encode()) wkb_f = BytesIO() wkb_f.write(bytes(ref_pnt.wkb)) # Other tests use `fromfile()` on string filenames so those # aren't tested here. for fh in (wkt_f, wkb_f): fh.seek(0) pnt = fromfile(fh) self.assertEqual(ref_pnt, pnt) def test_eq(self): "Testing equivalence." p = fromstr("POINT(5 23)") self.assertEqual(p, p.wkt) self.assertNotEqual(p, "foo") ls = fromstr("LINESTRING(0 0, 1 1, 5 5)") self.assertEqual(ls, ls.wkt) self.assertNotEqual(p, "bar") self.assertEqual(p, "POINT(5.0 23.0)") # Error shouldn't be raise on equivalence testing with # an invalid type. for g in (p, ls): self.assertIsNotNone(g) self.assertNotEqual(g, {"foo": "bar"}) self.assertIsNot(g, False) def test_hash(self): point_1 = Point(5, 23) point_2 = Point(5, 23, srid=4326) point_3 = Point(5, 23, srid=32632) multipoint_1 = MultiPoint(point_1, srid=4326) multipoint_2 = MultiPoint(point_2) multipoint_3 = MultiPoint(point_3) self.assertNotEqual(hash(point_1), hash(point_2)) self.assertNotEqual(hash(point_1), hash(point_3)) self.assertNotEqual(hash(point_2), hash(point_3)) self.assertNotEqual(hash(multipoint_1), hash(multipoint_2)) self.assertEqual(hash(multipoint_2), hash(multipoint_3)) self.assertNotEqual(hash(multipoint_1), hash(point_1)) self.assertNotEqual(hash(multipoint_2), hash(point_2)) self.assertNotEqual(hash(multipoint_3), hash(point_3)) def test_eq_with_srid(self): "Testing non-equivalence with different srids." p0 = Point(5, 23) p1 = Point(5, 23, srid=4326) p2 = Point(5, 23, srid=32632) # GEOS self.assertNotEqual(p0, p1) self.assertNotEqual(p1, p2) # EWKT self.assertNotEqual(p0, p1.ewkt) self.assertNotEqual(p1, p0.ewkt) self.assertNotEqual(p1, p2.ewkt) # Equivalence with matching SRIDs self.assertEqual(p2, p2) self.assertEqual(p2, p2.ewkt) # WKT contains no SRID so will not equal self.assertNotEqual(p2, p2.wkt) # SRID of 0 self.assertEqual(p0, "SRID=0;POINT (5 23)") self.assertNotEqual(p1, "SRID=0;POINT (5 23)") def test_points(self): "Testing Point objects." prev = fromstr("POINT(0 0)") for p in self.geometries.points: # Creating the point from the WKT pnt = fromstr(p.wkt) self.assertEqual(pnt.geom_type, "Point") self.assertEqual(pnt.geom_typeid, 0) self.assertEqual(pnt.dims, 0) self.assertEqual(p.x, pnt.x) self.assertEqual(p.y, pnt.y) self.assertEqual(pnt, fromstr(p.wkt)) self.assertIs(pnt == prev, False) # Use assertIs() to test __eq__. # Making sure that the point's X, Y components are what we expect self.assertAlmostEqual(p.x, pnt.tuple[0], 9) self.assertAlmostEqual(p.y, pnt.tuple[1], 9) # Testing the third dimension, and getting the tuple arguments if hasattr(p, "z"): self.assertIs(pnt.hasz, True) self.assertEqual(p.z, pnt.z) self.assertEqual(p.z, pnt.tuple[2], 9) tup_args = (p.x, p.y, p.z) set_tup1 = (2.71, 3.14, 5.23) set_tup2 = (5.23, 2.71, 3.14) else: self.assertIs(pnt.hasz, False) self.assertIsNone(pnt.z) tup_args = (p.x, p.y) set_tup1 = (2.71, 3.14) set_tup2 = (3.14, 2.71) # Centroid operation on point should be point itself self.assertEqual(p.centroid, pnt.centroid.tuple) # Now testing the different constructors pnt2 = Point(tup_args) # e.g., Point((1, 2)) pnt3 = Point(*tup_args) # e.g., Point(1, 2) self.assertEqual(pnt, pnt2) self.assertEqual(pnt, pnt3) # Now testing setting the x and y pnt.y = 3.14 pnt.x = 2.71 self.assertEqual(3.14, pnt.y) self.assertEqual(2.71, pnt.x) # Setting via the tuple/coords property pnt.tuple = set_tup1 self.assertEqual(set_tup1, pnt.tuple) pnt.coords = set_tup2 self.assertEqual(set_tup2, pnt.coords) prev = pnt # setting the previous geometry def test_point_reverse(self): point = GEOSGeometry("POINT(144.963 -37.8143)", 4326) self.assertEqual(point.srid, 4326) point.reverse() self.assertEqual(point.ewkt, "SRID=4326;POINT (-37.8143 144.963)") def test_multipoints(self): "Testing MultiPoint objects." for mp in self.geometries.multipoints: mpnt = fromstr(mp.wkt) self.assertEqual(mpnt.geom_type, "MultiPoint") self.assertEqual(mpnt.geom_typeid, 4) self.assertEqual(mpnt.dims, 0) self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9) self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9) with self.assertRaises(IndexError): mpnt.__getitem__(len(mpnt)) self.assertEqual(mp.centroid, mpnt.centroid.tuple) self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt)) for p in mpnt: self.assertEqual(p.geom_type, "Point") self.assertEqual(p.geom_typeid, 0) self.assertIs(p.empty, False) self.assertIs(p.valid, True) def test_linestring(self): "Testing LineString objects." prev = fromstr("POINT(0 0)") for line in self.geometries.linestrings: ls = fromstr(line.wkt) self.assertEqual(ls.geom_type, "LineString") self.assertEqual(ls.geom_typeid, 1) self.assertEqual(ls.dims, 1) self.assertIs(ls.empty, False) self.assertIs(ls.ring, False) if hasattr(line, "centroid"): self.assertEqual(line.centroid, ls.centroid.tuple) if hasattr(line, "tup"): self.assertEqual(line.tup, ls.tuple) self.assertEqual(ls, fromstr(line.wkt)) self.assertIs(ls == prev, False) # Use assertIs() to test __eq__. with self.assertRaises(IndexError): ls.__getitem__(len(ls)) prev = ls # Creating a LineString from a tuple, list, and numpy array self.assertEqual(ls, LineString(ls.tuple)) # tuple self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list # Point individual arguments self.assertEqual( ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt ) if numpy: self.assertEqual( ls, LineString(numpy.array(ls.tuple)) ) # as numpy array with self.assertRaisesMessage( TypeError, "Each coordinate should be a sequence (list or tuple)" ): LineString((0, 0)) with self.assertRaisesMessage( ValueError, "LineString requires at least 2 points, got 1." ): LineString([(0, 0)]) if numpy: with self.assertRaisesMessage( ValueError, "LineString requires at least 2 points, got 1." ): LineString(numpy.array([(0, 0)])) with mock.patch("django.contrib.gis.geos.linestring.numpy", False): with self.assertRaisesMessage( TypeError, "Invalid initialization input for LineStrings." ): LineString("wrong input") # Test __iter__(). self.assertEqual( list(LineString((0, 0), (1, 1), (2, 2))), [(0, 0), (1, 1), (2, 2)] ) def test_linestring_reverse(self): line = GEOSGeometry("LINESTRING(144.963 -37.8143,151.2607 -33.887)", 4326) self.assertEqual(line.srid, 4326) line.reverse() self.assertEqual( line.ewkt, "SRID=4326;LINESTRING (151.2607 -33.887, 144.963 -37.8143)" ) def _test_is_counterclockwise(self): lr = LinearRing((0, 0), (1, 0), (0, 1), (0, 0)) self.assertIs(lr.is_counterclockwise, True) lr.reverse() self.assertIs(lr.is_counterclockwise, False) msg = "Orientation of an empty LinearRing cannot be determined." with self.assertRaisesMessage(ValueError, msg): LinearRing().is_counterclockwise @skipIf(geos_version_tuple() < (3, 7), "GEOS >= 3.7.0 is required") def test_is_counterclockwise(self): self._test_is_counterclockwise() @skipIf(geos_version_tuple() < (3, 7), "GEOS >= 3.7.0 is required") def test_is_counterclockwise_geos_error(self): with mock.patch("django.contrib.gis.geos.prototypes.cs_is_ccw") as mocked: mocked.return_value = 0 mocked.func_name = "GEOSCoordSeq_isCCW" msg = 'Error encountered in GEOS C function "GEOSCoordSeq_isCCW".' with self.assertRaisesMessage(GEOSException, msg): LinearRing((0, 0), (1, 0), (0, 1), (0, 0)).is_counterclockwise @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.6.9") def test_is_counterclockwise_fallback(self): self._test_is_counterclockwise() def test_multilinestring(self): "Testing MultiLineString objects." prev = fromstr("POINT(0 0)") for line in self.geometries.multilinestrings: ml = fromstr(line.wkt) self.assertEqual(ml.geom_type, "MultiLineString") self.assertEqual(ml.geom_typeid, 5) self.assertEqual(ml.dims, 1) self.assertAlmostEqual(line.centroid[0], ml.centroid.x, 9) self.assertAlmostEqual(line.centroid[1], ml.centroid.y, 9) self.assertEqual(ml, fromstr(line.wkt)) self.assertIs(ml == prev, False) # Use assertIs() to test __eq__. prev = ml for ls in ml: self.assertEqual(ls.geom_type, "LineString") self.assertEqual(ls.geom_typeid, 1) self.assertIs(ls.empty, False) with self.assertRaises(IndexError): ml.__getitem__(len(ml)) self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt) self.assertEqual( ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml)) ) def test_linearring(self): "Testing LinearRing objects." for rr in self.geometries.linearrings: lr = fromstr(rr.wkt) self.assertEqual(lr.geom_type, "LinearRing") self.assertEqual(lr.geom_typeid, 2) self.assertEqual(lr.dims, 1) self.assertEqual(rr.n_p, len(lr)) self.assertIs(lr.valid, True) self.assertIs(lr.empty, False) # Creating a LinearRing from a tuple, list, and numpy array self.assertEqual(lr, LinearRing(lr.tuple)) self.assertEqual(lr, LinearRing(*lr.tuple)) self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple])) if numpy: self.assertEqual(lr, LinearRing(numpy.array(lr.tuple))) with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 3." ): LinearRing((0, 0), (1, 1), (0, 0)) with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 1." ): LinearRing([(0, 0)]) if numpy: with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 1." ): LinearRing(numpy.array([(0, 0)])) def test_linearring_json(self): self.assertJSONEqual( LinearRing((0, 0), (0, 1), (1, 1), (0, 0)).json, '{"coordinates": [[0, 0], [0, 1], [1, 1], [0, 0]], "type": "LineString"}', ) def test_polygons_from_bbox(self): "Testing `from_bbox` class method." bbox = (-180, -90, 180, 90) p = Polygon.from_bbox(bbox) self.assertEqual(bbox, p.extent) # Testing numerical precision x = 3.14159265358979323 bbox = (0, 0, 1, x) p = Polygon.from_bbox(bbox) y = p.extent[-1] self.assertEqual(format(x, ".13f"), format(y, ".13f")) def test_polygons(self): "Testing Polygon objects." prev = fromstr("POINT(0 0)") for p in self.geometries.polygons: # Creating the Polygon, testing its properties. poly = fromstr(p.wkt) self.assertEqual(poly.geom_type, "Polygon") self.assertEqual(poly.geom_typeid, 3) self.assertEqual(poly.dims, 2) self.assertIs(poly.empty, False) self.assertIs(poly.ring, False) self.assertEqual(p.n_i, poly.num_interior_rings) self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__ self.assertEqual(p.n_p, poly.num_points) # Area & Centroid self.assertAlmostEqual(p.area, poly.area, 9) self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9) self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9) # Testing the geometry equivalence self.assertEqual(poly, fromstr(p.wkt)) # Should not be equal to previous geometry self.assertIs(poly == prev, False) # Use assertIs() to test __eq__. self.assertIs(poly != prev, True) # Use assertIs() to test __ne__. # Testing the exterior ring ring = poly.exterior_ring self.assertEqual(ring.geom_type, "LinearRing") self.assertEqual(ring.geom_typeid, 2) if p.ext_ring_cs: self.assertEqual(p.ext_ring_cs, ring.tuple) self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__ # Testing __getitem__ and __setitem__ on invalid indices with self.assertRaises(IndexError): poly.__getitem__(len(poly)) with self.assertRaises(IndexError): poly.__setitem__(len(poly), False) with self.assertRaises(IndexError): poly.__getitem__(-1 * len(poly) - 1) # Testing __iter__ for r in poly: self.assertEqual(r.geom_type, "LinearRing") self.assertEqual(r.geom_typeid, 2) # Testing polygon construction. with self.assertRaises(TypeError): Polygon(0, [1, 2, 3]) with self.assertRaises(TypeError): Polygon("foo") # Polygon(shell, (hole1, ... holeN)) ext_ring, *int_rings = poly self.assertEqual(poly, Polygon(ext_ring, int_rings)) # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN) ring_tuples = tuple(r.tuple for r in poly) self.assertEqual(poly, Polygon(*ring_tuples)) # Constructing with tuples of LinearRings. self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt) self.assertEqual( poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt ) def test_polygons_templates(self): # Accessing Polygon attributes in templates should work. engine = Engine() template = engine.from_string("{{ polygons.0.wkt }}") polygons = [fromstr(p.wkt) for p in self.geometries.multipolygons[:2]] content = template.render(Context({"polygons": polygons})) self.assertIn("MULTIPOLYGON (((100", content) def test_polygon_comparison(self): p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0))) self.assertGreater(p1, p2) self.assertLess(p2, p1) p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0))) p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0))) self.assertGreater(p4, p3) self.assertLess(p3, p4) def test_multipolygons(self): "Testing MultiPolygon objects." fromstr("POINT (0 0)") for mp in self.geometries.multipolygons: mpoly = fromstr(mp.wkt) self.assertEqual(mpoly.geom_type, "MultiPolygon") self.assertEqual(mpoly.geom_typeid, 6) self.assertEqual(mpoly.dims, 2) self.assertEqual(mp.valid, mpoly.valid) if mp.valid: self.assertEqual(mp.num_geom, mpoly.num_geom) self.assertEqual(mp.n_p, mpoly.num_coords) self.assertEqual(mp.num_geom, len(mpoly)) with self.assertRaises(IndexError): mpoly.__getitem__(len(mpoly)) for p in mpoly: self.assertEqual(p.geom_type, "Polygon") self.assertEqual(p.geom_typeid, 3) self.assertIs(p.valid, True) self.assertEqual( mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt ) def test_memory_hijinks(self): "Testing Geometry __del__() on rings and polygons." # #### Memory issues with rings and poly # These tests are needed to ensure sanity with writable geometries. # Getting a polygon with interior rings, and pulling out the interior rings poly = fromstr(self.geometries.polygons[1].wkt) ring1 = poly[0] ring2 = poly[1] # These deletes should be 'harmless' since they are done on child geometries del ring1 del ring2 ring1 = poly[0] ring2 = poly[1] # Deleting the polygon del poly # Access to these rings is OK since they are clones. str(ring1) str(ring2) def test_coord_seq(self): "Testing Coordinate Sequence objects." for p in self.geometries.polygons: if p.ext_ring_cs: # Constructing the polygon and getting the coordinate sequence poly = fromstr(p.wkt) cs = poly.exterior_ring.coord_seq self.assertEqual( p.ext_ring_cs, cs.tuple ) # done in the Polygon test too. self.assertEqual( len(p.ext_ring_cs), len(cs) ) # Making sure __len__ works # Checks __getitem__ and __setitem__ for i in range(len(p.ext_ring_cs)): c1 = p.ext_ring_cs[i] # Expected value c2 = cs[i] # Value from coordseq self.assertEqual(c1, c2) # Constructing the test value to set the coordinate sequence with if len(c1) == 2: tset = (5, 23) else: tset = (5, 23, 8) cs[i] = tset # Making sure every set point matches what we expect for j in range(len(tset)): cs[i] = tset self.assertEqual(tset[j], cs[i][j]) def test_relate_pattern(self): "Testing relate() and relate_pattern()." g = fromstr("POINT (0 0)") with self.assertRaises(GEOSException): g.relate_pattern(0, "invalid pattern, yo") for rg in self.geometries.relate_geoms: a = fromstr(rg.wkt_a) b = fromstr(rg.wkt_b) self.assertEqual(rg.result, a.relate_pattern(b, rg.pattern)) self.assertEqual(rg.pattern, a.relate(b)) def test_intersection(self): "Testing intersects() and intersection()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) i1 = fromstr(self.geometries.intersect_geoms[i].wkt) self.assertIs(a.intersects(b), True) i2 = a.intersection(b) self.assertTrue(i1.equals(i2)) self.assertTrue(i1.equals(a & b)) # __and__ is intersection operator a &= b # testing __iand__ self.assertTrue(i1.equals(a)) def test_union(self): "Testing union()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) u1 = fromstr(self.geometries.union_geoms[i].wkt) u2 = a.union(b) self.assertTrue(u1.equals(u2)) self.assertTrue(u1.equals(a | b)) # __or__ is union operator a |= b # testing __ior__ self.assertTrue(u1.equals(a)) def test_unary_union(self): "Testing unary_union." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) u1 = fromstr(self.geometries.union_geoms[i].wkt) u2 = GeometryCollection(a, b).unary_union self.assertTrue(u1.equals(u2)) def test_difference(self): "Testing difference()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) d1 = fromstr(self.geometries.diff_geoms[i].wkt) d2 = a.difference(b) self.assertTrue(d1.equals(d2)) self.assertTrue(d1.equals(a - b)) # __sub__ is difference operator a -= b # testing __isub__ self.assertTrue(d1.equals(a)) def test_symdifference(self): "Testing sym_difference()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) d1 = fromstr(self.geometries.sdiff_geoms[i].wkt) d2 = a.sym_difference(b) self.assertTrue(d1.equals(d2)) self.assertTrue( d1.equals(a ^ b) ) # __xor__ is symmetric difference operator a ^= b # testing __ixor__ self.assertTrue(d1.equals(a)) def test_buffer(self): bg = self.geometries.buffer_geoms[0] g = fromstr(bg.wkt) # Can't use a floating-point for the number of quadsegs. with self.assertRaises(ctypes.ArgumentError): g.buffer(bg.width, quadsegs=1.1) self._test_buffer(self.geometries.buffer_geoms, "buffer") def test_buffer_with_style(self): bg = self.geometries.buffer_with_style_geoms[0] g = fromstr(bg.wkt) # Can't use a floating-point for the number of quadsegs. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, quadsegs=1.1) # Can't use a floating-point for the end cap style. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, end_cap_style=1.2) # Can't use a end cap style that is not in the enum. with self.assertRaises(GEOSException): g.buffer_with_style(bg.width, end_cap_style=55) # Can't use a floating-point for the join style. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, join_style=1.3) # Can't use a join style that is not in the enum. with self.assertRaises(GEOSException): g.buffer_with_style(bg.width, join_style=66) self._test_buffer( itertools.chain( self.geometries.buffer_geoms, self.geometries.buffer_with_style_geoms ), "buffer_with_style", ) def _test_buffer(self, geometries, buffer_method_name): for bg in geometries: g = fromstr(bg.wkt) # The buffer we expect exp_buf = fromstr(bg.buffer_wkt) # Constructing our buffer buf_kwargs = { kwarg_name: getattr(bg, kwarg_name) for kwarg_name in ( "width", "quadsegs", "end_cap_style", "join_style", "mitre_limit", ) if hasattr(bg, kwarg_name) } buf = getattr(g, buffer_method_name)(**buf_kwargs) self.assertEqual(exp_buf.num_coords, buf.num_coords) self.assertEqual(len(exp_buf), len(buf)) # Now assuring that each point in the buffer is almost equal for j in range(len(exp_buf)): exp_ring = exp_buf[j] buf_ring = buf[j] self.assertEqual(len(exp_ring), len(buf_ring)) for k in range(len(exp_ring)): # Asserting the X, Y of each point are almost equal (due to # floating point imprecision). self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9) self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9) def test_covers(self): poly = Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0, 0))) self.assertTrue(poly.covers(Point(5, 5))) self.assertFalse(poly.covers(Point(100, 100))) def test_closed(self): ls_closed = LineString((0, 0), (1, 1), (0, 0)) ls_not_closed = LineString((0, 0), (1, 1)) self.assertFalse(ls_not_closed.closed) self.assertTrue(ls_closed.closed) def test_srid(self): "Testing the SRID property and keyword." # Testing SRID keyword on Point pnt = Point(5, 23, srid=4326) self.assertEqual(4326, pnt.srid) pnt.srid = 3084 self.assertEqual(3084, pnt.srid) with self.assertRaises(ctypes.ArgumentError): pnt.srid = "4326" # Testing SRID keyword on fromstr(), and on Polygon rings. poly = fromstr(self.geometries.polygons[1].wkt, srid=4269) self.assertEqual(4269, poly.srid) for ring in poly: self.assertEqual(4269, ring.srid) poly.srid = 4326 self.assertEqual(4326, poly.shell.srid) # Testing SRID keyword on GeometryCollection gc = GeometryCollection( Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021 ) self.assertEqual(32021, gc.srid) for i in range(len(gc)): self.assertEqual(32021, gc[i].srid) # GEOS may get the SRID from HEXEWKB # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS # using `SELECT GeomFromText('POINT (5 23)', 4326);`. hex = "0101000020E610000000000000000014400000000000003740" p1 = fromstr(hex) self.assertEqual(4326, p1.srid) p2 = fromstr(p1.hex) self.assertIsNone(p2.srid) p3 = fromstr(p1.hex, srid=-1) # -1 is intended. self.assertEqual(-1, p3.srid) # Testing that geometry SRID could be set to its own value pnt_wo_srid = Point(1, 1) pnt_wo_srid.srid = pnt_wo_srid.srid # Input geometries that have an SRID. self.assertEqual(GEOSGeometry(pnt.ewkt, srid=pnt.srid).srid, pnt.srid) self.assertEqual(GEOSGeometry(pnt.ewkb, srid=pnt.srid).srid, pnt.srid) with self.assertRaisesMessage( ValueError, "Input geometry already has SRID: %d." % pnt.srid ): GEOSGeometry(pnt.ewkt, srid=1) with self.assertRaisesMessage( ValueError, "Input geometry already has SRID: %d." % pnt.srid ): GEOSGeometry(pnt.ewkb, srid=1) def test_custom_srid(self): """Test with a null srid and a srid unknown to GDAL.""" for srid in [None, 999999]: pnt = Point(111200, 220900, srid=srid) self.assertTrue( pnt.ewkt.startswith( ("SRID=%s;" % srid if srid else "") + "POINT (111200" ) ) self.assertIsInstance(pnt.ogr, gdal.OGRGeometry) self.assertIsNone(pnt.srs) # Test conversion from custom to a known srid c2w = gdal.CoordTransform( gdal.SpatialReference( "+proj=mill +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +R_A +ellps=WGS84 " "+datum=WGS84 +units=m +no_defs" ), gdal.SpatialReference(4326), ) new_pnt = pnt.transform(c2w, clone=True) self.assertEqual(new_pnt.srid, 4326) self.assertAlmostEqual(new_pnt.x, 1, 1) self.assertAlmostEqual(new_pnt.y, 2, 1) def test_mutable_geometries(self): "Testing the mutability of Polygons and Geometry Collections." # ### Testing the mutability of Polygons ### for p in self.geometries.polygons: poly = fromstr(p.wkt) # Should only be able to use __setitem__ with LinearRing geometries. with self.assertRaises(TypeError): poly.__setitem__(0, LineString((1, 1), (2, 2))) # Constructing the new shell by adding 500 to every point in the old shell. shell_tup = poly.shell.tuple new_coords = [] for point in shell_tup: new_coords.append((point[0] + 500.0, point[1] + 500.0)) new_shell = LinearRing(*tuple(new_coords)) # Assigning polygon's exterior ring w/the new shell poly.exterior_ring = new_shell str(new_shell) # new shell is still accessible self.assertEqual(poly.exterior_ring, new_shell) self.assertEqual(poly[0], new_shell) # ### Testing the mutability of Geometry Collections for tg in self.geometries.multipoints: mp = fromstr(tg.wkt) for i in range(len(mp)): # Creating a random point. pnt = mp[i] new = Point(random.randint(21, 100), random.randint(21, 100)) # Testing the assignment mp[i] = new str(new) # what was used for the assignment is still accessible self.assertEqual(mp[i], new) self.assertEqual(mp[i].wkt, new.wkt) self.assertNotEqual(pnt, mp[i]) # MultiPolygons involve much more memory management because each # Polygon w/in the collection has its own rings. for tg in self.geometries.multipolygons: mpoly = fromstr(tg.wkt) for i in range(len(mpoly)): poly = mpoly[i] old_poly = mpoly[i] # Offsetting the each ring in the polygon by 500. for j in range(len(poly)): r = poly[j] for k in range(len(r)): r[k] = (r[k][0] + 500.0, r[k][1] + 500.0) poly[j] = r self.assertNotEqual(mpoly[i], poly) # Testing the assignment mpoly[i] = poly str(poly) # Still accessible self.assertEqual(mpoly[i], poly) self.assertNotEqual(mpoly[i], old_poly) # Extreme (!!) __setitem__ -- no longer works, have to detect # in the first object that __setitem__ is called in the subsequent # objects -- maybe mpoly[0, 0, 0] = (3.14, 2.71)? # mpoly[0][0][0] = (3.14, 2.71) # self.assertEqual((3.14, 2.71), mpoly[0][0][0]) # Doing it more slowly.. # self.assertEqual((3.14, 2.71), mpoly[0].shell[0]) # del mpoly def test_point_list_assignment(self): p = Point(0, 0) p[:] = (1, 2, 3) self.assertEqual(p, Point(1, 2, 3)) p[:] = () self.assertEqual(p.wkt, Point()) p[:] = (1, 2) self.assertEqual(p.wkt, Point(1, 2)) with self.assertRaises(ValueError): p[:] = (1,) with self.assertRaises(ValueError): p[:] = (1, 2, 3, 4, 5) def test_linestring_list_assignment(self): ls = LineString((0, 0), (1, 1)) ls[:] = () self.assertEqual(ls, LineString()) ls[:] = ((0, 0), (1, 1), (2, 2)) self.assertEqual(ls, LineString((0, 0), (1, 1), (2, 2))) with self.assertRaises(ValueError): ls[:] = (1,) def test_linearring_list_assignment(self): ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0)) ls[:] = () self.assertEqual(ls, LinearRing()) ls[:] = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) self.assertEqual(ls, LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) with self.assertRaises(ValueError): ls[:] = ((0, 0), (1, 1), (2, 2)) def test_polygon_list_assignment(self): pol = Polygon() pol[:] = (((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)),) self.assertEqual( pol, Polygon( ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)), ), ) pol[:] = () self.assertEqual(pol, Polygon()) def test_geometry_collection_list_assignment(self): p = Point() gc = GeometryCollection() gc[:] = [p] self.assertEqual(gc, GeometryCollection(p)) gc[:] = () self.assertEqual(gc, GeometryCollection()) def test_threed(self): "Testing three-dimensional geometries." # Testing a 3D Point pnt = Point(2, 3, 8) self.assertEqual((2.0, 3.0, 8.0), pnt.coords) with self.assertRaises(TypeError): pnt.tuple = (1.0, 2.0) pnt.coords = (1.0, 2.0, 3.0) self.assertEqual((1.0, 2.0, 3.0), pnt.coords) # Testing a 3D LineString ls = LineString((2.0, 3.0, 8.0), (50.0, 250.0, -117.0)) self.assertEqual(((2.0, 3.0, 8.0), (50.0, 250.0, -117.0)), ls.tuple) with self.assertRaises(TypeError): ls.__setitem__(0, (1.0, 2.0)) ls[0] = (1.0, 2.0, 3.0) self.assertEqual((1.0, 2.0, 3.0), ls[0]) def test_distance(self): "Testing the distance() function." # Distance to self should be 0. pnt = Point(0, 0) self.assertEqual(0.0, pnt.distance(Point(0, 0))) # Distance should be 1 self.assertEqual(1.0, pnt.distance(Point(0, 1))) # Distance should be ~ sqrt(2) self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11) # Distances are from the closest vertex in each geometry -- # should be 3 (distance from (2, 2) to (5, 2)). ls1 = LineString((0, 0), (1, 1), (2, 2)) ls2 = LineString((5, 2), (6, 1), (7, 0)) self.assertEqual(3, ls1.distance(ls2)) def test_length(self): "Testing the length property." # Points have 0 length. pnt = Point(0, 0) self.assertEqual(0.0, pnt.length) # Should be ~ sqrt(2) ls = LineString((0, 0), (1, 1)) self.assertAlmostEqual(1.41421356237, ls.length, 11) # Should be circumference of Polygon poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) self.assertEqual(4.0, poly.length) # Should be sum of each element's length in collection. mpoly = MultiPolygon(poly.clone(), poly) self.assertEqual(8.0, mpoly.length) def test_emptyCollections(self): "Testing empty geometries and collections." geoms = [ GeometryCollection([]), fromstr("GEOMETRYCOLLECTION EMPTY"), GeometryCollection(), fromstr("POINT EMPTY"), Point(), fromstr("LINESTRING EMPTY"), LineString(), fromstr("POLYGON EMPTY"), Polygon(), fromstr("MULTILINESTRING EMPTY"), MultiLineString(), fromstr("MULTIPOLYGON EMPTY"), MultiPolygon(()), MultiPolygon(), ] if numpy: geoms.append(LineString(numpy.array([]))) for g in geoms: self.assertIs(g.empty, True) # Testing len() and num_geom. if isinstance(g, Polygon): self.assertEqual(1, len(g)) # Has one empty linear ring self.assertEqual(1, g.num_geom) self.assertEqual(0, len(g[0])) elif isinstance(g, (Point, LineString)): self.assertEqual(1, g.num_geom) self.assertEqual(0, len(g)) else: self.assertEqual(0, g.num_geom) self.assertEqual(0, len(g)) # Testing __getitem__ (doesn't work on Point or Polygon) if isinstance(g, Point): with self.assertRaises(IndexError): g.x elif isinstance(g, Polygon): lr = g.shell self.assertEqual("LINEARRING EMPTY", lr.wkt) self.assertEqual(0, len(lr)) self.assertIs(lr.empty, True) with self.assertRaises(IndexError): lr.__getitem__(0) else: with self.assertRaises(IndexError): g.__getitem__(0) def test_collection_dims(self): gc = GeometryCollection([]) self.assertEqual(gc.dims, -1) gc = GeometryCollection(Point(0, 0)) self.assertEqual(gc.dims, 0) gc = GeometryCollection(LineString((0, 0), (1, 1)), Point(0, 0)) self.assertEqual(gc.dims, 1) gc = GeometryCollection( LineString((0, 0), (1, 1)), Polygon(((0, 0), (0, 1), (1, 1), (0, 0))), Point(0, 0), ) self.assertEqual(gc.dims, 2) def test_collections_of_collections(self): "Testing GeometryCollection handling of other collections." # Creating a GeometryCollection WKT string composed of other # collections and polygons. coll = [mp.wkt for mp in self.geometries.multipolygons if mp.valid] coll.extend(mls.wkt for mls in self.geometries.multilinestrings) coll.extend(p.wkt for p in self.geometries.polygons) coll.extend(mp.wkt for mp in self.geometries.multipoints) gc_wkt = "GEOMETRYCOLLECTION(%s)" % ",".join(coll) # Should construct ok from WKT gc1 = GEOSGeometry(gc_wkt) # Should also construct ok from individual geometry arguments. gc2 = GeometryCollection(*tuple(g for g in gc1)) # And, they should be equal. self.assertEqual(gc1, gc2) def test_gdal(self): "Testing `ogr` and `srs` properties." g1 = fromstr("POINT(5 23)") self.assertIsInstance(g1.ogr, gdal.OGRGeometry) self.assertIsNone(g1.srs) g1_3d = fromstr("POINT(5 23 8)") self.assertIsInstance(g1_3d.ogr, gdal.OGRGeometry) self.assertEqual(g1_3d.ogr.z, 8) g2 = fromstr("LINESTRING(0 0, 5 5, 23 23)", srid=4326) self.assertIsInstance(g2.ogr, gdal.OGRGeometry) self.assertIsInstance(g2.srs, gdal.SpatialReference) self.assertEqual(g2.hex, g2.ogr.hex) self.assertEqual("WGS 84", g2.srs.name) def test_copy(self): "Testing use with the Python `copy` module." import copy poly = GEOSGeometry( "POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))" ) cpy1 = copy.copy(poly) cpy2 = copy.deepcopy(poly) self.assertNotEqual(poly._ptr, cpy1._ptr) self.assertNotEqual(poly._ptr, cpy2._ptr) def test_transform(self): "Testing `transform` method." orig = GEOSGeometry("POINT (-104.609 38.255)", 4326) trans = GEOSGeometry("POINT (992385.4472045 481455.4944650)", 2774) # Using a srid, a SpatialReference object, and a CoordTransform object # for transformations. t1, t2, t3 = orig.clone(), orig.clone(), orig.clone() t1.transform(trans.srid) t2.transform(gdal.SpatialReference("EPSG:2774")) ct = gdal.CoordTransform( gdal.SpatialReference("WGS84"), gdal.SpatialReference(2774) ) t3.transform(ct) # Testing use of the `clone` keyword. k1 = orig.clone() k2 = k1.transform(trans.srid, clone=True) self.assertEqual(k1, orig) self.assertNotEqual(k1, k2) # Different PROJ versions use different transformations, all are # correct as having a 1 meter accuracy. prec = -1 for p in (t1, t2, t3, k2): self.assertAlmostEqual(trans.x, p.x, prec) self.assertAlmostEqual(trans.y, p.y, prec) def test_transform_3d(self): p3d = GEOSGeometry("POINT (5 23 100)", 4326) p3d.transform(2774) self.assertAlmostEqual(p3d.z, 100, 3) def test_transform_noop(self): """Testing `transform` method (SRID match)""" # transform() should no-op if source & dest SRIDs match, # regardless of whether GDAL is available. g = GEOSGeometry("POINT (-104.609 38.255)", 4326) gt = g.tuple g.transform(4326) self.assertEqual(g.tuple, gt) self.assertEqual(g.srid, 4326) g = GEOSGeometry("POINT (-104.609 38.255)", 4326) g1 = g.transform(4326, clone=True) self.assertEqual(g1.tuple, g.tuple) self.assertEqual(g1.srid, 4326) self.assertIsNot(g1, g, "Clone didn't happen") def test_transform_nosrid(self): """Testing `transform` method (no SRID or negative SRID)""" g = GEOSGeometry("POINT (-104.609 38.255)", srid=None) with self.assertRaises(GEOSException): g.transform(2774) g = GEOSGeometry("POINT (-104.609 38.255)", srid=None) with self.assertRaises(GEOSException): g.transform(2774, clone=True) g = GEOSGeometry("POINT (-104.609 38.255)", srid=-1) with self.assertRaises(GEOSException): g.transform(2774) g = GEOSGeometry("POINT (-104.609 38.255)", srid=-1) with self.assertRaises(GEOSException): g.transform(2774, clone=True) def test_extent(self): "Testing `extent` method." # The xmin, ymin, xmax, ymax of the MultiPoint should be returned. mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50)) self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent) pnt = Point(5.23, 17.8) # Extent of points is just the point itself repeated. self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent) # Testing on the 'real world' Polygon. poly = fromstr(self.geometries.polygons[3].wkt) ring = poly.shell x, y = ring.x, ring.y xmin, ymin = min(x), min(y) xmax, ymax = max(x), max(y) self.assertEqual((xmin, ymin, xmax, ymax), poly.extent) def test_pickle(self): "Testing pickling and unpickling support." # Creating a list of test geometries for pickling, # and setting the SRID on some of them. def get_geoms(lst, srid=None): return [GEOSGeometry(tg.wkt, srid) for tg in lst] tgeoms = get_geoms(self.geometries.points) tgeoms.extend(get_geoms(self.geometries.multilinestrings, 4326)) tgeoms.extend(get_geoms(self.geometries.polygons, 3084)) tgeoms.extend(get_geoms(self.geometries.multipolygons, 3857)) tgeoms.append(Point(srid=4326)) tgeoms.append(Point()) for geom in tgeoms: s1 = pickle.dumps(geom) g1 = pickle.loads(s1) self.assertEqual(geom, g1) self.assertEqual(geom.srid, g1.srid) def test_prepared(self): "Testing PreparedGeometry support." # Creating a simple multipolygon and getting a prepared version. mpoly = GEOSGeometry( "MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))" ) prep = mpoly.prepared # A set of test points. pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)] for pnt in pnts: # Results should be the same (but faster) self.assertEqual(mpoly.contains(pnt), prep.contains(pnt)) self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt)) self.assertEqual(mpoly.covers(pnt), prep.covers(pnt)) self.assertTrue(prep.crosses(fromstr("LINESTRING(1 1, 15 15)"))) self.assertTrue(prep.disjoint(Point(-5, -5))) poly = Polygon(((-1, -1), (1, 1), (1, 0), (-1, -1))) self.assertTrue(prep.overlaps(poly)) poly = Polygon(((-5, 0), (-5, 5), (0, 5), (-5, 0))) self.assertTrue(prep.touches(poly)) poly = Polygon(((-1, -1), (-1, 11), (11, 11), (11, -1), (-1, -1))) self.assertTrue(prep.within(poly)) # Original geometry deletion should not crash the prepared one (#21662) del mpoly self.assertTrue(prep.covers(Point(5, 5))) def test_line_merge(self): "Testing line merge support" ref_geoms = ( fromstr("LINESTRING(1 1, 1 1, 3 3)"), fromstr("MULTILINESTRING((1 1, 3 3), (3 3, 4 2))"), ) ref_merged = ( fromstr("LINESTRING(1 1, 3 3)"), fromstr("LINESTRING (1 1, 3 3, 4 2)"), ) for geom, merged in zip(ref_geoms, ref_merged): self.assertEqual(merged, geom.merged) def test_valid_reason(self): "Testing IsValidReason support" g = GEOSGeometry("POINT(0 0)") self.assertTrue(g.valid) self.assertIsInstance(g.valid_reason, str) self.assertEqual(g.valid_reason, "Valid Geometry") g = GEOSGeometry("LINESTRING(0 0, 0 0)") self.assertFalse(g.valid) self.assertIsInstance(g.valid_reason, str) self.assertTrue( g.valid_reason.startswith("Too few points in geometry component") ) def test_linearref(self): "Testing linear referencing" ls = fromstr("LINESTRING(0 0, 0 10, 10 10, 10 0)") mls = fromstr("MULTILINESTRING((0 0, 0 10), (10 0, 10 10))") self.assertEqual(ls.project(Point(0, 20)), 10.0) self.assertEqual(ls.project(Point(7, 6)), 24) self.assertEqual(ls.project_normalized(Point(0, 20)), 1.0 / 3) self.assertEqual(ls.interpolate(10), Point(0, 10)) self.assertEqual(ls.interpolate(24), Point(10, 6)) self.assertEqual(ls.interpolate_normalized(1.0 / 3), Point(0, 10)) self.assertEqual(mls.project(Point(0, 20)), 10) self.assertEqual(mls.project(Point(7, 6)), 16) self.assertEqual(mls.interpolate(9), Point(0, 9)) self.assertEqual(mls.interpolate(17), Point(10, 7)) def test_deconstructible(self): """ Geometry classes should be deconstructible. """ point = Point(4.337844, 50.827537, srid=4326) path, args, kwargs = point.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.point.Point") self.assertEqual(args, (4.337844, 50.827537)) self.assertEqual(kwargs, {"srid": 4326}) ls = LineString(((0, 0), (1, 1))) path, args, kwargs = ls.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LineString") self.assertEqual(args, (((0, 0), (1, 1)),)) self.assertEqual(kwargs, {}) ls2 = LineString([Point(0, 0), Point(1, 1)], srid=4326) path, args, kwargs = ls2.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LineString") self.assertEqual(args, ([Point(0, 0), Point(1, 1)],)) self.assertEqual(kwargs, {"srid": 4326}) ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4)) poly = Polygon(ext_coords, int_coords) path, args, kwargs = poly.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.polygon.Polygon") self.assertEqual(args, (ext_coords, int_coords)) self.assertEqual(kwargs, {}) lr = LinearRing((0, 0), (0, 1), (1, 1), (0, 0)) path, args, kwargs = lr.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LinearRing") self.assertEqual(args, ((0, 0), (0, 1), (1, 1), (0, 0))) self.assertEqual(kwargs, {}) mp = MultiPoint(Point(0, 0), Point(1, 1)) path, args, kwargs = mp.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiPoint") self.assertEqual(args, (Point(0, 0), Point(1, 1))) self.assertEqual(kwargs, {}) ls1 = LineString((0, 0), (1, 1)) ls2 = LineString((2, 2), (3, 3)) mls = MultiLineString(ls1, ls2) path, args, kwargs = mls.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiLineString") self.assertEqual(args, (ls1, ls2)) self.assertEqual(kwargs, {}) p1 = Polygon(((0, 0), (0, 1), (1, 1), (0, 0))) p2 = Polygon(((1, 1), (1, 2), (2, 2), (1, 1))) mp = MultiPolygon(p1, p2) path, args, kwargs = mp.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiPolygon") self.assertEqual(args, (p1, p2)) self.assertEqual(kwargs, {}) poly = Polygon(((0, 0), (0, 1), (1, 1), (0, 0))) gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly) path, args, kwargs = gc.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.GeometryCollection") self.assertEqual( args, (Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly) ) self.assertEqual(kwargs, {}) def test_subclassing(self): """ GEOSGeometry subclass may itself be subclassed without being forced-cast to the parent class during `__init__`. """ class ExtendedPolygon(Polygon): def __init__(self, *args, data=0, **kwargs): super().__init__(*args, **kwargs) self._data = data def __str__(self): return "EXT_POLYGON - data: %d - %s" % (self._data, self.wkt) ext_poly = ExtendedPolygon(((0, 0), (0, 1), (1, 1), (0, 0)), data=3) self.assertEqual(type(ext_poly), ExtendedPolygon) # ExtendedPolygon.__str__ should be called (instead of Polygon.__str__). self.assertEqual( str(ext_poly), "EXT_POLYGON - data: 3 - POLYGON ((0 0, 0 1, 1 1, 0 0))" ) self.assertJSONEqual( ext_poly.json, '{"coordinates": [[[0, 0], [0, 1], [1, 1], [0, 0]]], "type": "Polygon"}', ) def test_geos_version_tuple(self): versions = ( (b"3.0.0rc4-CAPI-1.3.3", (3, 0, 0)), (b"3.0.0-CAPI-1.4.1", (3, 0, 0)), (b"3.4.0dev-CAPI-1.8.0", (3, 4, 0)), (b"3.4.0dev-CAPI-1.8.0 r0", (3, 4, 0)), (b"3.6.2-CAPI-1.10.2 4d2925d6", (3, 6, 2)), ) for version_string, version_tuple in versions: with self.subTest(version_string=version_string): with mock.patch( "django.contrib.gis.geos.libgeos.geos_version", lambda: version_string, ): self.assertEqual(geos_version_tuple(), version_tuple) def test_from_gml(self): self.assertEqual( GEOSGeometry("POINT(0 0)"), GEOSGeometry.from_gml( '<gml:Point gml:id="p21" ' 'srsName="http://www.opengis.net/def/crs/EPSG/0/4326">' ' <gml:pos srsDimension="2">0 0</gml:pos>' "</gml:Point>" ), ) def test_from_ewkt(self): self.assertEqual( GEOSGeometry.from_ewkt("SRID=1;POINT(1 1)"), Point(1, 1, srid=1) ) self.assertEqual(GEOSGeometry.from_ewkt("POINT(1 1)"), Point(1, 1)) def test_from_ewkt_empty_string(self): msg = "Expected WKT but got an empty string." with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("") with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRID=1;") def test_from_ewkt_invalid_srid(self): msg = "EWKT has invalid SRID part." with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRUD=1;POINT(1 1)") with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRID=WGS84;POINT(1 1)") def test_fromstr_scientific_wkt(self): self.assertEqual(GEOSGeometry("POINT(1.0e-1 1.0e+1)"), Point(0.1, 10)) def test_normalize(self): g = MultiPoint(Point(0, 0), Point(2, 2), Point(1, 1)) self.assertIsNone(g.normalize()) self.assertTrue( g.equals_exact(MultiPoint(Point(2, 2), Point(1, 1), Point(0, 0))) ) @skipIf(geos_version_tuple() < (3, 8), "GEOS >= 3.8.0 is required") def test_make_valid(self): poly = GEOSGeometry("POLYGON((0 0, 0 23, 23 0, 23 23, 0 0))") self.assertIs(poly.valid, False) valid_poly = poly.make_valid() self.assertIs(valid_poly.valid, True) self.assertNotEqual(valid_poly, poly) valid_poly2 = valid_poly.make_valid() self.assertIs(valid_poly2.valid, True) self.assertEqual(valid_poly, valid_poly2) @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.7.3") def test_make_valid_geos_version(self): msg = "GEOSGeometry.make_valid() requires GEOS >= 3.8.0." poly = GEOSGeometry("POLYGON((0 0, 0 23, 23 0, 23 23, 0 0))") with self.assertRaisesMessage(GEOSException, msg): poly.make_valid() def test_empty_point(self): p = Point(srid=4326) self.assertEqual(p.ogr.ewkt, p.ewkt) self.assertEqual(p.transform(2774, clone=True), Point(srid=2774)) p.transform(2774) self.assertEqual(p, Point(srid=2774)) def test_linestring_iter(self): ls = LineString((0, 0), (1, 1)) it = iter(ls) # Step into CoordSeq iterator. next(it) ls[:] = [] with self.assertRaises(IndexError): next(it)
7a96b417f921d1ed998b261f67d405f444442292236d3ef1f56ccfee3ca0536c
from django.contrib.gis.db.models import Collect, Count, Extent, F, Union from django.contrib.gis.geos import GEOSGeometry, MultiPoint, Point from django.db import NotSupportedError, connection from django.test import TestCase, skipUnlessDBFeature from django.test.utils import override_settings from django.utils import timezone from .models import Article, Author, Book, City, DirectoryEntry, Event, Location, Parcel class RelatedGeoModelTest(TestCase): fixtures = ["initial"] def test02_select_related(self): "Testing `select_related` on geographic models (see #7126)." qs1 = City.objects.order_by("id") qs2 = City.objects.order_by("id").select_related() qs3 = City.objects.order_by("id").select_related("location") # Reference data for what's in the fixtures. cities = ( ("Aurora", "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, 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.point.y, 6) @skipUnlessDBFeature("supports_extent_aggr") def test_related_extent_aggregate(self): "Testing the `Extent` aggregate on related geographic models." # This combines the Extent and Union aggregates into one query aggs = City.objects.aggregate(Extent("location__point")) # One for all locations, one that excludes New Mexico (Roswell). all_extent = (-104.528056, 29.763374, -79.460734, 40.18476) txpa_extent = (-97.516111, 29.763374, -79.460734, 40.18476) e1 = City.objects.aggregate(Extent("location__point"))[ "location__point__extent" ] e2 = City.objects.exclude(state="NM").aggregate(Extent("location__point"))[ "location__point__extent" ] e3 = aggs["location__point__extent"] # The tolerance value is to four decimal places because of differences # between the Oracle and PostGIS spatial backends on the extent calculation. tol = 4 for ref, e in [(all_extent, e1), (txpa_extent, e2), (all_extent, e3)]: for ref_val, e_val in zip(ref, e): self.assertAlmostEqual(ref_val, e_val, tol) @skipUnlessDBFeature("supports_extent_aggr") def test_related_extent_annotate(self): """ Test annotation with Extent GeoAggregate. """ cities = City.objects.annotate( points_extent=Extent("location__point") ).order_by("name") tol = 4 self.assertAlmostEqual( cities[0].points_extent, (-97.516111, 33.058333, -97.516111, 33.058333), tol ) @skipUnlessDBFeature("supports_union_aggr") def test_related_union_aggregate(self): "Testing the `Union` aggregate on related geographic models." # This combines the Extent and Union aggregates into one query aggs = City.objects.aggregate(Union("location__point")) # These are the points that are components of the aggregate geographic # union that is returned. Each point # corresponds to City PK. p1 = Point(-104.528056, 33.387222) p2 = Point(-97.516111, 33.058333) p3 = Point(-79.460734, 40.18476) p4 = Point(-96.801611, 32.782057) p5 = Point(-95.363151, 29.763374) # The second union aggregate is for a union # query that includes limiting information in the WHERE clause (in other # words a `.filter()` precedes the call to `.aggregate(Union()`). ref_u1 = MultiPoint(p1, p2, p4, p5, p3, srid=4326) ref_u2 = MultiPoint(p2, p3, srid=4326) u1 = City.objects.aggregate(Union("location__point"))["location__point__union"] u2 = City.objects.exclude( name__in=("Roswell", "Houston", "Dallas", "Fort Worth"), ).aggregate(Union("location__point"))["location__point__union"] u3 = aggs["location__point__union"] self.assertEqual(type(u1), MultiPoint) self.assertEqual(type(u3), MultiPoint) # Ordering of points in the result of the union is not defined and # implementation-dependent (DB backend, GEOS version) self.assertEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u1}) self.assertEqual({p.ewkt for p in ref_u2}, {p.ewkt for p in u2}) self.assertEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u3}) def test05_select_related_fk_to_subclass(self): """ select_related on a query over a model with an FK to a model subclass. """ # Regression test for #9752. list(DirectoryEntry.objects.select_related()) def test06_f_expressions(self): "Testing F() expressions on GeometryFields." # Constructing a dummy parcel border and getting the City instance for # assigning the FK. b1 = GEOSGeometry( "POLYGON((-97.501205 33.052520,-97.501205 33.052576," "-97.501150 33.052576,-97.501150 33.052520,-97.501205 33.052520))", srid=4326, ) pcity = City.objects.get(name="Aurora") # First parcel has incorrect center point that is equal to the City; # it also has a second border that is different from the first as a # 100ft buffer around the City. c1 = pcity.location.point c2 = c1.transform(2276, clone=True) b2 = c2.buffer(100) Parcel.objects.create( name="P1", city=pcity, center1=c1, center2=c2, border1=b1, border2=b2 ) # Now creating a second Parcel where the borders are the same, just # in different coordinate systems. The center points are also the # same (but in different coordinate systems), and this time they # actually correspond to the centroid of the border. c1 = b1.centroid c2 = c1.transform(2276, clone=True) b2 = ( b1 if connection.features.supports_transform else b1.transform(2276, clone=True) ) Parcel.objects.create( name="P2", city=pcity, center1=c1, center2=c2, border1=b1, border2=b2 ) # Should return the second Parcel, which has the center within the # border. qs = Parcel.objects.filter(center1__within=F("border1")) self.assertEqual(1, len(qs)) self.assertEqual("P2", qs[0].name) # This time center2 is in a different coordinate system and needs to be # wrapped in transformation SQL. qs = Parcel.objects.filter(center2__within=F("border1")) if connection.features.supports_transform: self.assertEqual("P2", qs.get().name) else: msg = "This backend doesn't support the Transform function." with self.assertRaisesMessage(NotSupportedError, msg): list(qs) # Should return the first Parcel, which has the center point equal # to the point in the City ForeignKey. qs = Parcel.objects.filter(center1=F("city__location__point")) self.assertEqual(1, len(qs)) self.assertEqual("P1", qs[0].name) # This time the city column should be wrapped in transformation SQL. qs = Parcel.objects.filter(border2__contains=F("city__location__point")) if connection.features.supports_transform: self.assertEqual("P1", qs.get().name) else: msg = "This backend doesn't support the Transform function." with self.assertRaisesMessage(NotSupportedError, msg): list(qs) def test07_values(self): "Testing values() and values_list()." gqs = Location.objects.all() gvqs = Location.objects.values() gvlqs = Location.objects.values_list() # Incrementing through each of the models, dictionaries, and tuples # returned by each QuerySet. for m, d, t in zip(gqs, gvqs, gvlqs): # The values should be Geometry objects and not raw strings returned # by the spatial database. self.assertIsInstance(d["point"], GEOSGeometry) self.assertIsInstance(t[1], GEOSGeometry) self.assertEqual(m.point, d["point"]) self.assertEqual(m.point, t[1]) @override_settings(USE_TZ=True) def test_07b_values(self): "Testing values() and values_list() with aware datetime. See #21565." Event.objects.create(name="foo", when=timezone.now()) list(Event.objects.values_list("when")) def test08_defer_only(self): "Testing defer() and only() on Geographic models." qs = Location.objects.all() def_qs = Location.objects.defer("point") for loc, def_loc in zip(qs, def_qs): self.assertEqual(loc.point, def_loc.point) def test09_pk_relations(self): "Ensuring correct primary key column is selected across relations. See #10757." # The expected ID values -- notice the last two location IDs # are out of order. Dallas and Houston have location IDs that differ # from their PKs -- this is done to ensure that the related location # ID column is selected instead of ID column for the city. city_ids = (1, 2, 3, 4, 5) loc_ids = (1, 2, 3, 5, 4) ids_qs = City.objects.order_by("id").values("id", "location__id") for val_dict, c_id, l_id in zip(ids_qs, city_ids, loc_ids): self.assertEqual(val_dict["id"], c_id) self.assertEqual(val_dict["location__id"], l_id) def test10_combine(self): "Testing the combination of two QuerySets (#10807)." buf1 = City.objects.get(name="Aurora").location.point.buffer(0.1) buf2 = City.objects.get(name="Kecksburg").location.point.buffer(0.1) qs1 = City.objects.filter(location__point__within=buf1) qs2 = City.objects.filter(location__point__within=buf2) combined = qs1 | qs2 names = [c.name for c in combined] self.assertEqual(2, len(names)) self.assertIn("Aurora", names) self.assertIn("Kecksburg", names) @skipUnlessDBFeature("allows_group_by_lob") def test12a_count(self): "Testing `Count` aggregate on geo-fields." # The City, 'Fort Worth' uses the same location as Dallas. dallas = City.objects.get(name="Dallas") # Count annotation should be 2 for the Dallas location now. loc = Location.objects.annotate(num_cities=Count("city")).get( id=dallas.location.id ) self.assertEqual(2, loc.num_cities) def test12b_count(self): "Testing `Count` aggregate on non geo-fields." # Should only be one author (Trevor Paglen) returned by this query, and # the annotation should have 3 for the number of books, see #11087. # Also testing with a values(), see #11489. qs = Author.objects.annotate(num_books=Count("books")).filter(num_books__gt=1) vqs = ( Author.objects.values("name") .annotate(num_books=Count("books")) .filter(num_books__gt=1) ) self.assertEqual(1, len(qs)) self.assertEqual(3, qs[0].num_books) self.assertEqual(1, len(vqs)) self.assertEqual(3, vqs[0]["num_books"]) @skipUnlessDBFeature("allows_group_by_lob") def test13c_count(self): "Testing `Count` aggregate with `.values()`. See #15305." qs = ( Location.objects.filter(id=5) .annotate(num_cities=Count("city")) .values("id", "point", "num_cities") ) self.assertEqual(1, len(qs)) self.assertEqual(2, qs[0]["num_cities"]) self.assertIsInstance(qs[0]["point"], GEOSGeometry) def test13_select_related_null_fk(self): "Testing `select_related` on a nullable ForeignKey." Book.objects.create(title="Without Author") b = Book.objects.select_related("author").get(title="Without Author") # Should be `None`, and not a 'dummy' model. self.assertIsNone(b.author) @skipUnlessDBFeature("supports_collect_aggr") def test_collect(self): """ Testing the `Collect` aggregate. """ # Reference query: # SELECT AsText(ST_Collect("relatedapp_location"."point")) # FROM "relatedapp_city" # LEFT OUTER JOIN # "relatedapp_location" ON ( # "relatedapp_city"."location_id" = "relatedapp_location"."id" # ) # WHERE "relatedapp_city"."state" = 'TX'; ref_geom = GEOSGeometry( "MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057," "-95.363151 29.763374,-96.801611 32.782057)" ) coll = City.objects.filter(state="TX").aggregate(Collect("location__point"))[ "location__point__collect" ] # Even though Dallas and Ft. Worth share same point, Collect doesn't # consolidate -- that's why 4 points in MultiPoint. self.assertEqual(4, len(coll)) self.assertTrue(ref_geom.equals(coll)) def test15_invalid_select_related(self): """ select_related on the related name manager of a unique FK. """ qs = Article.objects.select_related("author__article") # This triggers TypeError when `get_default_columns` has no `local_only` # keyword. The TypeError is swallowed if QuerySet is actually # evaluated as list generation swallows TypeError in CPython. str(qs.query) def test16_annotated_date_queryset(self): "Ensure annotated date querysets work if spatial backend is used. See #14648." birth_years = [ dt.year for dt in list( Author.objects.annotate(num_books=Count("books")).dates("dob", "year") ) ] birth_years.sort() self.assertEqual([1950, 1974], birth_years) # TODO: Related tests for KML, GML, and distance lookups.
07cc39282882e61339e79b1746104e360708f96c7ffd74025aba697851ceae12
from django.contrib.gis.db 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) location = models.ForeignKey(Location, models.CASCADE) def __str__(self): return self.name class AugmentedLocation(Location): extra_text = models.TextField(blank=True) 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) 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.PolygonField(srid=2276) def __str__(self): return self.name class Author(SimpleModel): name = models.CharField(max_length=100) dob = models.DateField() class Article(SimpleModel): title = models.CharField(max_length=100) author = models.ForeignKey(Author, models.CASCADE, unique=True) class Book(SimpleModel): title = models.CharField(max_length=100) author = models.ForeignKey(Author, models.SET_NULL, related_name="books", null=True) class Event(SimpleModel): name = models.CharField(max_length=100) when = models.DateTimeField()
e9d218b7d5a77ea247260e972ccc0e0d48f1ff6bdbf659a182b9acd8edf327b4
import os import shutil import struct import tempfile import zipfile from unittest import mock from django.contrib.gis.gdal import GDALRaster, SpatialReference from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.raster.band import GDALBand from django.contrib.gis.shortcuts import numpy from django.test import SimpleTestCase from ..data.rasters.textrasters import JSON_RASTER class GDALRasterTests(SimpleTestCase): """ Test a GDALRaster instance created from a file (GeoTiff). """ def setUp(self): self.rs_path = os.path.join( os.path.dirname(__file__), "../data/rasters/raster.tif" ) self.rs = GDALRaster(self.rs_path) def test_rs_name_repr(self): self.assertEqual(self.rs_path, self.rs.name) self.assertRegex(repr(self.rs), r"<Raster object at 0x\w+>") def test_rs_driver(self): self.assertEqual(self.rs.driver.name, "GTiff") def test_rs_size(self): self.assertEqual(self.rs.width, 163) self.assertEqual(self.rs.height, 174) def test_rs_srs(self): self.assertEqual(self.rs.srs.srid, 3086) self.assertEqual(self.rs.srs.units, (1.0, "metre")) def test_rs_srid(self): rast = GDALRaster( { "width": 16, "height": 16, "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.geotransform, [511700.4680706557, 100.0, 0.0, 435103.3771231986, 0.0, -100.0], ) self.assertEqual(self.rs.origin, [511700.4680706557, 435103.3771231986]) self.assertEqual(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.assertEqual(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_RASTER) # geotransform accepts both floats and ints rsmem.geotransform = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] self.assertEqual(rsmem.geotransform, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) rsmem.geotransform = range(6) self.assertEqual(rsmem.geotransform, [float(x) for x in range(6)]) self.assertEqual(rsmem.origin, [0, 3]) self.assertEqual(rsmem.origin.x, 0) self.assertEqual(rsmem.origin.y, 3) self.assertEqual(rsmem.scale, [1, 5]) self.assertEqual(rsmem.scale.x, 1) self.assertEqual(rsmem.scale.y, 5) self.assertEqual(rsmem.skew, [2, 4]) self.assertEqual(rsmem.skew.x, 2) self.assertEqual(rsmem.skew.y, 4) self.assertEqual(rsmem.width, 5) self.assertEqual(rsmem.height, 5) def test_geotransform_bad_inputs(self): rsmem = GDALRaster(JSON_RASTER) error_geotransforms = [ [1, 2], [1, 2, 3, 4, 5, "foo"], [1, 2, 3, 4, 5, 6, "foo"], ] msg = "Geotransform must consist of 6 numeric values." for geotransform in error_geotransforms: with self.subTest(i=geotransform), self.assertRaisesMessage( ValueError, msg ): rsmem.geotransform = geotransform def test_rs_extent(self): self.assertEqual( self.rs.extent, ( 511700.4680706557, 417703.3771231986, 528000.4680706557, 435103.3771231986, ), ) def test_rs_bands(self): self.assertEqual(len(self.rs.bands), 1) self.assertIsInstance(self.rs.bands[0], GDALBand) def test_memory_based_raster_creation(self): # Create uint8 raster with full pixel data range (0-255) rast = GDALRaster( { "datatype": 1, "width": 16, "height": 16, "srid": 4326, "bands": [ { "data": range(256), "nodata_value": 255, } ], } ) # Get array from raster result = rast.bands[0].data() if numpy: result = result.flatten().tolist() # Assert data is same as original input self.assertEqual(result, list(range(256))) def test_file_based_raster_creation(self): # Prepare tempfile rstfile = tempfile.NamedTemporaryFile(suffix=".tif") # Create file-based raster from scratch GDALRaster( { "datatype": self.rs.bands[0].datatype(), "driver": "tif", "name": rstfile.name, "width": 163, "height": 174, "nr_of_bands": 1, "srid": self.rs.srs.wkt, "origin": (self.rs.origin.x, self.rs.origin.y), "scale": (self.rs.scale.x, self.rs.scale.y), "skew": (self.rs.skew.x, self.rs.skew.y), "bands": [ { "data": self.rs.bands[0].data(), "nodata_value": self.rs.bands[0].nodata_value, } ], } ) # Reload newly created raster from file restored_raster = GDALRaster(rstfile.name) # Presence of TOWGS84 depend on GDAL/Proj versions. self.assertEqual( restored_raster.srs.wkt.replace("TOWGS84[0,0,0,0,0,0,0],", ""), self.rs.srs.wkt.replace("TOWGS84[0,0,0,0,0,0,0],", ""), ) self.assertEqual(restored_raster.geotransform, self.rs.geotransform) if numpy: numpy.testing.assert_equal( restored_raster.bands[0].data(), self.rs.bands[0].data() ) else: self.assertEqual(restored_raster.bands[0].data(), self.rs.bands[0].data()) def test_nonexistent_file(self): msg = 'Unable to read raster source input "nonexistent.tif".' with self.assertRaisesMessage(GDALException, msg): GDALRaster("nonexistent.tif") def test_vsi_raster_creation(self): # Open a raster as a file object. with open(self.rs_path, "rb") as dat: # Instantiate a raster from the file binary buffer. vsimem = GDALRaster(dat.read()) # The data of the in-memory file is equal to the source file. result = vsimem.bands[0].data() target = self.rs.bands[0].data() if numpy: result = result.flatten().tolist() target = target.flatten().tolist() self.assertEqual(result, target) def test_vsi_raster_deletion(self): path = "/vsimem/raster.tif" # Create a vsi-based raster from scratch. vsimem = GDALRaster( { "name": path, "driver": "tif", "width": 4, "height": 4, "srid": 4326, "bands": [ { "data": range(16), } ], } ) # The virtual file exists. rst = GDALRaster(path) self.assertEqual(rst.width, 4) # Delete GDALRaster. del vsimem del rst # The virtual file has been removed. msg = 'Could not open the datasource at "/vsimem/raster.tif"' with self.assertRaisesMessage(GDALException, msg): GDALRaster(path) def test_vsi_invalid_buffer_error(self): msg = "Failed creating VSI raster from the input buffer." with self.assertRaisesMessage(GDALException, msg): GDALRaster(b"not-a-raster-buffer") def test_vsi_buffer_property(self): # Create a vsi-based raster from scratch. rast = GDALRaster( { "name": "/vsimem/raster.tif", "driver": "tif", "width": 4, "height": 4, "srid": 4326, "bands": [ { "data": range(16), } ], } ) # Do a round trip from raster to buffer to raster. result = GDALRaster(rast.vsi_buffer).bands[0].data() if numpy: result = result.flatten().tolist() # Band data is equal to nodata value except on input block of ones. self.assertEqual(result, list(range(16))) # The vsi buffer is None for rasters that are not vsi based. self.assertIsNone(self.rs.vsi_buffer) def test_vsi_vsizip_filesystem(self): rst_zipfile = tempfile.NamedTemporaryFile(suffix=".zip") with zipfile.ZipFile(rst_zipfile, mode="w") as zf: zf.write(self.rs_path, "raster.tif") rst_path = "/vsizip/" + os.path.join(rst_zipfile.name, "raster.tif") rst = GDALRaster(rst_path) self.assertEqual(rst.driver.name, self.rs.driver.name) self.assertEqual(rst.name, rst_path) self.assertIs(rst.is_vsi_based, True) self.assertIsNone(rst.vsi_buffer) def test_offset_size_and_shape_on_raster_creation(self): rast = GDALRaster( { "datatype": 1, "width": 4, "height": 4, "srid": 4326, "bands": [ { "data": (1,), "offset": (1, 1), "size": (2, 2), "shape": (1, 1), "nodata_value": 2, } ], } ) # Get array from raster. result = rast.bands[0].data() if numpy: result = result.flatten().tolist() # Band data is equal to nodata value except on input block of ones. self.assertEqual(result, [2, 2, 2, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 2, 2, 2]) def test_set_nodata_value_on_raster_creation(self): # Create raster filled with nodata values. rast = GDALRaster( { "datatype": 1, "width": 2, "height": 2, "srid": 4326, "bands": [{"nodata_value": 23}], } ) # Get array from raster. result = rast.bands[0].data() if numpy: result = result.flatten().tolist() # All band data is equal to nodata value. self.assertEqual(result, [23] * 4) def test_set_nodata_none_on_raster_creation(self): # Create raster without data and without nodata value. rast = GDALRaster( { "datatype": 1, "width": 2, "height": 2, "srid": 4326, "bands": [{"nodata_value": None}], } ) # Get array from raster. result = rast.bands[0].data() if numpy: result = result.flatten().tolist() # Band data is equal to zero because no nodata value has been specified. self.assertEqual(result, [0] * 4) def test_raster_metadata_property(self): data = self.rs.metadata self.assertEqual(data["DEFAULT"], {"AREA_OR_POINT": "Area"}) self.assertEqual(data["IMAGE_STRUCTURE"], {"INTERLEAVE": "BAND"}) # Create file-based raster from scratch source = GDALRaster( { "datatype": 1, "width": 2, "height": 2, "srid": 4326, "bands": [{"data": range(4), "nodata_value": 99}], } ) # Set metadata on raster and on a band. metadata = { "DEFAULT": {"OWNER": "Django", "VERSION": "1.0", "AREA_OR_POINT": "Point"}, } source.metadata = metadata source.bands[0].metadata = metadata self.assertEqual(source.metadata["DEFAULT"], metadata["DEFAULT"]) self.assertEqual(source.bands[0].metadata["DEFAULT"], metadata["DEFAULT"]) # Update metadata on raster. metadata = { "DEFAULT": {"VERSION": "2.0"}, } source.metadata = metadata self.assertEqual(source.metadata["DEFAULT"]["VERSION"], "2.0") # Remove metadata on raster. metadata = { "DEFAULT": {"OWNER": None}, } source.metadata = metadata self.assertNotIn("OWNER", source.metadata["DEFAULT"]) def test_raster_info_accessor(self): infos = self.rs.info # Data info_lines = [line.strip() for line in infos.split("\n") if line.strip() != ""] for line in [ "Driver: GTiff/GeoTIFF", "Files: {}".format(self.rs_path), "Size is 163, 174", "Origin = (511700.468070655711927,435103.377123198588379)", "Pixel Size = (100.000000000000000,-100.000000000000000)", "Metadata:", "AREA_OR_POINT=Area", "Image Structure Metadata:", "INTERLEAVE=BAND", "Band 1 Block=163x50 Type=Byte, ColorInterp=Gray", "NoData Value=15", ]: self.assertIn(line, info_lines) for line in [ r"Upper Left \( 511700.468, 435103.377\) " r'\( 82d51\'46.1\d"W, 27d55\' 1.5\d"N\)', r"Lower Left \( 511700.468, 417703.377\) " r'\( 82d51\'52.0\d"W, 27d45\'37.5\d"N\)', r"Upper Right \( 528000.468, 435103.377\) " r'\( 82d41\'48.8\d"W, 27d54\'56.3\d"N\)', r"Lower Right \( 528000.468, 417703.377\) " r'\( 82d41\'55.5\d"W, 27d45\'32.2\d"N\)', r"Center \( 519850.468, 426403.377\) " r'\( 82d46\'50.6\d"W, 27d50\'16.9\d"N\)', ]: self.assertRegex(infos, line) # CRS (skip the name because string depends on the GDAL/Proj versions). self.assertIn("NAD83 / Florida GDL Albers", infos) def test_compressed_file_based_raster_creation(self): rstfile = tempfile.NamedTemporaryFile(suffix=".tif") # Make a compressed copy of an existing raster. compressed = self.rs.warp( {"papsz_options": {"compress": "packbits"}, "name": rstfile.name} ) # Check physically if compression worked. self.assertLess(os.path.getsize(compressed.name), os.path.getsize(self.rs.name)) # Create file-based raster with options from scratch. compressed = GDALRaster( { "datatype": 1, "driver": "tif", "name": rstfile.name, "width": 40, "height": 40, "srid": 3086, "origin": (500000, 400000), "scale": (100, -100), "skew": (0, 0), "bands": [ { "data": range(40 ^ 2), "nodata_value": 255, } ], "papsz_options": { "compress": "packbits", "pixeltype": "signedbyte", "blockxsize": 23, "blockysize": 23, }, } ) # Check if options used on creation are stored in metadata. # Reopening the raster ensures that all metadata has been written # to the file. compressed = GDALRaster(compressed.name) self.assertEqual( compressed.metadata["IMAGE_STRUCTURE"]["COMPRESSION"], "PACKBITS", ) self.assertEqual( compressed.bands[0].metadata["IMAGE_STRUCTURE"]["PIXELTYPE"], "SIGNEDBYTE" ) self.assertIn("Block=40x23", compressed.info) def test_raster_warp(self): # Create in memory raster source = GDALRaster( { "datatype": 1, "driver": "MEM", "name": "sourceraster", "width": 4, "height": 4, "nr_of_bands": 1, "srid": 3086, "origin": (500000, 400000), "scale": (100, -100), "skew": (0, 0), "bands": [ { "data": range(16), "nodata_value": 255, } ], } ) # Test altering the scale, width, and height of a raster data = { "scale": [200, -200], "width": 2, "height": 2, } target = source.warp(data) self.assertEqual(target.width, data["width"]) self.assertEqual(target.height, data["height"]) self.assertEqual(target.scale, data["scale"]) self.assertEqual(target.bands[0].datatype(), source.bands[0].datatype()) self.assertEqual(target.name, "sourceraster_copy.MEM") result = target.bands[0].data() if numpy: result = result.flatten().tolist() self.assertEqual(result, [5, 7, 13, 15]) # Test altering the name and datatype (to float) data = { "name": "/path/to/targetraster.tif", "datatype": 6, } target = source.warp(data) self.assertEqual(target.bands[0].datatype(), 6) self.assertEqual(target.name, "/path/to/targetraster.tif") self.assertEqual(target.driver.name, "MEM") result = target.bands[0].data() if numpy: result = result.flatten().tolist() self.assertEqual( result, [ 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, ], ) def test_raster_warp_nodata_zone(self): # Create in memory raster. source = GDALRaster( { "datatype": 1, "driver": "MEM", "width": 4, "height": 4, "srid": 3086, "origin": (500000, 400000), "scale": (100, -100), "skew": (0, 0), "bands": [ { "data": range(16), "nodata_value": 23, } ], } ) # Warp raster onto a location that does not cover any pixels of the original. result = source.warp({"origin": (200000, 200000)}).bands[0].data() if numpy: result = result.flatten().tolist() # The result is an empty raster filled with the correct nodata value. self.assertEqual(result, [23] * 16) def test_raster_clone(self): rstfile = tempfile.NamedTemporaryFile(suffix=".tif") tests = [ ("MEM", "", 23), # In memory raster. ("tif", rstfile.name, 99), # In file based raster. ] for driver, name, nodata_value in tests: with self.subTest(driver=driver): source = GDALRaster( { "datatype": 1, "driver": driver, "name": name, "width": 4, "height": 4, "srid": 3086, "origin": (500000, 400000), "scale": (100, -100), "skew": (0, 0), "bands": [ { "data": range(16), "nodata_value": nodata_value, } ], } ) clone = source.clone() self.assertNotEqual(clone.name, source.name) self.assertEqual(clone._write, source._write) self.assertEqual(clone.srs.srid, source.srs.srid) self.assertEqual(clone.width, source.width) self.assertEqual(clone.height, source.height) self.assertEqual(clone.origin, source.origin) self.assertEqual(clone.scale, source.scale) self.assertEqual(clone.skew, source.skew) self.assertIsNot(clone, source) def test_raster_transform(self): tests = [ 3086, "3086", SpatialReference(3086), ] for srs in tests: with self.subTest(srs=srs): # Prepare tempfile and nodata value. rstfile = tempfile.NamedTemporaryFile(suffix=".tif") ndv = 99 # Create in file based raster. source = GDALRaster( { "datatype": 1, "driver": "tif", "name": rstfile.name, "width": 5, "height": 5, "nr_of_bands": 1, "srid": 4326, "origin": (-5, 5), "scale": (2, -2), "skew": (0, 0), "bands": [ { "data": range(25), "nodata_value": ndv, } ], } ) target = source.transform(srs) # Reload data from disk. target = GDALRaster(target.name) self.assertEqual(target.srs.srid, 3086) self.assertEqual(target.width, 7) self.assertEqual(target.height, 7) self.assertEqual(target.bands[0].datatype(), source.bands[0].datatype()) self.assertAlmostEqual(target.origin[0], 9124842.791079799, 3) self.assertAlmostEqual(target.origin[1], 1589911.6476407414, 3) self.assertAlmostEqual(target.scale[0], 223824.82664250192, 3) self.assertAlmostEqual(target.scale[1], -223824.82664250192, 3) self.assertEqual(target.skew, [0, 0]) result = target.bands[0].data() if numpy: result = result.flatten().tolist() # The reprojection of a raster that spans over a large area # skews the data matrix and might introduce nodata values. self.assertEqual( result, [ ndv, ndv, ndv, ndv, 4, ndv, ndv, ndv, ndv, 2, 3, 9, ndv, ndv, ndv, 1, 2, 8, 13, 19, ndv, 0, 6, 6, 12, 18, 18, 24, ndv, 10, 11, 16, 22, 23, ndv, ndv, ndv, 15, 21, 22, ndv, ndv, ndv, ndv, 20, ndv, ndv, ndv, ndv, ], ) def test_raster_transform_clone(self): with mock.patch.object(GDALRaster, "clone") as mocked_clone: # Create in file based raster. rstfile = tempfile.NamedTemporaryFile(suffix=".tif") source = GDALRaster( { "datatype": 1, "driver": "tif", "name": rstfile.name, "width": 5, "height": 5, "nr_of_bands": 1, "srid": 4326, "origin": (-5, 5), "scale": (2, -2), "skew": (0, 0), "bands": [ { "data": range(25), "nodata_value": 99, } ], } ) # transform() returns a clone because it is the same SRID and # driver. source.transform(4326) self.assertEqual(mocked_clone.call_count, 1) def test_raster_transform_clone_name(self): # Create in file based raster. rstfile = tempfile.NamedTemporaryFile(suffix=".tif") source = GDALRaster( { "datatype": 1, "driver": "tif", "name": rstfile.name, "width": 5, "height": 5, "nr_of_bands": 1, "srid": 4326, "origin": (-5, 5), "scale": (2, -2), "skew": (0, 0), "bands": [ { "data": range(25), "nodata_value": 99, } ], } ) clone_name = rstfile.name + "_respect_name.GTiff" target = source.transform(4326, name=clone_name) self.assertEqual(target.name, clone_name) class GDALBandTests(SimpleTestCase): rs_path = os.path.join(os.path.dirname(__file__), "../data/rasters/raster.tif") def test_band_data(self): rs = GDALRaster(self.rs_path) band = rs.bands[0] self.assertEqual(band.width, 163) self.assertEqual(band.height, 174) self.assertEqual(band.description, "") self.assertEqual(band.datatype(), 1) self.assertEqual(band.datatype(as_string=True), "GDT_Byte") self.assertEqual(band.color_interp(), 1) self.assertEqual(band.color_interp(as_string=True), "GCI_GrayIndex") self.assertEqual(band.nodata_value, 15) if numpy: data = band.data() assert_array = numpy.loadtxt( os.path.join( os.path.dirname(__file__), "../data/rasters/raster.numpy.txt" ) ) numpy.testing.assert_equal(data, assert_array) self.assertEqual(data.shape, (band.height, band.width)) def test_band_statistics(self): with tempfile.TemporaryDirectory() as tmp_dir: rs_path = os.path.join(tmp_dir, "raster.tif") shutil.copyfile(self.rs_path, rs_path) rs = GDALRaster(rs_path) band = rs.bands[0] pam_file = rs_path + ".aux.xml" smin, smax, smean, sstd = band.statistics(approximate=True) self.assertEqual(smin, 0) self.assertEqual(smax, 9) self.assertAlmostEqual(smean, 2.842331288343558) self.assertAlmostEqual(sstd, 2.3965567248965356) smin, smax, smean, sstd = band.statistics(approximate=False, refresh=True) self.assertEqual(smin, 0) self.assertEqual(smax, 9) self.assertAlmostEqual(smean, 2.828326634228898) self.assertAlmostEqual(sstd, 2.4260526986669095) self.assertEqual(band.min, 0) self.assertEqual(band.max, 9) self.assertAlmostEqual(band.mean, 2.828326634228898) self.assertAlmostEqual(band.std, 2.4260526986669095) # Statistics are persisted into PAM file on band close rs = band = None self.assertTrue(os.path.isfile(pam_file)) def test_read_mode_error(self): # Open raster in read mode rs = GDALRaster(self.rs_path, write=False) band = rs.bands[0] # Setting attributes in write mode raises exception in the _flush method with self.assertRaises(GDALException): setattr(band, "nodata_value", 10) def test_band_data_setters(self): # Create in-memory raster and get band rsmem = GDALRaster( { "datatype": 1, "driver": "MEM", "name": "mem_rst", "width": 10, "height": 10, "nr_of_bands": 1, "srid": 4326, } ) bandmem = rsmem.bands[0] # Set nodata value bandmem.nodata_value = 99 self.assertEqual(bandmem.nodata_value, 99) # Set data for entire dataset bandmem.data(range(100)) if numpy: numpy.testing.assert_equal( bandmem.data(), numpy.arange(100).reshape(10, 10) ) else: self.assertEqual(bandmem.data(), list(range(100))) # Prepare data for setting values in subsequent tests block = list(range(100, 104)) packed_block = struct.pack("<" + "B B B B", *block) # Set data from list bandmem.data(block, (1, 1), (2, 2)) result = bandmem.data(offset=(1, 1), size=(2, 2)) if numpy: numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2)) else: self.assertEqual(result, block) # Set data from packed block bandmem.data(packed_block, (1, 1), (2, 2)) result = bandmem.data(offset=(1, 1), size=(2, 2)) if numpy: numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2)) else: self.assertEqual(result, block) # Set data from bytes bandmem.data(bytes(packed_block), (1, 1), (2, 2)) result = bandmem.data(offset=(1, 1), size=(2, 2)) if numpy: numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2)) else: self.assertEqual(result, block) # Set data from bytearray bandmem.data(bytearray(packed_block), (1, 1), (2, 2)) result = bandmem.data(offset=(1, 1), size=(2, 2)) if numpy: numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2)) else: self.assertEqual(result, block) # Set data from memoryview bandmem.data(memoryview(packed_block), (1, 1), (2, 2)) result = bandmem.data(offset=(1, 1), size=(2, 2)) if numpy: numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2)) else: self.assertEqual(result, block) # Set data from numpy array if numpy: bandmem.data(numpy.array(block, dtype="int8").reshape(2, 2), (1, 1), (2, 2)) numpy.testing.assert_equal( bandmem.data(offset=(1, 1), size=(2, 2)), numpy.array(block).reshape(2, 2), ) # Test json input data rsmemjson = GDALRaster(JSON_RASTER) bandmemjson = rsmemjson.bands[0] if numpy: numpy.testing.assert_equal( bandmemjson.data(), numpy.array(range(25)).reshape(5, 5) ) else: self.assertEqual(bandmemjson.data(), list(range(25))) def test_band_statistics_automatic_refresh(self): rsmem = GDALRaster( { "srid": 4326, "width": 2, "height": 2, "bands": [{"data": [0] * 4, "nodata_value": 99}], } ) band = rsmem.bands[0] # Populate statistics cache self.assertEqual(band.statistics(), (0, 0, 0, 0)) # Change data band.data([1, 1, 0, 0]) # Statistics are properly updated self.assertEqual(band.statistics(), (0.0, 1.0, 0.5, 0.5)) # Change nodata_value band.nodata_value = 0 # Statistics are properly updated self.assertEqual(band.statistics(), (1.0, 1.0, 1.0, 0.0)) def test_band_statistics_empty_band(self): rsmem = GDALRaster( { "srid": 4326, "width": 1, "height": 1, "bands": [{"data": [0], "nodata_value": 0}], } ) self.assertEqual(rsmem.bands[0].statistics(), (None, None, None, None)) def test_band_delete_nodata(self): rsmem = GDALRaster( { "srid": 4326, "width": 1, "height": 1, "bands": [{"data": [0], "nodata_value": 1}], } ) rsmem.bands[0].nodata_value = None self.assertIsNone(rsmem.bands[0].nodata_value) def test_band_data_replication(self): band = GDALRaster( { "srid": 4326, "width": 3, "height": 3, "bands": [{"data": range(10, 19), "nodata_value": 0}], } ).bands[0] # Variations for input (data, shape, expected result). combos = ( ([1], (1, 1), [1] * 9), (range(3), (1, 3), [0, 0, 0, 1, 1, 1, 2, 2, 2]), (range(3), (3, 1), [0, 1, 2, 0, 1, 2, 0, 1, 2]), ) for combo in combos: band.data(combo[0], shape=combo[1]) if numpy: numpy.testing.assert_equal( band.data(), numpy.array(combo[2]).reshape(3, 3) ) else: self.assertEqual(band.data(), list(combo[2]))
6ace37ac6f2ff77b430f34cdd5aa16d10f755c3f664735a33245a25747c121bd
import os import re from datetime import datetime from pathlib import Path from django.contrib.gis.gdal import DataSource, Envelope, GDALException, OGRGeometry from django.contrib.gis.gdal.field import OFTDateTime, OFTInteger, OFTReal, OFTString from django.contrib.gis.geos import GEOSGeometry from django.test import SimpleTestCase from ..test_data import TEST_DATA, TestDS, get_ds_file wgs_84_wkt = ( 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",' '6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",' "0.017453292519943295]]" ) # Using a regex because of small differences depending on GDAL versions. wgs_84_wkt_regex = r'^GEOGCS\["(GCS_)?WGS[ _](19)?84".*$' datetime_format = "%Y-%m-%dT%H:%M:%S" # List of acceptable data sources. ds_list = ( TestDS( "test_point", nfeat=5, nfld=3, geom="POINT", gtype=1, driver="ESRI Shapefile", fields={"dbl": OFTReal, "int": OFTInteger, "str": OFTString}, extent=(-1.35011, 0.166623, -0.524093, 0.824508), # Got extent from QGIS srs_wkt=wgs_84_wkt, field_values={ "dbl": [float(i) for i in range(1, 6)], "int": list(range(1, 6)), "str": [str(i) for i in range(1, 6)], }, fids=range(5), ), TestDS( "test_vrt", ext="vrt", nfeat=3, nfld=3, geom="POINT", gtype="Point25D", driver="OGR_VRT", fields={ "POINT_X": OFTString, "POINT_Y": OFTString, "NUM": OFTString, }, # VRT uses CSV, which all types are OFTString. extent=(1.0, 2.0, 100.0, 523.5), # Min/Max from CSV field_values={ "POINT_X": ["1.0", "5.0", "100.0"], "POINT_Y": ["2.0", "23.0", "523.5"], "NUM": ["5", "17", "23"], }, fids=range(1, 4), ), TestDS( "test_poly", nfeat=3, nfld=3, geom="POLYGON", gtype=3, driver="ESRI Shapefile", fields={"float": OFTReal, "int": OFTInteger, "str": OFTString}, extent=(-1.01513, -0.558245, 0.161876, 0.839637), # Got extent from QGIS srs_wkt=wgs_84_wkt, ), TestDS( "has_nulls", nfeat=3, nfld=6, geom="POLYGON", gtype=3, driver="GeoJSON", ext="geojson", fields={ "uuid": OFTString, "name": OFTString, "num": OFTReal, "integer": OFTInteger, "datetime": OFTDateTime, "boolean": OFTInteger, }, extent=(-75.274200, 39.846504, -74.959717, 40.119040), # Got extent from QGIS field_values={ "uuid": [ "1378c26f-cbe6-44b0-929f-eb330d4991f5", "fa2ba67c-a135-4338-b924-a9622b5d869f", "4494c1f3-55ab-4256-b365-12115cb388d5", ], "name": ["Philadelphia", None, "north"], "num": [1.001, None, 0.0], "integer": [5, None, 8], "boolean": [True, None, False], "datetime": [ datetime.strptime("1994-08-14T11:32:14", datetime_format), None, datetime.strptime("2018-11-29T03:02:52", datetime_format), ], }, fids=range(3), ), ) bad_ds = (TestDS("foo"),) class DataSourceTest(SimpleTestCase): def test01_valid_shp(self): "Testing valid SHP Data Source files." for source in ds_list: # Loading up the data source ds = DataSource(source.ds) # The layer count is what's expected (only 1 layer in a SHP file). self.assertEqual(1, len(ds)) # Making sure GetName works self.assertEqual(source.ds, ds.name) # Making sure the driver name matches up self.assertEqual(source.driver, str(ds.driver)) # Making sure indexing works msg = "Index out of range when accessing layers in a datasource: %s." with self.assertRaisesMessage(IndexError, msg % len(ds)): ds.__getitem__(len(ds)) with self.assertRaisesMessage( IndexError, "Invalid OGR layer name given: invalid." ): ds.__getitem__("invalid") def test_ds_input_pathlib(self): test_shp = Path(get_ds_file("test_point", "shp")) ds = DataSource(test_shp) self.assertEqual(len(ds), 1) def test02_invalid_shp(self): "Testing invalid SHP files for the Data Source." for source in bad_ds: with self.assertRaises(GDALException): DataSource(source.ds) def test03a_layers(self): "Testing Data Source Layers." for source in ds_list: ds = DataSource(source.ds) # Incrementing through each layer, this tests DataSource.__iter__ for layer in ds: self.assertEqual(layer.name, source.name) self.assertEqual(str(layer), source.name) # Making sure we get the number of features we expect self.assertEqual(len(layer), source.nfeat) # Making sure we get the number of fields we expect self.assertEqual(source.nfld, layer.num_fields) self.assertEqual(source.nfld, len(layer.fields)) # Testing the layer's extent (an Envelope), and its properties self.assertIsInstance(layer.extent, Envelope) self.assertAlmostEqual(source.extent[0], layer.extent.min_x, 5) self.assertAlmostEqual(source.extent[1], layer.extent.min_y, 5) self.assertAlmostEqual(source.extent[2], layer.extent.max_x, 5) self.assertAlmostEqual(source.extent[3], layer.extent.max_y, 5) # Now checking the field names. flds = layer.fields for f in flds: self.assertIn(f, source.fields) # Negative FIDs are not allowed. with self.assertRaisesMessage( IndexError, "Negative indices are not allowed on OGR Layers." ): layer.__getitem__(-1) with self.assertRaisesMessage(IndexError, "Invalid feature id: 50000."): layer.__getitem__(50000) if hasattr(source, "field_values"): # Testing `Layer.get_fields` (which uses Layer.__iter__) for fld_name, fld_value in source.field_values.items(): self.assertEqual(fld_value, layer.get_fields(fld_name)) # Testing `Layer.__getitem__`. for i, fid in enumerate(source.fids): feat = layer[fid] self.assertEqual(fid, feat.fid) # Maybe this should be in the test below, but we might # as well test the feature values here while in this # loop. for fld_name, fld_value in source.field_values.items(): self.assertEqual(fld_value[i], feat.get(fld_name)) msg = ( "Index out of range when accessing field in a feature: %s." ) with self.assertRaisesMessage(IndexError, msg % len(feat)): feat.__getitem__(len(feat)) with self.assertRaisesMessage( IndexError, "Invalid OFT field name given: invalid." ): feat.__getitem__("invalid") def test03b_layer_slice(self): "Test indexing and slicing on Layers." # Using the first data-source because the same slice # can be used for both the layer and the control values. source = ds_list[0] ds = DataSource(source.ds) sl = slice(1, 3) feats = ds[0][sl] for fld_name in ds[0].fields: test_vals = [feat.get(fld_name) for feat in feats] control_vals = source.field_values[fld_name][sl] self.assertEqual(control_vals, test_vals) def test03c_layer_references(self): """ Ensure OGR objects keep references to the objects they belong to. """ source = ds_list[0] # See ticket #9448. def get_layer(): # This DataSource object is not accessible outside this # scope. However, a reference should still be kept alive # on the `Layer` returned. ds = DataSource(source.ds) return ds[0] # Making sure we can call OGR routines on the Layer returned. lyr = get_layer() self.assertEqual(source.nfeat, len(lyr)) self.assertEqual(source.gtype, lyr.geom_type.num) # Same issue for Feature/Field objects, see #18640 self.assertEqual(str(lyr[0]["str"]), "1") def test04_features(self): "Testing Data Source Features." for source in ds_list: ds = DataSource(source.ds) # Incrementing through each layer for layer in ds: # Incrementing through each feature in the layer for feat in layer: # Making sure the number of fields, and the geometry type # are what's expected. self.assertEqual(source.nfld, len(list(feat))) self.assertEqual(source.gtype, feat.geom_type) # Making sure the fields match to an appropriate OFT type. for k, v in source.fields.items(): # Making sure we get the proper OGR Field instance, using # a string value index for the feature. self.assertIsInstance(feat[k], v) self.assertIsInstance(feat.fields[0], str) # Testing Feature.__iter__ for fld in feat: self.assertIn(fld.name, source.fields) def test05_geometries(self): "Testing Geometries from Data Source Features." for source in ds_list: ds = DataSource(source.ds) # Incrementing through each layer and feature. for layer in ds: geoms = layer.get_geoms() geos_geoms = layer.get_geoms(geos=True) self.assertEqual(len(geoms), len(geos_geoms)) self.assertEqual(len(geoms), len(layer)) for feat, geom, geos_geom in zip(layer, geoms, geos_geoms): g = feat.geom self.assertEqual(geom, g) self.assertIsInstance(geos_geom, GEOSGeometry) self.assertEqual(g, geos_geom.ogr) # Making sure we get the right Geometry name & type self.assertEqual(source.geom, g.geom_name) self.assertEqual(source.gtype, g.geom_type) # Making sure the SpatialReference is as expected. if hasattr(source, "srs_wkt"): self.assertIsNotNone(re.match(wgs_84_wkt_regex, g.srs.wkt)) def test06_spatial_filter(self): "Testing the Layer.spatial_filter property." ds = DataSource(get_ds_file("cities", "shp")) lyr = ds[0] # When not set, it should be None. self.assertIsNone(lyr.spatial_filter) # Must be set a/an OGRGeometry or 4-tuple. with self.assertRaises(TypeError): lyr._set_spatial_filter("foo") # Setting the spatial filter with a tuple/list with the extent of # a buffer centering around Pueblo. with self.assertRaises(ValueError): lyr._set_spatial_filter(list(range(5))) filter_extent = (-105.609252, 37.255001, -103.609252, 39.255001) lyr.spatial_filter = (-105.609252, 37.255001, -103.609252, 39.255001) self.assertEqual(OGRGeometry.from_bbox(filter_extent), lyr.spatial_filter) feats = [feat for feat in lyr] self.assertEqual(1, len(feats)) self.assertEqual("Pueblo", feats[0].get("Name")) # Setting the spatial filter with an OGRGeometry for buffer centering # around Houston. filter_geom = OGRGeometry( "POLYGON((-96.363151 28.763374,-94.363151 28.763374," "-94.363151 30.763374,-96.363151 30.763374,-96.363151 28.763374))" ) lyr.spatial_filter = filter_geom self.assertEqual(filter_geom, lyr.spatial_filter) feats = [feat for feat in lyr] self.assertEqual(1, len(feats)) self.assertEqual("Houston", feats[0].get("Name")) # Clearing the spatial filter by setting it to None. Now # should indicate that there are 3 features in the Layer. lyr.spatial_filter = None self.assertEqual(3, len(lyr)) def test07_integer_overflow(self): "Testing that OFTReal fields, treated as OFTInteger, do not overflow." # Using *.dbf from Census 2010 TIGER Shapefile for Texas, # which has land area ('ALAND10') stored in a Real field # with no precision. ds = DataSource(os.path.join(TEST_DATA, "texas.dbf")) feat = ds[0][0] # Reference value obtained using `ogrinfo`. self.assertEqual(676586997978, feat.get("ALAND10")) def test_nonexistent_field(self): source = ds_list[0] ds = DataSource(source.ds) msg = "invalid field name: nonexistent" with self.assertRaisesMessage(GDALException, msg): ds[0].get_fields("nonexistent")
3abd24d13d8e671dc8b39020ab6c169235a9e672921a2d240553fdc2e5d79d4f
import json import pickle from django.contrib.gis.gdal import ( CoordTransform, GDALException, OGRGeometry, OGRGeomType, SpatialReference, ) from django.template import Context from django.template.engine import Engine from django.test import SimpleTestCase from ..test_data import TestDataMixin class OGRGeomTest(SimpleTestCase, TestDataMixin): "This tests the OGR Geometry." def test_geomtype(self): "Testing OGRGeomType object." # OGRGeomType should initialize on all these inputs. OGRGeomType(1) OGRGeomType(7) OGRGeomType("point") OGRGeomType("GeometrycollectioN") OGRGeomType("LINearrING") OGRGeomType("Unknown") # Should throw TypeError on this input with self.assertRaises(GDALException): OGRGeomType(23) with self.assertRaises(GDALException): OGRGeomType("fooD") with self.assertRaises(GDALException): OGRGeomType(9) # Equivalence can take strings, ints, and other OGRGeomTypes self.assertEqual(OGRGeomType(1), OGRGeomType(1)) self.assertEqual(OGRGeomType(7), "GeometryCollection") self.assertEqual(OGRGeomType("point"), "POINT") self.assertNotEqual(OGRGeomType("point"), 2) self.assertEqual(OGRGeomType("unknown"), 0) self.assertEqual(OGRGeomType(6), "MULtiPolyGON") self.assertEqual(OGRGeomType(1), OGRGeomType("point")) self.assertNotEqual(OGRGeomType("POINT"), OGRGeomType(6)) # Testing the Django field name equivalent property. self.assertEqual("PointField", OGRGeomType("Point").django) self.assertEqual("GeometryField", OGRGeomType("Geometry").django) self.assertEqual("GeometryField", OGRGeomType("Unknown").django) self.assertIsNone(OGRGeomType("none").django) # 'Geometry' initialization implies an unknown geometry type. gt = OGRGeomType("Geometry") self.assertEqual(0, gt.num) self.assertEqual("Unknown", gt.name) def test_geomtype_25d(self): "Testing OGRGeomType object with 25D types." wkb25bit = OGRGeomType.wkb25bit self.assertEqual(OGRGeomType(wkb25bit + 1), "Point25D") self.assertEqual(OGRGeomType("MultiLineString25D"), (5 + wkb25bit)) self.assertEqual( "GeometryCollectionField", OGRGeomType("GeometryCollection25D").django ) def test_wkt(self): "Testing WKT output." for g in self.geometries.wkt_out: geom = OGRGeometry(g.wkt) self.assertEqual(g.wkt, geom.wkt) def test_ewkt(self): "Testing EWKT input/output." for ewkt_val in ("POINT (1 2 3)", "LINEARRING (0 0,1 1,2 1,0 0)"): # First with ewkt output when no SRID in EWKT self.assertEqual(ewkt_val, OGRGeometry(ewkt_val).ewkt) # No test consumption with an SRID specified. ewkt_val = "SRID=4326;%s" % ewkt_val geom = OGRGeometry(ewkt_val) self.assertEqual(ewkt_val, geom.ewkt) self.assertEqual(4326, geom.srs.srid) def test_gml(self): "Testing GML output." for g in self.geometries.wkt_out: geom = OGRGeometry(g.wkt) exp_gml = g.gml self.assertEqual(exp_gml, geom.gml) def test_hex(self): "Testing HEX input/output." for g in self.geometries.hex_wkt: geom1 = OGRGeometry(g.wkt) self.assertEqual(g.hex.encode(), geom1.hex) # Constructing w/HEX geom2 = OGRGeometry(g.hex) self.assertEqual(geom1, geom2) def test_wkb(self): "Testing WKB input/output." for g in self.geometries.hex_wkt: geom1 = OGRGeometry(g.wkt) wkb = geom1.wkb self.assertEqual(wkb.hex().upper(), g.hex) # Constructing w/WKB. geom2 = OGRGeometry(wkb) self.assertEqual(geom1, geom2) def test_json(self): "Testing GeoJSON input/output." for g in self.geometries.json_geoms: geom = OGRGeometry(g.wkt) if not hasattr(g, "not_equal"): # Loading jsons to prevent decimal differences self.assertEqual(json.loads(g.json), json.loads(geom.json)) self.assertEqual(json.loads(g.json), json.loads(geom.geojson)) self.assertEqual(OGRGeometry(g.wkt), OGRGeometry(geom.json)) # Test input with some garbage content (but valid json) (#15529) geom = OGRGeometry( '{"type": "Point", "coordinates": [ 100.0, 0.0 ], "other": "<test>"}' ) self.assertIsInstance(geom, OGRGeometry) def test_points(self): "Testing Point objects." OGRGeometry("POINT(0 0)") for p in self.geometries.points: if not hasattr(p, "z"): # No 3D pnt = OGRGeometry(p.wkt) self.assertEqual(1, pnt.geom_type) self.assertEqual("POINT", pnt.geom_name) self.assertEqual(p.x, pnt.x) self.assertEqual(p.y, pnt.y) self.assertEqual((p.x, p.y), pnt.tuple) def test_multipoints(self): "Testing MultiPoint objects." for mp in self.geometries.multipoints: mgeom1 = OGRGeometry(mp.wkt) # First one from WKT self.assertEqual(4, mgeom1.geom_type) self.assertEqual("MULTIPOINT", mgeom1.geom_name) mgeom2 = OGRGeometry("MULTIPOINT") # Creating empty multipoint mgeom3 = OGRGeometry("MULTIPOINT") for g in mgeom1: mgeom2.add(g) # adding each point from the multipoints mgeom3.add(g.wkt) # should take WKT as well self.assertEqual(mgeom1, mgeom2) # they should equal self.assertEqual(mgeom1, mgeom3) self.assertEqual(mp.coords, mgeom2.coords) self.assertEqual(mp.n_p, mgeom2.point_count) def test_linestring(self): "Testing LineString objects." prev = OGRGeometry("POINT(0 0)") for ls in self.geometries.linestrings: linestr = OGRGeometry(ls.wkt) self.assertEqual(2, linestr.geom_type) self.assertEqual("LINESTRING", linestr.geom_name) self.assertEqual(ls.n_p, linestr.point_count) self.assertEqual(ls.coords, linestr.tuple) self.assertEqual(linestr, OGRGeometry(ls.wkt)) self.assertNotEqual(linestr, prev) msg = "Index out of range when accessing points of a line string: %s." with self.assertRaisesMessage(IndexError, msg % len(linestr)): linestr.__getitem__(len(linestr)) prev = linestr # Testing the x, y properties. x = [tmpx for tmpx, tmpy in ls.coords] y = [tmpy for tmpx, tmpy in ls.coords] self.assertEqual(x, linestr.x) self.assertEqual(y, linestr.y) def test_multilinestring(self): "Testing MultiLineString objects." prev = OGRGeometry("POINT(0 0)") for mls in self.geometries.multilinestrings: mlinestr = OGRGeometry(mls.wkt) self.assertEqual(5, mlinestr.geom_type) self.assertEqual("MULTILINESTRING", mlinestr.geom_name) self.assertEqual(mls.n_p, mlinestr.point_count) self.assertEqual(mls.coords, mlinestr.tuple) self.assertEqual(mlinestr, OGRGeometry(mls.wkt)) self.assertNotEqual(mlinestr, prev) prev = mlinestr for ls in mlinestr: self.assertEqual(2, ls.geom_type) self.assertEqual("LINESTRING", ls.geom_name) msg = "Index out of range when accessing geometry in a collection: %s." with self.assertRaisesMessage(IndexError, msg % len(mlinestr)): mlinestr.__getitem__(len(mlinestr)) def test_linearring(self): "Testing LinearRing objects." prev = OGRGeometry("POINT(0 0)") for rr in self.geometries.linearrings: lr = OGRGeometry(rr.wkt) # self.assertEqual(101, lr.geom_type.num) self.assertEqual("LINEARRING", lr.geom_name) self.assertEqual(rr.n_p, len(lr)) self.assertEqual(lr, OGRGeometry(rr.wkt)) self.assertNotEqual(lr, prev) prev = lr def test_polygons(self): "Testing Polygon objects." # Testing `from_bbox` class method bbox = (-180, -90, 180, 90) p = OGRGeometry.from_bbox(bbox) self.assertEqual(bbox, p.extent) prev = OGRGeometry("POINT(0 0)") for p in self.geometries.polygons: poly = OGRGeometry(p.wkt) self.assertEqual(3, poly.geom_type) self.assertEqual("POLYGON", poly.geom_name) self.assertEqual(p.n_p, poly.point_count) self.assertEqual(p.n_i + 1, len(poly)) msg = "Index out of range when accessing rings of a polygon: %s." with self.assertRaisesMessage(IndexError, msg % len(poly)): poly.__getitem__(len(poly)) # Testing area & centroid. self.assertAlmostEqual(p.area, poly.area, 9) x, y = poly.centroid.tuple self.assertAlmostEqual(p.centroid[0], x, 9) self.assertAlmostEqual(p.centroid[1], y, 9) # Testing equivalence self.assertEqual(poly, OGRGeometry(p.wkt)) self.assertNotEqual(poly, prev) if p.ext_ring_cs: ring = poly[0] self.assertEqual(p.ext_ring_cs, ring.tuple) self.assertEqual(p.ext_ring_cs, poly[0].tuple) self.assertEqual(len(p.ext_ring_cs), ring.point_count) for r in poly: self.assertEqual("LINEARRING", r.geom_name) def test_polygons_templates(self): # Accessing Polygon attributes in templates should work. engine = Engine() template = engine.from_string("{{ polygons.0.wkt }}") polygons = [OGRGeometry(p.wkt) for p in self.geometries.multipolygons[:2]] content = template.render(Context({"polygons": polygons})) self.assertIn("MULTIPOLYGON (((100", content) def test_closepolygons(self): "Testing closing Polygon objects." # Both rings in this geometry are not closed. poly = OGRGeometry("POLYGON((0 0, 5 0, 5 5, 0 5), (1 1, 2 1, 2 2, 2 1))") self.assertEqual(8, poly.point_count) with self.assertRaises(GDALException): poly.centroid poly.close_rings() self.assertEqual( 10, poly.point_count ) # Two closing points should've been added self.assertEqual(OGRGeometry("POINT(2.5 2.5)"), poly.centroid) def test_multipolygons(self): "Testing MultiPolygon objects." OGRGeometry("POINT(0 0)") for mp in self.geometries.multipolygons: mpoly = OGRGeometry(mp.wkt) self.assertEqual(6, mpoly.geom_type) self.assertEqual("MULTIPOLYGON", mpoly.geom_name) if mp.valid: self.assertEqual(mp.n_p, mpoly.point_count) self.assertEqual(mp.num_geom, len(mpoly)) msg = "Index out of range when accessing geometry in a collection: %s." with self.assertRaisesMessage(IndexError, msg % len(mpoly)): mpoly.__getitem__(len(mpoly)) for p in mpoly: self.assertEqual("POLYGON", p.geom_name) self.assertEqual(3, p.geom_type) self.assertEqual(mpoly.wkt, OGRGeometry(mp.wkt).wkt) def test_srs(self): "Testing OGR Geometries with Spatial Reference objects." for mp in self.geometries.multipolygons: # Creating a geometry w/spatial reference sr = SpatialReference("WGS84") mpoly = OGRGeometry(mp.wkt, sr) self.assertEqual(sr.wkt, mpoly.srs.wkt) # Ensuring that SRS is propagated to clones. klone = mpoly.clone() self.assertEqual(sr.wkt, klone.srs.wkt) # Ensuring all children geometries (polygons and their rings) all # return the assigned spatial reference as well. for poly in mpoly: self.assertEqual(sr.wkt, poly.srs.wkt) for ring in poly: self.assertEqual(sr.wkt, ring.srs.wkt) # Ensuring SRS propagate in topological ops. a = OGRGeometry(self.geometries.topology_geoms[0].wkt_a, sr) b = OGRGeometry(self.geometries.topology_geoms[0].wkt_b, sr) diff = a.difference(b) union = a.union(b) self.assertEqual(sr.wkt, diff.srs.wkt) self.assertEqual(sr.srid, union.srs.srid) # Instantiating w/an integer SRID mpoly = OGRGeometry(mp.wkt, 4326) self.assertEqual(4326, mpoly.srid) mpoly.srs = SpatialReference(4269) self.assertEqual(4269, mpoly.srid) self.assertEqual("NAD83", mpoly.srs.name) # Incrementing through the multipolygon after the spatial reference # has been re-assigned. for poly in mpoly: self.assertEqual(mpoly.srs.wkt, poly.srs.wkt) poly.srs = 32140 for ring in poly: # Changing each ring in the polygon self.assertEqual(32140, ring.srs.srid) self.assertEqual("NAD83 / Texas South Central", ring.srs.name) ring.srs = str(SpatialReference(4326)) # back to WGS84 self.assertEqual(4326, ring.srs.srid) # Using the `srid` property. ring.srid = 4322 self.assertEqual("WGS 72", ring.srs.name) self.assertEqual(4322, ring.srid) # srs/srid may be assigned their own values, even when srs is None. mpoly = OGRGeometry(mp.wkt, srs=None) mpoly.srs = mpoly.srs mpoly.srid = mpoly.srid def test_srs_transform(self): "Testing transform()." orig = OGRGeometry("POINT (-104.609 38.255)", 4326) trans = OGRGeometry("POINT (992385.4472045 481455.4944650)", 2774) # Using an srid, a SpatialReference object, and a CoordTransform object # or transformations. t1, t2, t3 = orig.clone(), orig.clone(), orig.clone() t1.transform(trans.srid) t2.transform(SpatialReference("EPSG:2774")) ct = CoordTransform(SpatialReference("WGS84"), SpatialReference(2774)) t3.transform(ct) # Testing use of the `clone` keyword. k1 = orig.clone() k2 = k1.transform(trans.srid, clone=True) self.assertEqual(k1, orig) self.assertNotEqual(k1, k2) # Different PROJ versions use different transformations, all are # correct as having a 1 meter accuracy. prec = -1 for p in (t1, t2, t3, k2): self.assertAlmostEqual(trans.x, p.x, prec) self.assertAlmostEqual(trans.y, p.y, prec) def test_transform_dim(self): "Testing coordinate dimension is the same on transformed geometries." ls_orig = OGRGeometry("LINESTRING(-104.609 38.255)", 4326) ls_trans = OGRGeometry("LINESTRING(992385.4472045 481455.4944650)", 2774) # Different PROJ versions use different transformations, all are # correct as having a 1 meter accuracy. prec = -1 ls_orig.transform(ls_trans.srs) # Making sure the coordinate dimension is still 2D. self.assertEqual(2, ls_orig.coord_dim) self.assertAlmostEqual(ls_trans.x[0], ls_orig.x[0], prec) self.assertAlmostEqual(ls_trans.y[0], ls_orig.y[0], prec) def test_difference(self): "Testing difference()." for i in range(len(self.geometries.topology_geoms)): a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a) b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b) d1 = OGRGeometry(self.geometries.diff_geoms[i].wkt) d2 = a.difference(b) self.assertTrue(d1.geos.equals(d2.geos)) self.assertTrue( d1.geos.equals((a - b).geos) ) # __sub__ is difference operator a -= b # testing __isub__ self.assertTrue(d1.geos.equals(a.geos)) def test_intersection(self): "Testing intersects() and intersection()." for i in range(len(self.geometries.topology_geoms)): a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a) b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b) i1 = OGRGeometry(self.geometries.intersect_geoms[i].wkt) self.assertTrue(a.intersects(b)) i2 = a.intersection(b) self.assertTrue(i1.geos.equals(i2.geos)) self.assertTrue( i1.geos.equals((a & b).geos) ) # __and__ is intersection operator a &= b # testing __iand__ self.assertTrue(i1.geos.equals(a.geos)) def test_symdifference(self): "Testing sym_difference()." for i in range(len(self.geometries.topology_geoms)): a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a) b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b) d1 = OGRGeometry(self.geometries.sdiff_geoms[i].wkt) d2 = a.sym_difference(b) self.assertTrue(d1.geos.equals(d2.geos)) self.assertTrue( d1.geos.equals((a ^ b).geos) ) # __xor__ is symmetric difference operator a ^= b # testing __ixor__ self.assertTrue(d1.geos.equals(a.geos)) def test_union(self): "Testing union()." for i in range(len(self.geometries.topology_geoms)): a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a) b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b) u1 = OGRGeometry(self.geometries.union_geoms[i].wkt) u2 = a.union(b) self.assertTrue(u1.geos.equals(u2.geos)) self.assertTrue(u1.geos.equals((a | b).geos)) # __or__ is union operator a |= b # testing __ior__ self.assertTrue(u1.geos.equals(a.geos)) def test_add(self): "Testing GeometryCollection.add()." # Can't insert a Point into a MultiPolygon. mp = OGRGeometry("MultiPolygon") pnt = OGRGeometry("POINT(5 23)") with self.assertRaises(GDALException): mp.add(pnt) # GeometryCollection.add may take an OGRGeometry (if another collection # of the same type all child geoms will be added individually) or WKT. for mp in self.geometries.multipolygons: mpoly = OGRGeometry(mp.wkt) mp1 = OGRGeometry("MultiPolygon") mp2 = OGRGeometry("MultiPolygon") mp3 = OGRGeometry("MultiPolygon") for poly in mpoly: mp1.add(poly) # Adding a geometry at a time mp2.add(poly.wkt) # Adding WKT mp3.add(mpoly) # Adding a MultiPolygon's entire contents at once. for tmp in (mp1, mp2, mp3): self.assertEqual(mpoly, tmp) def test_extent(self): "Testing `extent` property." # The xmin, ymin, xmax, ymax of the MultiPoint should be returned. mp = OGRGeometry("MULTIPOINT(5 23, 0 0, 10 50)") self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent) # Testing on the 'real world' Polygon. poly = OGRGeometry(self.geometries.polygons[3].wkt) ring = poly.shell x, y = ring.x, ring.y xmin, ymin = min(x), min(y) xmax, ymax = max(x), max(y) self.assertEqual((xmin, ymin, xmax, ymax), poly.extent) def test_25D(self): "Testing 2.5D geometries." pnt_25d = OGRGeometry("POINT(1 2 3)") self.assertEqual("Point25D", pnt_25d.geom_type.name) self.assertEqual(3.0, pnt_25d.z) self.assertEqual(3, pnt_25d.coord_dim) ls_25d = OGRGeometry("LINESTRING(1 1 1,2 2 2,3 3 3)") self.assertEqual("LineString25D", ls_25d.geom_type.name) self.assertEqual([1.0, 2.0, 3.0], ls_25d.z) self.assertEqual(3, ls_25d.coord_dim) def test_pickle(self): "Testing pickle support." g1 = OGRGeometry("LINESTRING(1 1 1,2 2 2,3 3 3)", "WGS84") g2 = pickle.loads(pickle.dumps(g1)) self.assertEqual(g1, g2) self.assertEqual(4326, g2.srs.srid) self.assertEqual(g1.srs.wkt, g2.srs.wkt) def test_ogrgeometry_transform_workaround(self): "Testing coordinate dimensions on geometries after transformation." # A bug in GDAL versions prior to 1.7 changes the coordinate # dimension of a geometry after it has been transformed. # This test ensures that the bug workarounds employed within # `OGRGeometry.transform` indeed work. wkt_2d = "MULTILINESTRING ((0 0,1 1,2 2))" wkt_3d = "MULTILINESTRING ((0 0 0,1 1 1,2 2 2))" srid = 4326 # For both the 2D and 3D MultiLineString, ensure _both_ the dimension # of the collection and the component LineString have the expected # coordinate dimension after transform. geom = OGRGeometry(wkt_2d, srid) geom.transform(srid) self.assertEqual(2, geom.coord_dim) self.assertEqual(2, geom[0].coord_dim) self.assertEqual(wkt_2d, geom.wkt) geom = OGRGeometry(wkt_3d, srid) geom.transform(srid) self.assertEqual(3, geom.coord_dim) self.assertEqual(3, geom[0].coord_dim) self.assertEqual(wkt_3d, geom.wkt) # Testing binary predicates, `assertIs` is used to check that bool is returned. def test_equivalence_regression(self): "Testing equivalence methods with non-OGRGeometry instances." self.assertIsNotNone(OGRGeometry("POINT(0 0)")) self.assertNotEqual(OGRGeometry("LINESTRING(0 0, 1 1)"), 3) def test_contains(self): self.assertIs( OGRGeometry("POINT(0 0)").contains(OGRGeometry("POINT(0 0)")), True ) self.assertIs( OGRGeometry("POINT(0 0)").contains(OGRGeometry("POINT(0 1)")), False ) def test_crosses(self): self.assertIs( OGRGeometry("LINESTRING(0 0, 1 1)").crosses( OGRGeometry("LINESTRING(0 1, 1 0)") ), True, ) self.assertIs( OGRGeometry("LINESTRING(0 0, 0 1)").crosses( OGRGeometry("LINESTRING(1 0, 1 1)") ), False, ) def test_disjoint(self): self.assertIs( OGRGeometry("LINESTRING(0 0, 1 1)").disjoint( OGRGeometry("LINESTRING(0 1, 1 0)") ), False, ) self.assertIs( OGRGeometry("LINESTRING(0 0, 0 1)").disjoint( OGRGeometry("LINESTRING(1 0, 1 1)") ), True, ) def test_equals(self): self.assertIs( OGRGeometry("POINT(0 0)").contains(OGRGeometry("POINT(0 0)")), True ) self.assertIs( OGRGeometry("POINT(0 0)").contains(OGRGeometry("POINT(0 1)")), False ) def test_intersects(self): self.assertIs( OGRGeometry("LINESTRING(0 0, 1 1)").intersects( OGRGeometry("LINESTRING(0 1, 1 0)") ), True, ) self.assertIs( OGRGeometry("LINESTRING(0 0, 0 1)").intersects( OGRGeometry("LINESTRING(1 0, 1 1)") ), False, ) def test_overlaps(self): self.assertIs( OGRGeometry("POLYGON ((0 0, 0 2, 2 2, 2 0, 0 0))").overlaps( OGRGeometry("POLYGON ((1 1, 1 5, 5 5, 5 1, 1 1))") ), True, ) self.assertIs( OGRGeometry("POINT(0 0)").overlaps(OGRGeometry("POINT(0 1)")), False ) def test_touches(self): self.assertIs( OGRGeometry("POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))").touches( OGRGeometry("LINESTRING(0 2, 2 0)") ), True, ) self.assertIs( OGRGeometry("POINT(0 0)").touches(OGRGeometry("POINT(0 1)")), False ) def test_within(self): self.assertIs( OGRGeometry("POINT(0.5 0.5)").within( OGRGeometry("POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))") ), True, ) self.assertIs( OGRGeometry("POINT(0 0)").within(OGRGeometry("POINT(0 1)")), False ) def test_from_gml(self): self.assertEqual( OGRGeometry("POINT(0 0)"), OGRGeometry.from_gml( '<gml:Point gml:id="p21" ' 'srsName="http://www.opengis.net/def/crs/EPSG/0/4326">' ' <gml:pos srsDimension="2">0 0</gml:pos>' "</gml:Point>" ), ) def test_empty(self): self.assertIs(OGRGeometry("POINT (0 0)").empty, False) self.assertIs(OGRGeometry("POINT EMPTY").empty, True) def test_empty_point_to_geos(self): p = OGRGeometry("POINT EMPTY", srs=4326) self.assertEqual(p.geos.ewkt, p.ewkt)
8acee38d695fd930c760405b26429e2827f26db4643e8705f0259bdf8c4dbf54
import unittest from django.contrib.gis.gdal import GDAL_VERSION, gdal_full_version, gdal_version class GDALTest(unittest.TestCase): def test_gdal_version(self): if GDAL_VERSION: self.assertEqual(gdal_version(), ("%s.%s.%s" % GDAL_VERSION).encode()) else: self.assertIn(b".", gdal_version()) def test_gdal_full_version(self): full_version = gdal_full_version() self.assertIn(gdal_version(), full_version) self.assertTrue(full_version.startswith(b"GDAL"))
15f8219a159421f9835a4c46f94933d114260334f5df6e694208951687358850
import unittest from django.contrib.gis.gdal import Envelope, GDALException class TestPoint: def __init__(self, x, y): self.x = x self.y = y class EnvelopeTest(unittest.TestCase): def setUp(self): self.e = Envelope(0, 0, 5, 5) def test01_init(self): "Testing Envelope initialization." e1 = Envelope((0, 0, 5, 5)) Envelope(0, 0, 5, 5) Envelope(0, "0", "5", 5) # Thanks to ww for this Envelope(e1._envelope) with self.assertRaises(GDALException): Envelope((5, 5, 0, 0)) with self.assertRaises(GDALException): Envelope(5, 5, 0, 0) with self.assertRaises(GDALException): Envelope((0, 0, 5, 5, 3)) with self.assertRaises(GDALException): Envelope(()) with self.assertRaises(ValueError): Envelope(0, "a", 5, 5) with self.assertRaises(TypeError): Envelope("foo") with self.assertRaises(GDALException): Envelope((1, 1, 0, 0)) # Shouldn't raise an exception for min_x == max_x or min_y == max_y Envelope(0, 0, 0, 0) def test02_properties(self): "Testing Envelope properties." e = Envelope(0, 0, 2, 3) self.assertEqual(0, e.min_x) self.assertEqual(0, e.min_y) self.assertEqual(2, e.max_x) self.assertEqual(3, e.max_y) self.assertEqual((0, 0), e.ll) self.assertEqual((2, 3), e.ur) self.assertEqual((0, 0, 2, 3), e.tuple) self.assertEqual("POLYGON((0.0 0.0,0.0 3.0,2.0 3.0,2.0 0.0,0.0 0.0))", e.wkt) self.assertEqual("(0.0, 0.0, 2.0, 3.0)", str(e)) def test03_equivalence(self): "Testing Envelope equivalence." e1 = Envelope(0.523, 0.217, 253.23, 523.69) e2 = Envelope((0.523, 0.217, 253.23, 523.69)) self.assertEqual(e1, e2) self.assertEqual((0.523, 0.217, 253.23, 523.69), e1) def test04_expand_to_include_pt_2_params(self): "Testing Envelope expand_to_include -- point as two parameters." self.e.expand_to_include(2, 6) self.assertEqual((0, 0, 5, 6), self.e) self.e.expand_to_include(-1, -1) self.assertEqual((-1, -1, 5, 6), self.e) def test05_expand_to_include_pt_2_tuple(self): "Testing Envelope expand_to_include -- point as a single 2-tuple parameter." self.e.expand_to_include((10, 10)) self.assertEqual((0, 0, 10, 10), self.e) self.e.expand_to_include((-10, -10)) self.assertEqual((-10, -10, 10, 10), self.e) def test06_expand_to_include_extent_4_params(self): "Testing Envelope expand_to_include -- extent as 4 parameters." self.e.expand_to_include(-1, 1, 3, 7) self.assertEqual((-1, 0, 5, 7), self.e) def test06_expand_to_include_extent_4_tuple(self): "Testing Envelope expand_to_include -- extent as a single 4-tuple parameter." self.e.expand_to_include((-1, 1, 3, 7)) self.assertEqual((-1, 0, 5, 7), self.e) def test07_expand_to_include_envelope(self): "Testing Envelope expand_to_include with Envelope as parameter." self.e.expand_to_include(Envelope(-1, 1, 3, 7)) self.assertEqual((-1, 0, 5, 7), self.e) def test08_expand_to_include_point(self): "Testing Envelope expand_to_include with Point as parameter." self.e.expand_to_include(TestPoint(-1, 1)) self.assertEqual((-1, 0, 5, 5), self.e) self.e.expand_to_include(TestPoint(10, 10)) self.assertEqual((-1, 0, 10, 10), self.e)
b8a8513a55c24c79edac393f31d19fe29f6595c3cb767b2a4617d389c78d82c1
from unittest import skipIf from django.contrib.gis.gdal import ( GDAL_VERSION, AxisOrder, CoordTransform, GDALException, SpatialReference, SRSException, ) from django.contrib.gis.geos import GEOSGeometry from django.test import SimpleTestCase class TestSRS: def __init__(self, wkt, **kwargs): self.wkt = wkt for key, value in kwargs.items(): setattr(self, key, value) WGS84_proj = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs " # Some Spatial 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,AUTHORITY["EPSG","9122"]],AXIS["Latitude",NORTH],' 'AXIS["Longitude",EAST],AUTHORITY["EPSG","4326"]]', epsg=4326, projected=False, geographic=True, local=False, lin_name="unknown", ang_name="degree", lin_units=1.0, ang_units=0.0174532925199, auth={"GEOGCS": ("EPSG", "4326"), "spheroid": ("EPSG", "7030")}, attr=( ("DATUM", "WGS_1984"), (("SPHEROID", 1), "6378137"), ("primem|authority", "EPSG"), ), ), TestSRS( 'PROJCS["NAD83 / Texas South Central",' 'GEOGCS["NAD83",DATUM["North_American_Datum_1983",' 'SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],' 'AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4269"]],PROJECTION["Lambert_Conformal_Conic_2SP"],' 'PARAMETER["standard_parallel_1",30.2833333333333],' 'PARAMETER["standard_parallel_2",28.3833333333333],' 'PARAMETER["latitude_of_origin",27.8333333333333],' 'PARAMETER["central_meridian",-99],PARAMETER["false_easting",600000],' 'PARAMETER["false_northing",4000000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],' 'AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","32140"]]', epsg=32140, projected=True, geographic=False, local=False, lin_name="metre", ang_name="degree", lin_units=1.0, ang_units=0.0174532925199, auth={ "PROJCS": ("EPSG", "32140"), "spheroid": ("EPSG", "7019"), "unit": ("EPSG", "9001"), }, attr=( ("DATUM", "North_American_Datum_1983"), (("SPHEROID", 2), "298.257222101"), ("PROJECTION", "Lambert_Conformal_Conic_2SP"), ), ), TestSRS( 'PROJCS["NAD83 / Texas South Central (ftUS)",' 'GEOGCS["NAD83",DATUM["North_American_Datum_1983",' 'SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],' 'AUTHORITY["EPSG","6269"]],' 'PRIMEM["Greenwich",0],' 'UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic_2SP"],' 'PARAMETER["false_easting",1968500],' 'PARAMETER["false_northing",13123333.3333333],' 'PARAMETER["central_meridian",-99],' 'PARAMETER["standard_parallel_1",28.3833333333333],' 'PARAMETER["standard_parallel_2",30.2833333333333],' 'PARAMETER["latitude_of_origin",27.8333333333333],' 'UNIT["US survey foot",0.304800609601219],AXIS["Easting",EAST],' 'AXIS["Northing",NORTH]]', epsg=None, projected=True, geographic=False, local=False, lin_name="US survey foot", ang_name="Degree", lin_units=0.3048006096012192, ang_units=0.0174532925199, auth={"PROJCS": (None, None)}, attr=( ("PROJCS|GeOgCs|spheroid", "GRS 1980"), (("projcs", 9), "UNIT"), (("projcs", 11), "AXIS"), ), ), # This is really ESRI format, not WKT -- but the import should work the same TestSRS( 'LOCAL_CS["Non-Earth (Meter)",LOCAL_DATUM["Local Datum",32767],' 'UNIT["Meter",1],AXIS["X",EAST],AXIS["Y",NORTH]]', esri=True, epsg=None, projected=False, geographic=False, local=True, lin_name="Meter", ang_name="degree", lin_units=1.0, ang_units=0.0174532925199, attr=(("LOCAL_DATUM", "Local Datum"),), ), ) # Well-Known Names well_known = ( 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.01745329251994328,' 'AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]', wk="WGS84", name="WGS 84", attrs=(("GEOGCS|AUTHORITY", 1, "4326"), ("SPHEROID", "WGS 84")), ), TestSRS( 'GEOGCS["WGS 72",DATUM["WGS_1972",SPHEROID["WGS 72",6378135,298.26,' 'AUTHORITY["EPSG","7043"]],AUTHORITY["EPSG","6322"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4322"]]', wk="WGS72", name="WGS 72", attrs=(("GEOGCS|AUTHORITY", 1, "4322"), ("SPHEROID", "WGS 72")), ), TestSRS( 'GEOGCS["NAD27",DATUM["North_American_Datum_1927",' 'SPHEROID["Clarke 1866",6378206.4,294.9786982138982,' 'AUTHORITY["EPSG","7008"]],AUTHORITY["EPSG","6267"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4267"]]', wk="NAD27", name="NAD27", attrs=(("GEOGCS|AUTHORITY", 1, "4267"), ("SPHEROID", "Clarke 1866")), ), TestSRS( 'GEOGCS["NAD83",DATUM["North_American_Datum_1983",' 'SPHEROID["GRS 1980",6378137,298.257222101,' 'AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4269"]]', wk="NAD83", name="NAD83", attrs=(("GEOGCS|AUTHORITY", 1, "4269"), ("SPHEROID", "GRS 1980")), ), TestSRS( 'PROJCS["NZGD49 / Karamea Circuit",GEOGCS["NZGD49",' 'DATUM["New_Zealand_Geodetic_Datum_1949",' 'SPHEROID["International 1924",6378388,297,' 'AUTHORITY["EPSG","7022"]],' "TOWGS84[59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993]," 'AUTHORITY["EPSG","6272"]],PRIMEM["Greenwich",0,' 'AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,' 'AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4272"]],' 'PROJECTION["Transverse_Mercator"],' 'PARAMETER["latitude_of_origin",-41.28991152777778],' 'PARAMETER["central_meridian",172.1090281944444],' 'PARAMETER["scale_factor",1],PARAMETER["false_easting",300000],' 'PARAMETER["false_northing",700000],' 'UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","27216"]]', wk="EPSG:27216", name="NZGD49 / Karamea Circuit", attrs=( ("PROJECTION", "Transverse_Mercator"), ("SPHEROID", "International 1924"), ), ), ) bad_srlist = ( "Foobar", 'OOJCS["NAD83 / Texas South Central",GEOGCS["NAD83",' 'DATUM["North_American_Datum_1983",' 'SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],' 'AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4269"]],PROJECTION["Lambert_Conformal_Conic_2SP"],' 'PARAMETER["standard_parallel_1",30.28333333333333],' 'PARAMETER["standard_parallel_2",28.38333333333333],' 'PARAMETER["latitude_of_origin",27.83333333333333],' 'PARAMETER["central_meridian",-99],PARAMETER["false_easting",600000],' 'PARAMETER["false_northing",4000000],UNIT["metre",1,' 'AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32140"]]', ) class SpatialRefTest(SimpleTestCase): def test01_wkt(self): "Testing initialization on valid OGC WKT." for s in srlist: SpatialReference(s.wkt) def test02_bad_wkt(self): "Testing initialization on invalid WKT." for bad in bad_srlist: try: srs = SpatialReference(bad) srs.validate() except (SRSException, GDALException): pass else: self.fail('Should not have initialized on bad WKT "%s"!') def test03_get_wkt(self): "Testing getting the WKT." for s in srlist: srs = SpatialReference(s.wkt) # GDAL 3 strips UNIT part in the last occurrence. self.assertEqual( s.wkt.replace(',UNIT["Meter",1]', ""), srs.wkt.replace(',UNIT["Meter",1]', ""), ) def test04_proj(self): """PROJ import and export.""" proj_parts = [ "+proj=longlat", "+ellps=WGS84", "+towgs84=0,0,0,0,0,0,0", "+datum=WGS84", "+no_defs", ] srs1 = SpatialReference(srlist[0].wkt) srs2 = SpatialReference(WGS84_proj) self.assertTrue(all(part in proj_parts for part in srs1.proj.split())) self.assertTrue(all(part in proj_parts for part in srs2.proj.split())) def test05_epsg(self): "Test EPSG import." for s in srlist: if s.epsg: srs1 = SpatialReference(s.wkt) srs2 = SpatialReference(s.epsg) srs3 = SpatialReference(str(s.epsg)) srs4 = SpatialReference("EPSG:%d" % s.epsg) for srs in (srs1, srs2, srs3, srs4): for attr, expected in s.attr: self.assertEqual(expected, srs[attr]) def test07_boolean_props(self): "Testing the boolean properties." for s in srlist: srs = SpatialReference(s.wkt) self.assertEqual(s.projected, srs.projected) self.assertEqual(s.geographic, srs.geographic) def test08_angular_linear(self): "Testing the linear and angular units routines." for s in srlist: srs = SpatialReference(s.wkt) self.assertEqual(s.ang_name, srs.angular_name) self.assertEqual(s.lin_name, srs.linear_name) self.assertAlmostEqual(s.ang_units, srs.angular_units, 9) self.assertAlmostEqual(s.lin_units, srs.linear_units, 9) def test09_authority(self): "Testing the authority name & code routines." for s in srlist: if hasattr(s, "auth"): srs = SpatialReference(s.wkt) for target, tup in s.auth.items(): self.assertEqual(tup[0], srs.auth_name(target)) self.assertEqual(tup[1], srs.auth_code(target)) def test10_attributes(self): "Testing the attribute retrieval routines." for s in srlist: srs = SpatialReference(s.wkt) for tup in s.attr: att = tup[0] # Attribute to test exp = tup[1] # Expected result self.assertEqual(exp, srs[att]) def test11_wellknown(self): "Testing Well Known Names of Spatial References." for s in well_known: srs = SpatialReference(s.wk) self.assertEqual(s.name, srs.name) for tup in s.attrs: if len(tup) == 2: key = tup[0] exp = tup[1] elif len(tup) == 3: key = tup[:2] exp = tup[2] self.assertEqual(srs[key], exp) def test12_coordtransform(self): "Testing initialization of a CoordTransform." target = SpatialReference("WGS84") CoordTransform(SpatialReference(srlist[0].wkt), target) def test13_attr_value(self): "Testing the attr_value() method." s1 = SpatialReference("WGS84") with self.assertRaises(TypeError): s1.__getitem__(0) with self.assertRaises(TypeError): s1.__getitem__(("GEOGCS", "foo")) self.assertEqual("WGS 84", s1["GEOGCS"]) self.assertEqual("WGS_1984", s1["DATUM"]) self.assertEqual("EPSG", s1["AUTHORITY"]) self.assertEqual(4326, int(s1["AUTHORITY", 1])) self.assertIsNone(s1["FOOBAR"]) def test_unicode(self): wkt = ( 'PROJCS["DHDN / Soldner 39 Langschoß",' 'GEOGCS["DHDN",DATUM["Deutsches_Hauptdreiecksnetz",' 'SPHEROID["Bessel 1841",6377397.155,299.1528128,AUTHORITY["EPSG","7004"]],' 'AUTHORITY["EPSG","6314"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4314"]],PROJECTION["Cassini_Soldner"],' 'PARAMETER["latitude_of_origin",50.66738711],' 'PARAMETER["central_meridian",6.28935703],' 'PARAMETER["false_easting",0],PARAMETER["false_northing",0],' 'UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["X",NORTH],AXIS["Y",EAST],' 'AUTHORITY["mj10777.de","187939"]]' ) srs = SpatialReference(wkt) srs_list = [srs, srs.clone()] srs.import_wkt(wkt) for srs in srs_list: self.assertEqual(srs.name, "DHDN / Soldner 39 Langschoß") self.assertEqual(srs.wkt, wkt) self.assertIn("Langschoß", srs.pretty_wkt) self.assertIn("Langschoß", srs.xml) @skipIf(GDAL_VERSION < (3, 0), "GDAL >= 3.0 is required") def test_axis_order(self): wgs84_trad = SpatialReference(4326, axis_order=AxisOrder.TRADITIONAL) wgs84_auth = SpatialReference(4326, axis_order=AxisOrder.AUTHORITY) # Coordinate interpretation may depend on the srs axis predicate. pt = GEOSGeometry("POINT (992385.4472045 481455.4944650)", 2774) pt_trad = pt.transform(wgs84_trad, clone=True) self.assertAlmostEqual(pt_trad.x, -104.609, 3) self.assertAlmostEqual(pt_trad.y, 38.255, 3) pt_auth = pt.transform(wgs84_auth, clone=True) self.assertAlmostEqual(pt_auth.x, 38.255, 3) self.assertAlmostEqual(pt_auth.y, -104.609, 3) # clone() preserves the axis order. pt_auth = pt.transform(wgs84_auth.clone(), clone=True) self.assertAlmostEqual(pt_auth.x, 38.255, 3) self.assertAlmostEqual(pt_auth.y, -104.609, 3) def test_axis_order_invalid(self): msg = "SpatialReference.axis_order must be an AxisOrder instance." with self.assertRaisesMessage(ValueError, msg): SpatialReference(4326, axis_order="other") @skipIf(GDAL_VERSION > (3, 0), "GDAL < 3.0 doesn't support authority.") def test_axis_order_non_traditional_invalid(self): msg = "AxisOrder.AUTHORITY is not supported in GDAL < 3.0." with self.assertRaisesMessage(ValueError, msg): SpatialReference(4326, axis_order=AxisOrder.AUTHORITY) def test_esri(self): srs = SpatialReference("NAD83") pre_esri_wkt = srs.wkt srs.to_esri() self.assertNotEqual(srs.wkt, pre_esri_wkt) self.assertIn('DATUM["D_North_American_1983"', srs.wkt) srs.from_esri() self.assertIn('DATUM["North_American_Datum_1983"', srs.wkt)
1a6f3a5cdaa6537912e1943821eb6126e9b58d3cf183c0fdad02a0befd00a325
import unittest from unittest import mock from django.contrib.gis.gdal import Driver, GDALException valid_drivers = ( # vector "ESRI Shapefile", "MapInfo File", "TIGER", "S57", "DGN", "Memory", "CSV", "GML", "KML", # raster "GTiff", "JPEG", "MEM", "PNG", ) invalid_drivers = ("Foo baz", "clucka", "ESRI Shp", "ESRI rast") aliases = { "eSrI": "ESRI Shapefile", "TigER/linE": "TIGER", "SHAPE": "ESRI Shapefile", "sHp": "ESRI Shapefile", "tiFf": "GTiff", "tIf": "GTiff", "jPEg": "JPEG", "jpG": "JPEG", } class DriverTest(unittest.TestCase): def test01_valid_driver(self): "Testing valid GDAL/OGR Data Source Drivers." for d in valid_drivers: dr = Driver(d) self.assertEqual(d, str(dr)) def test02_invalid_driver(self): "Testing invalid GDAL/OGR Data Source Drivers." for i in invalid_drivers: with self.assertRaises(GDALException): Driver(i) def test03_aliases(self): "Testing driver aliases." for alias, full_name in aliases.items(): dr = Driver(alias) self.assertEqual(full_name, str(dr)) @mock.patch("django.contrib.gis.gdal.driver.vcapi.get_driver_count") @mock.patch("django.contrib.gis.gdal.driver.rcapi.get_driver_count") @mock.patch("django.contrib.gis.gdal.driver.vcapi.register_all") @mock.patch("django.contrib.gis.gdal.driver.rcapi.register_all") def test_registered(self, rreg, vreg, rcount, vcount): """ Prototypes are registered only if their respective driver counts are zero. """ def check(rcount_val, vcount_val): vreg.reset_mock() rreg.reset_mock() rcount.return_value = rcount_val vcount.return_value = vcount_val Driver.ensure_registered() if rcount_val: self.assertFalse(rreg.called) else: rreg.assert_called_once_with() if vcount_val: self.assertFalse(vreg.called) else: vreg.assert_called_once_with() check(0, 0) check(120, 0) check(0, 120) check(120, 120)
eed948299d0162227ed7ead0f236e7ae91b6f0ef929597b1ba63e8ef6b9beeb9
from django.contrib.gis.geos import Point from django.test import SimpleTestCase, override_settings from .models import City, site, site_gis, site_gis_custom @override_settings(ROOT_URLCONF="django.contrib.gis.tests.geoadmin.urls") class GeoAdminTest(SimpleTestCase): admin_site = site # ModelAdmin def test_widget_empty_string(self): geoadmin = self.admin_site._registry[City] form = geoadmin.get_changelist_form(None)({"point": ""}) with self.assertRaisesMessage(AssertionError, "no logs"): with self.assertLogs("django.contrib.gis", "ERROR"): output = str(form["point"]) self.assertInHTML( '<textarea id="id_point" class="vSerializedField required" cols="150"' ' rows="10" name="point"></textarea>', output, ) def test_widget_invalid_string(self): geoadmin = self.admin_site._registry[City] form = geoadmin.get_changelist_form(None)({"point": "INVALID()"}) with self.assertLogs("django.contrib.gis", "ERROR") as cm: output = str(form["point"]) self.assertInHTML( '<textarea id="id_point" class="vSerializedField required" cols="150"' ' rows="10" name="point"></textarea>', output, ) self.assertEqual(len(cm.records), 1) self.assertEqual( cm.records[0].getMessage(), "Error creating geometry from value 'INVALID()' (String input " "unrecognized as WKT EWKT, and HEXEWKB.)", ) def test_widget_has_changed(self): geoadmin = self.admin_site._registry[City] form = geoadmin.get_changelist_form(None)() has_changed = form.fields["point"].has_changed initial = Point(13.4197458572965953, 52.5194108501149799, srid=4326) data_same = "SRID=3857;POINT(1493879.2754093995 6894592.019687599)" data_almost_same = "SRID=3857;POINT(1493879.2754093990 6894592.019687590)" data_changed = "SRID=3857;POINT(1493884.0527237 6894593.8111804)" self.assertIs(has_changed(None, data_changed), True) self.assertIs(has_changed(initial, ""), True) self.assertIs(has_changed(None, ""), False) self.assertIs(has_changed(initial, data_same), False) self.assertIs(has_changed(initial, data_almost_same), False) self.assertIs(has_changed(initial, data_changed), True) class GISAdminTests(GeoAdminTest): admin_site = site_gis # GISModelAdmin def test_default_gis_widget_kwargs(self): geoadmin = self.admin_site._registry[City] form = geoadmin.get_changelist_form(None)() widget = form["point"].field.widget self.assertEqual(widget.attrs["default_lat"], 47) self.assertEqual(widget.attrs["default_lon"], 5) self.assertEqual(widget.attrs["default_zoom"], 12) def test_custom_gis_widget_kwargs(self): geoadmin = site_gis_custom._registry[City] form = geoadmin.get_changelist_form(None)() widget = form["point"].field.widget self.assertEqual(widget.attrs["default_lat"], 55) self.assertEqual(widget.attrs["default_lon"], 37) self.assertEqual(widget.attrs["default_zoom"], 12)
61bef269688ad74d640a99257c211e3fc616a712cd7cc54ab1489af420ea9a23
from django.contrib.gis.db import models from ..admin import admin class City(models.Model): name = models.CharField(max_length=30) point = models.PointField() class Meta: app_label = "geoadmin" def __str__(self): return self.name class CityAdminCustomWidgetKwargs(admin.GISModelAdmin): gis_widget_kwargs = { "attrs": { "default_lat": 55, "default_lon": 37, }, } site = admin.AdminSite(name="gis_admin_modeladmin") site.register(City, admin.ModelAdmin) site_gis = admin.AdminSite(name="gis_admin_gismodeladmin") site_gis.register(City, admin.GISModelAdmin) site_gis_custom = admin.AdminSite(name="gis_admin_gismodeladmin") site_gis_custom.register(City, CityAdminCustomWidgetKwargs)
12544a6a016ead9a7074bc009e2f0a35189011ae0935d41e65ae8533a8dea9dc
from django.contrib.gis.db import models from django.db import migrations from django.db.models import deletion class Migration(migrations.Migration): dependencies = [ ("rasterapp", "0001_setup_extensions"), ] operations = [ migrations.CreateModel( name="RasterModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "rast", models.fields.RasterField( blank=True, null=True, srid=4326, verbose_name="A Verbose Raster Name", ), ), ( "rastprojected", models.fields.RasterField( null=True, srid=3086, verbose_name="A Projected Raster Table", ), ), ("geom", models.fields.PointField(null=True, srid=4326)), ], options={ "required_db_features": ["supports_raster"], }, ), migrations.CreateModel( name="RasterRelatedModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "rastermodel", models.ForeignKey( on_delete=deletion.CASCADE, to="rasterapp.rastermodel", ), ), ], options={ "required_db_features": ["supports_raster"], }, ), ]
6a774b9a68d5c180eacdc2bdae0cdd8025c1e8d813a837496527f6fe1e463abe
from django.db import connection, migrations if connection.features.supports_raster: from django.contrib.postgres.operations import CreateExtension pg_version = connection.ops.postgis_version_tuple() class Migration(migrations.Migration): # PostGIS 3+ requires postgis_raster extension. if pg_version[1:] >= (3,): operations = [ CreateExtension("postgis_raster"), ] else: operations = [] else: class Migration(migrations.Migration): operations = []
9143856d9b7b940ce0d5cb35812ead24c700fc09b9415b586b73e5eb1fa70833
from django.contrib.gis.db import models from django.db import connection, migrations ops = [ migrations.CreateModel( name="Neighborhood", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("name", models.CharField(max_length=100, unique=True)), ("geom", models.MultiPolygonField(srid=4326)), ], options={}, bases=(models.Model,), ), migrations.CreateModel( name="Household", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "neighborhood", models.ForeignKey( "gis_migrations.Neighborhood", models.SET_NULL, to_field="id", null=True, ), ), ("address", models.CharField(max_length=100)), ("zip_code", models.IntegerField(null=True, blank=True)), ("geom", models.PointField(srid=4326, geography=True)), ], options={}, bases=(models.Model,), ), migrations.CreateModel( name="Family", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("name", models.CharField(max_length=100, unique=True)), ], options={}, bases=(models.Model,), ), migrations.AddField( model_name="household", name="family", field=models.ForeignKey( "gis_migrations.Family", models.SET_NULL, blank=True, null=True ), preserve_default=True, ), ] if connection.features.supports_raster: ops += [ migrations.CreateModel( name="Heatmap", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("name", models.CharField(max_length=100, unique=True)), ("rast", models.fields.RasterField(srid=4326)), ], options={}, bases=(models.Model,), ), ] class Migration(migrations.Migration): """ Used for gis-specific migration tests. """ dependencies = [ ("gis_migrations", "0001_setup_extensions"), ] operations = ops
91b0fa1641082e791d0f911ccd163cbb7068d65265c3aeb84a4c7ba85c915149
from django.db import models class Article(models.Model): headline = models.CharField(max_length=100, default="Default headline") pub_date = models.DateTimeField() class Meta: app_label = "fixtures_model_package" ordering = ("-pub_date", "headline") def __str__(self): return self.headline
b4be1e0246f236bdcd9df5726466eb0c2ef651590e4a73de3a4f5c5fc40c0769
from .article import Article, ArticleIdea, ArticleTag, ArticleTranslation, NewsArticle from .customers import Address, Contact, Customer from .empty_join import SlugPage from .person import Country, Friendship, Group, Membership, Person __all__ = [ "Address", "Article", "ArticleIdea", "ArticleTag", "ArticleTranslation", "Contact", "Country", "Customer", "Friendship", "Group", "Membership", "NewsArticle", "Person", "SlugPage", ]
e057f0e50aec09146047d00da2059a738458ee6a307902ca9cd0b4c46c8edc96
from django.db import models from django.db.models.fields.related import ReverseManyToOneDescriptor from django.db.models.lookups import StartsWith from django.db.models.query_utils import PathInfo class CustomForeignObjectRel(models.ForeignObjectRel): """ Define some extra Field methods so this Rel acts more like a Field, which lets us use ReverseManyToOneDescriptor in both directions. """ @property def foreign_related_fields(self): return tuple(lhs_field for lhs_field, rhs_field in self.field.related_fields) def get_attname(self): return self.name class StartsWithRelation(models.ForeignObject): """ A ForeignObject that uses StartsWith operator in its joins instead of the default equality operator. This is logically a many-to-many relation and creates a ReverseManyToOneDescriptor in both directions. """ auto_created = False many_to_many = False many_to_one = True one_to_many = False one_to_one = False rel_class = CustomForeignObjectRel def __init__(self, *args, **kwargs): kwargs["on_delete"] = models.DO_NOTHING super().__init__(*args, **kwargs) @property def field(self): """ Makes ReverseManyToOneDescriptor work in both directions. """ return self.remote_field def get_extra_restriction(self, alias, related_alias): to_field = self.remote_field.model._meta.get_field(self.to_fields[0]) from_field = self.model._meta.get_field(self.from_fields[0]) return StartsWith(to_field.get_col(alias), from_field.get_col(related_alias)) def get_joining_columns(self, reverse_join=False): return () def get_path_info(self, filtered_relation=None): to_opts = self.remote_field.model._meta from_opts = self.model._meta return [ PathInfo( from_opts=from_opts, to_opts=to_opts, target_fields=(to_opts.pk,), join_field=self, m2m=False, direct=False, filtered_relation=filtered_relation, ) ] def get_reverse_path_info(self, filtered_relation=None): to_opts = self.model._meta from_opts = self.remote_field.model._meta return [ PathInfo( from_opts=from_opts, to_opts=to_opts, target_fields=(to_opts.pk,), join_field=self.remote_field, m2m=False, direct=False, filtered_relation=filtered_relation, ) ] def contribute_to_class(self, cls, name, private_only=False): super().contribute_to_class(cls, name, private_only) setattr(cls, self.name, ReverseManyToOneDescriptor(self)) class BrokenContainsRelation(StartsWithRelation): """ This model is designed to yield no join conditions and raise an exception in ``Join.as_sql()``. """ def get_extra_restriction(self, alias, related_alias): return None class SlugPage(models.Model): slug = models.CharField(max_length=20, unique=True) descendants = StartsWithRelation( "self", from_fields=["slug"], to_fields=["slug"], related_name="ascendants", ) containers = BrokenContainsRelation( "self", from_fields=["slug"], to_fields=["slug"], ) class Meta: ordering = ["slug"] def __str__(self): return "SlugPage %s" % self.slug
0b0c46b1d0cf8a5a6e81b28443546e5692263aff19eca7d8e9331aabb06550e2
import datetime from django.db import models class Country(models.Model): # Table Column Fields name = models.CharField(max_length=50) def __str__(self): return self.name class Person(models.Model): # Table Column Fields name = models.CharField(max_length=128) person_country_id = models.IntegerField() # Relation Fields person_country = models.ForeignObject( Country, from_fields=["person_country_id"], to_fields=["id"], on_delete=models.CASCADE, ) friends = models.ManyToManyField("self", through="Friendship", symmetrical=False) class Meta: ordering = ("name",) def __str__(self): return self.name class Group(models.Model): # Table Column Fields name = models.CharField(max_length=128) group_country = models.ForeignKey(Country, models.CASCADE) members = models.ManyToManyField( Person, related_name="groups", through="Membership" ) class Meta: ordering = ("name",) def __str__(self): return self.name class Membership(models.Model): # Table Column Fields membership_country = models.ForeignKey(Country, models.CASCADE) date_joined = models.DateTimeField(default=datetime.datetime.now) invite_reason = models.CharField(max_length=64, null=True) person_id = models.IntegerField() group_id = models.IntegerField(blank=True, null=True) # Relation Fields person = models.ForeignObject( Person, from_fields=["person_id", "membership_country"], to_fields=["id", "person_country_id"], on_delete=models.CASCADE, ) group = models.ForeignObject( Group, from_fields=["group_id", "membership_country"], to_fields=["id", "group_country"], on_delete=models.CASCADE, ) class Meta: ordering = ("date_joined", "invite_reason") def __str__(self): group_name = self.group.name if self.group_id else "NULL" return "%s is a member of %s" % (self.person.name, group_name) class Friendship(models.Model): # Table Column Fields from_friend_country = models.ForeignKey( Country, models.CASCADE, related_name="from_friend_country" ) from_friend_id = models.IntegerField() to_friend_country_id = models.IntegerField() to_friend_id = models.IntegerField() # Relation Fields from_friend = models.ForeignObject( Person, on_delete=models.CASCADE, from_fields=["from_friend_country", "from_friend_id"], to_fields=["person_country_id", "id"], related_name="from_friend", ) to_friend_country = models.ForeignObject( Country, from_fields=["to_friend_country_id"], to_fields=["id"], related_name="to_friend_country", on_delete=models.CASCADE, ) to_friend = models.ForeignObject( Person, from_fields=["to_friend_country_id", "to_friend_id"], to_fields=["person_country_id", "id"], related_name="to_friend", on_delete=models.CASCADE, )
96c0c980f560a11bd2c7e14d99bc219f73e866dd44aba91e6e8086393758df24
from django.db import models class Address(models.Model): company = models.CharField(max_length=1) customer_id = models.IntegerField() class Meta: unique_together = [ ("company", "customer_id"), ] class Customer(models.Model): company = models.CharField(max_length=1) customer_id = models.IntegerField() address = models.ForeignObject( Address, models.CASCADE, null=True, # order mismatches the Contact ForeignObject. from_fields=["company", "customer_id"], to_fields=["company", "customer_id"], ) class Meta: unique_together = [ ("company", "customer_id"), ] class Contact(models.Model): company_code = models.CharField(max_length=1) customer_code = models.IntegerField() customer = models.ForeignObject( Customer, models.CASCADE, related_name="contacts", to_fields=["customer_id", "company"], from_fields=["customer_code", "company_code"], )
ff2423551423f9b4842da1dc6aea0d81dbe5ddbae10413ba1df9076f3a116db9
from django.db import models from django.db.models.fields.related import ForwardManyToOneDescriptor from django.utils.translation import get_language class ArticleTranslationDescriptor(ForwardManyToOneDescriptor): """ The set of articletranslation should not set any local fields. """ def __set__(self, instance, value): if instance is None: raise AttributeError("%s must be accessed via instance" % self.field.name) self.field.set_cached_value(instance, value) if value is not None and not self.field.remote_field.multiple: self.field.remote_field.set_cached_value(value, instance) class ColConstraint: # Anything with as_sql() method works in get_extra_restriction(). def __init__(self, alias, col, value): self.alias, self.col, self.value = alias, col, value def as_sql(self, compiler, connection): qn = compiler.quote_name_unless_alias return "%s.%s = %%s" % (qn(self.alias), qn(self.col)), [self.value] class ActiveTranslationField(models.ForeignObject): """ This field will allow querying and fetching the currently active translation for Article from ArticleTranslation. """ requires_unique_target = False def get_extra_restriction(self, alias, related_alias): return ColConstraint(alias, "lang", get_language()) def get_extra_descriptor_filter(self, instance): return {"lang": get_language()} def contribute_to_class(self, cls, name): super().contribute_to_class(cls, name) setattr(cls, self.name, ArticleTranslationDescriptor(self)) class ActiveTranslationFieldWithQ(ActiveTranslationField): def get_extra_descriptor_filter(self, instance): return models.Q(lang=get_language()) class Article(models.Model): active_translation = ActiveTranslationField( "ArticleTranslation", from_fields=["id"], to_fields=["article"], related_name="+", on_delete=models.CASCADE, null=True, ) active_translation_q = ActiveTranslationFieldWithQ( "ArticleTranslation", from_fields=["id"], to_fields=["article"], related_name="+", on_delete=models.CASCADE, null=True, ) pub_date = models.DateField() def __str__(self): try: return self.active_translation.title except ArticleTranslation.DoesNotExist: return "[No translation found]" class NewsArticle(Article): pass class ArticleTranslation(models.Model): article = models.ForeignKey(Article, models.CASCADE) lang = models.CharField(max_length=2) title = models.CharField(max_length=100) body = models.TextField() abstract = models.TextField(null=True) class Meta: unique_together = ("article", "lang") class ArticleTag(models.Model): article = models.ForeignKey( Article, models.CASCADE, related_name="tags", related_query_name="tag", ) name = models.CharField(max_length=255) class ArticleIdea(models.Model): articles = models.ManyToManyField( Article, related_name="ideas", related_query_name="idea_things", ) name = models.CharField(max_length=255)
bd2ba9d502cea8300d17497b3ced72e195035fe0f704aaa0cf7ccd1bd983c139
from django.db import models # Since the test database doesn't have tablespaces, it's impossible for Django # to create the tables for models where db_tablespace is set. To avoid this # problem, we mark the models as unmanaged, and temporarily revert them to # managed during each test. We also set them to use the same tables as the # "reference" models to avoid errors when other tests run 'migrate' # (proxy_models_inheritance does). class ScientistRef(models.Model): name = models.CharField(max_length=50) class ArticleRef(models.Model): title = models.CharField(max_length=50, unique=True) code = models.CharField(max_length=50, unique=True) authors = models.ManyToManyField(ScientistRef, related_name="articles_written_set") reviewers = models.ManyToManyField( ScientistRef, related_name="articles_reviewed_set" ) class Scientist(models.Model): name = models.CharField(max_length=50) class Meta: db_table = "model_options_scientistref" db_tablespace = "tbl_tbsp" managed = False class Article(models.Model): title = models.CharField(max_length=50, unique=True) code = models.CharField(max_length=50, unique=True, db_tablespace="idx_tbsp") authors = models.ManyToManyField(Scientist, related_name="articles_written_set") reviewers = models.ManyToManyField( Scientist, related_name="articles_reviewed_set", db_tablespace="idx_tbsp" ) class Meta: db_table = "model_options_articleref" db_tablespace = "tbl_tbsp" managed = False # Also set the tables for automatically created models Authors = Article._meta.get_field("authors").remote_field.through Authors._meta.db_table = "model_options_articleref_authors" Reviewers = Article._meta.get_field("reviewers").remote_field.through Reviewers._meta.db_table = "model_options_articleref_reviewers"
028329f5742d9886cd1eacc8f611274d8650e04ef28c9e1de610c227b58c76d9
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("sites", "0001_initial"), ] operations = [ migrations.CreateModel( name="CustomArticle", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("title", models.CharField(max_length=50)), ( "places_this_article_should_appear", models.ForeignKey("sites.Site", models.CASCADE), ), ], options={ "abstract": False, }, bases=(models.Model,), ), migrations.CreateModel( name="ExclusiveArticle", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("title", models.CharField(max_length=50)), ("site", models.ForeignKey("sites.Site", models.CASCADE)), ], options={ "abstract": False, }, bases=(models.Model,), ), migrations.CreateModel( name="SyndicatedArticle", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("title", models.CharField(max_length=50)), ("sites", models.ManyToManyField("sites.Site")), ], options={ "abstract": False, }, bases=(models.Model,), ), ]
0a55ac4c2700fdd38088539d9664f97de4abe075ae62d91592e56e4fabd94943
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("db_functions", "0001_setup_extensions"), ] operations = [ migrations.CreateModel( name="Author", fields=[ ("name", models.CharField(max_length=50)), ("alias", models.CharField(max_length=50, null=True, blank=True)), ("goes_by", models.CharField(max_length=50, null=True, blank=True)), ("age", models.PositiveSmallIntegerField(default=30)), ], ), migrations.CreateModel( name="Article", fields=[ ( "authors", models.ManyToManyField( "db_functions.Author", related_name="articles" ), ), ("title", models.CharField(max_length=50)), ("summary", models.CharField(max_length=200, null=True, blank=True)), ("text", models.TextField()), ("written", models.DateTimeField()), ("published", models.DateTimeField(null=True, blank=True)), ("updated", models.DateTimeField(null=True, blank=True)), ("views", models.PositiveIntegerField(default=0)), ], ), migrations.CreateModel( name="Fan", fields=[ ("name", models.CharField(max_length=50)), ("age", models.PositiveSmallIntegerField(default=30)), ( "author", models.ForeignKey( "db_functions.Author", models.CASCADE, related_name="fans" ), ), ("fan_since", models.DateTimeField(null=True, blank=True)), ], ), migrations.CreateModel( name="DTModel", fields=[ ("name", models.CharField(max_length=32)), ("start_datetime", models.DateTimeField(null=True, blank=True)), ("end_datetime", models.DateTimeField(null=True, blank=True)), ("start_date", models.DateField(null=True, blank=True)), ("end_date", models.DateField(null=True, blank=True)), ("start_time", models.TimeField(null=True, blank=True)), ("end_time", models.TimeField(null=True, blank=True)), ("duration", models.DurationField(null=True, blank=True)), ], ), migrations.CreateModel( name="DecimalModel", fields=[ ("n1", models.DecimalField(decimal_places=2, max_digits=6)), ( "n2", models.DecimalField( decimal_places=7, max_digits=9, null=True, blank=True ), ), ], ), migrations.CreateModel( name="IntegerModel", fields=[ ("big", models.BigIntegerField(null=True, blank=True)), ("normal", models.IntegerField(null=True, blank=True)), ("small", models.SmallIntegerField(null=True, blank=True)), ], ), migrations.CreateModel( name="FloatModel", fields=[ ("f1", models.FloatField(null=True, blank=True)), ("f2", models.FloatField(null=True, blank=True)), ], ), ]
3ac8c0b5b1a7c3a045aab3079c15a645baecc528f9ba83b92c9b23425399d2bf
from django.db import connection from django.db.models import CharField from django.db.models.functions import SHA512 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA512Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ] ) def test_basic(self): authors = ( Author.objects.annotate( sha512_alias=SHA512("alias"), ) .values_list("sha512_alias", flat=True) .order_by("pk") ) self.assertSequenceEqual( authors, [ "ed014a19bb67a85f9c8b1d81e04a0e7101725be8627d79d02ca4f3bd803f33cf" "3b8fed53e80d2a12c0d0e426824d99d110f0919298a5055efff040a3fc091518", "b09c449f3ba49a32ab44754982d4749ac938af293e4af2de28858858080a1611" "2b719514b5e48cb6ce54687e843a4b3e69a04cdb2a9dc99c3b99bdee419fa7d0", "b554d182e25fb487a3f2b4285bb8672f98956b5369138e681b467d1f079af116" "172d88798345a3a7666faf5f35a144c60812d3234dcd35f444624f2faee16857", "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e" if connection.features.interprets_empty_strings_as_nulls else None, ], ) def test_transform(self): with register_lookup(CharField, SHA512): authors = Author.objects.filter( alias__sha512=( "ed014a19bb67a85f9c8b1d81e04a0e7101725be8627d79d02ca4f3bd8" "03f33cf3b8fed53e80d2a12c0d0e426824d99d110f0919298a5055eff" "f040a3fc091518" ), ).values_list("alias", flat=True) self.assertSequenceEqual(authors, ["John Smith"])
c3b0f10b534d7f4eec7f880f47756700ca8dd98fc97f44acf1a295ac783be171
from django.db.models import Value from django.db.models.functions import StrIndex from django.test import TestCase from django.utils import timezone from ..models import Article, Author class StrIndexTests(TestCase): def test_annotate_charfield(self): Author.objects.create(name="George. R. R. Martin") Author.objects.create(name="J. R. R. Tolkien") Author.objects.create(name="Terry Pratchett") authors = Author.objects.annotate(fullstop=StrIndex("name", Value("R."))) self.assertQuerysetEqual( authors.order_by("name"), [9, 4, 0], lambda a: a.fullstop ) def test_annotate_textfield(self): Article.objects.create( title="How to Django", text="This is about How to Django.", written=timezone.now(), ) Article.objects.create( title="How to Tango", text="Won't find anything here.", written=timezone.now(), ) articles = Article.objects.annotate(title_pos=StrIndex("text", "title")) self.assertQuerysetEqual( articles.order_by("title"), [15, 0], lambda a: a.title_pos ) def test_order_by(self): Author.objects.create(name="Terry Pratchett") Author.objects.create(name="J. R. R. Tolkien") Author.objects.create(name="George. R. R. Martin") self.assertQuerysetEqual( Author.objects.order_by(StrIndex("name", Value("R.")).asc()), [ "Terry Pratchett", "J. R. R. Tolkien", "George. R. R. Martin", ], lambda a: a.name, ) self.assertQuerysetEqual( Author.objects.order_by(StrIndex("name", Value("R.")).desc()), [ "George. R. R. Martin", "J. R. R. Tolkien", "Terry Pratchett", ], lambda a: a.name, ) def test_unicode_values(self): Author.objects.create(name="ツリー") Author.objects.create(name="皇帝") Author.objects.create(name="皇帝 ツリー") authors = Author.objects.annotate(sb=StrIndex("name", Value("リ"))) self.assertQuerysetEqual(authors.order_by("name"), [2, 0, 5], lambda a: a.sb) def test_filtering(self): Author.objects.create(name="George. R. R. Martin") Author.objects.create(name="Terry Pratchett") self.assertQuerysetEqual( Author.objects.annotate(middle_name=StrIndex("name", Value("R."))).filter( middle_name__gt=0 ), ["George. R. R. Martin"], lambda a: a.name, )
8fe70008e6139a7c54efa1a3527121c237f4d7279dd2c8ab3fad4c071be0d1f2
from django.db import connection from django.db.models import CharField from django.db.models.functions import Length, Reverse, Trim from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class ReverseTests(TestCase): @classmethod def setUpTestData(cls): cls.john = Author.objects.create(name="John Smith", alias="smithj") cls.elena = Author.objects.create(name="Élena Jordan", alias="elena") cls.python = Author.objects.create(name="パイソン") def test_null(self): author = Author.objects.annotate(backward=Reverse("alias")).get( pk=self.python.pk ) self.assertEqual( author.backward, "" if connection.features.interprets_empty_strings_as_nulls else None, ) def test_basic(self): authors = Author.objects.annotate(backward=Reverse("name")) self.assertQuerysetEqual( authors, [ ("John Smith", "htimS nhoJ"), ("Élena Jordan", "nadroJ anelÉ"), ("パイソン", "ンソイパ"), ], lambda a: (a.name, a.backward), ordered=False, ) def test_transform(self): with register_lookup(CharField, Reverse): authors = Author.objects.all() self.assertCountEqual( authors.filter(name__reverse=self.john.name[::-1]), [self.john] ) self.assertCountEqual( authors.exclude(name__reverse=self.john.name[::-1]), [self.elena, self.python], ) def test_expressions(self): author = Author.objects.annotate(backward=Reverse(Trim("name"))).get( pk=self.john.pk ) self.assertEqual(author.backward, self.john.name[::-1]) with register_lookup(CharField, Reverse), register_lookup(CharField, Length): authors = Author.objects.all() self.assertCountEqual( authors.filter(name__reverse__length__gt=7), [self.john, self.elena] ) self.assertCountEqual( authors.exclude(name__reverse__length__gt=7), [self.python] )
9be3983b630c3965495bc705f19388666659ea37b11d106693d53744cd1819d2
from django.db.models import IntegerField from django.db.models.functions import Chr, Left, Ord from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class ChrTests(TestCase): @classmethod def setUpTestData(cls): cls.john = Author.objects.create(name="John Smith", alias="smithj") cls.elena = Author.objects.create(name="Élena Jordan", alias="elena") cls.rhonda = Author.objects.create(name="Rhonda") def test_basic(self): authors = Author.objects.annotate(first_initial=Left("name", 1)) self.assertCountEqual(authors.filter(first_initial=Chr(ord("J"))), [self.john]) self.assertCountEqual( authors.exclude(first_initial=Chr(ord("J"))), [self.elena, self.rhonda] ) def test_non_ascii(self): authors = Author.objects.annotate(first_initial=Left("name", 1)) self.assertCountEqual(authors.filter(first_initial=Chr(ord("É"))), [self.elena]) self.assertCountEqual( authors.exclude(first_initial=Chr(ord("É"))), [self.john, self.rhonda] ) def test_transform(self): with register_lookup(IntegerField, Chr): authors = Author.objects.annotate(name_code_point=Ord("name")) self.assertCountEqual( authors.filter(name_code_point__chr=Chr(ord("J"))), [self.john] ) self.assertCountEqual( authors.exclude(name_code_point__chr=Chr(ord("J"))), [self.elena, self.rhonda], )
e7064f03a9cae83e2410c78da371eeaeaec1ff3ddddd7bfff3beaa1de53b235f
from django.db import connection from django.db.models import Value from django.db.models.functions import Length, Repeat from django.test import TestCase from ..models import Author class RepeatTests(TestCase): def test_basic(self): Author.objects.create(name="John", alias="xyz") none_value = ( "" if connection.features.interprets_empty_strings_as_nulls else None ) tests = ( (Repeat("name", 0), ""), (Repeat("name", 2), "JohnJohn"), (Repeat("name", Length("alias")), "JohnJohnJohn"), (Repeat(Value("x"), 3), "xxx"), (Repeat("name", None), none_value), (Repeat(Value(None), 4), none_value), (Repeat("goes_by", 1), none_value), ) for function, repeated_text in tests: with self.subTest(function=function): authors = Author.objects.annotate(repeated_text=function) self.assertQuerysetEqual( authors, [repeated_text], lambda a: a.repeated_text, ordered=False ) def test_negative_number(self): with self.assertRaisesMessage( ValueError, "'number' must be greater or equal to 0." ): Repeat("name", -1)
f1836fc0fe2a74bd9b885b4c1a8547b2c4b50da151dcf21009e18242860fb17a
from django.db import connection from django.db.models import CharField from django.db.models.functions import SHA256 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA256Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ] ) def test_basic(self): authors = ( Author.objects.annotate( sha256_alias=SHA256("alias"), ) .values_list("sha256_alias", flat=True) .order_by("pk") ) self.assertSequenceEqual( authors, [ "ef61a579c907bbed674c0dbcbcf7f7af8f851538eef7b8e58c5bee0b8cfdac4a", "6e4cce20cd83fc7c202f21a8b2452a68509cf24d1c272a045b5e0cfc43f0d94e", "3ad2039e3ec0c88973ae1c0fce5a3dbafdd5a1627da0a92312c54ebfcf43988e", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" if connection.features.interprets_empty_strings_as_nulls else None, ], ) def test_transform(self): with register_lookup(CharField, SHA256): authors = Author.objects.filter( alias__sha256=( "ef61a579c907bbed674c0dbcbcf7f7af8f851538eef7b8e58c5bee0b8cfdac4a" ), ).values_list("alias", flat=True) self.assertSequenceEqual(authors, ["John Smith"])
0a5bf193c731423dc925cd6c44db9e148ab8789c7f0ca6bac3585e25a145953d
from django.db import connection from django.db.models import CharField from django.db.models.functions import SHA384 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA384Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ] ) def test_basic(self): authors = ( Author.objects.annotate( sha384_alias=SHA384("alias"), ) .values_list("sha384_alias", flat=True) .order_by("pk") ) self.assertSequenceEqual( authors, [ "9df976bfbcf96c66fbe5cba866cd4deaa8248806f15b69c4010a404112906e4ca7b57e" "53b9967b80d77d4f5c2982cbc8", "72202c8005492016cc670219cce82d47d6d2d4273464c742ab5811d691b1e82a748954" "9e3a73ffa119694f90678ba2e3", "eda87fae41e59692c36c49e43279c8111a00d79122a282a944e8ba9a403218f049a483" "26676a43c7ba378621175853b0", "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274ede" "bfe76f65fbd51ad2f14898b95b", "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274ede" "bfe76f65fbd51ad2f14898b95b" if connection.features.interprets_empty_strings_as_nulls else None, ], ) def test_transform(self): with register_lookup(CharField, SHA384): authors = Author.objects.filter( alias__sha384=( "9df976bfbcf96c66fbe5cba866cd4deaa8248806f15b69c4010a404112906e4ca7" "b57e53b9967b80d77d4f5c2982cbc8" ), ).values_list("alias", flat=True) self.assertSequenceEqual(authors, ["John Smith"])
d12d6b5928e06cb83c53c524b74158fc9988cc671f8580543fc155f2909fcf00
import unittest from django.db import NotSupportedError, connection from django.db.models import CharField from django.db.models.functions import SHA224 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA224Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ] ) def test_basic(self): authors = ( Author.objects.annotate( sha224_alias=SHA224("alias"), ) .values_list("sha224_alias", flat=True) .order_by("pk") ) self.assertSequenceEqual( authors, [ "a61303c220731168452cb6acf3759438b1523e768f464e3704e12f70", "2297904883e78183cb118fc3dc21a610d60daada7b6ebdbc85139f4d", "eba942746e5855121d9d8f79e27dfdebed81adc85b6bf41591203080", "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f" if connection.features.interprets_empty_strings_as_nulls else None, ], ) def test_transform(self): with register_lookup(CharField, SHA224): authors = Author.objects.filter( alias__sha224=( "a61303c220731168452cb6acf3759438b1523e768f464e3704e12f70" ), ).values_list("alias", flat=True) self.assertSequenceEqual(authors, ["John Smith"]) @unittest.skipUnless( connection.vendor == "oracle", "Oracle doesn't support SHA224." ) def test_unsupported(self): msg = "SHA224 is not supported on Oracle." with self.assertRaisesMessage(NotSupportedError, msg): Author.objects.annotate(sha224_alias=SHA224("alias")).first()
fdd741707dddbc6c3efd45a00de4bbfeef30e3b93df816094a069d46a25e647a
from django.db.models import CharField from django.db.models.functions import Lower from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class LowerTests(TestCase): def test_basic(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.annotate(lower_name=Lower("name")) self.assertQuerysetEqual( authors.order_by("name"), ["john smith", "rhonda"], lambda a: a.lower_name ) Author.objects.update(name=Lower("name")) self.assertQuerysetEqual( authors.order_by("name"), [ ("john smith", "john smith"), ("rhonda", "rhonda"), ], lambda a: (a.lower_name, a.name), ) def test_num_args(self): with self.assertRaisesMessage( TypeError, "'Lower' takes exactly 1 argument (2 given)" ): Author.objects.update(name=Lower("name", "name")) def test_transform(self): with register_lookup(CharField, Lower): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.filter(name__lower__exact="john smith") self.assertQuerysetEqual( authors.order_by("name"), ["John Smith"], lambda a: a.name )
8efeb68caa3d1e9e754ec413dbfb1b47d72b8bb7d2b31ddb51bafe6700c0abf3
from django.db.models import IntegerField, Value from django.db.models.functions import Lower, Right from django.test import TestCase from ..models import Author class RightTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") def test_basic(self): authors = Author.objects.annotate(name_part=Right("name", 5)) self.assertQuerysetEqual( authors.order_by("name"), ["Smith", "honda"], lambda a: a.name_part ) # If alias is null, set it to the first 2 lower characters of the name. Author.objects.filter(alias__isnull=True).update(alias=Lower(Right("name", 2))) self.assertQuerysetEqual( authors.order_by("name"), ["smithj", "da"], lambda a: a.alias ) def test_invalid_length(self): with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"): Author.objects.annotate(raises=Right("name", 0)) def test_expressions(self): authors = Author.objects.annotate( name_part=Right("name", Value(3, output_field=IntegerField())) ) self.assertQuerysetEqual( authors.order_by("name"), ["ith", "nda"], lambda a: a.name_part )
899c1ff47f23ea6211bd2b18edf5d53c1ec67bff655582f4c8054d81b418299d
from django.db.models import F, Value from django.db.models.functions import Concat, Replace from django.test import TestCase from ..models import Author class ReplaceTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name="George R. R. Martin") Author.objects.create(name="J. R. R. Tolkien") def test_replace_with_empty_string(self): qs = Author.objects.annotate( without_middlename=Replace(F("name"), Value("R. R. "), Value("")), ) self.assertQuerysetEqual( qs, [ ("George R. R. Martin", "George Martin"), ("J. R. R. Tolkien", "J. Tolkien"), ], transform=lambda x: (x.name, x.without_middlename), ordered=False, ) def test_case_sensitive(self): qs = Author.objects.annotate( same_name=Replace(F("name"), Value("r. r."), Value("")) ) self.assertQuerysetEqual( qs, [ ("George R. R. Martin", "George R. R. Martin"), ("J. R. R. Tolkien", "J. R. R. Tolkien"), ], transform=lambda x: (x.name, x.same_name), ordered=False, ) def test_replace_expression(self): qs = Author.objects.annotate( same_name=Replace( Concat(Value("Author: "), F("name")), Value("Author: "), Value("") ), ) self.assertQuerysetEqual( qs, [ ("George R. R. Martin", "George R. R. Martin"), ("J. R. R. Tolkien", "J. R. R. Tolkien"), ], transform=lambda x: (x.name, x.same_name), ordered=False, ) def test_update(self): Author.objects.update( name=Replace(F("name"), Value("R. R. "), Value("")), ) self.assertQuerysetEqual( Author.objects.all(), [ ("George Martin"), ("J. Tolkien"), ], transform=lambda x: x.name, ordered=False, ) def test_replace_with_default_arg(self): # The default replacement is an empty string. qs = Author.objects.annotate(same_name=Replace(F("name"), Value("R. R. "))) self.assertQuerysetEqual( qs, [ ("George R. R. Martin", "George Martin"), ("J. R. R. Tolkien", "J. Tolkien"), ], transform=lambda x: (x.name, x.same_name), ordered=False, )
28e8c1ad4042de6d781819adde6f99054d535bfb3790bf91d462161e91ece038
from django.db.models import IntegerField, Value from django.db.models.functions import Left, Lower from django.test import TestCase from ..models import Author class LeftTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") def test_basic(self): authors = Author.objects.annotate(name_part=Left("name", 5)) self.assertQuerysetEqual( authors.order_by("name"), ["John ", "Rhond"], lambda a: a.name_part ) # If alias is null, set it to the first 2 lower characters of the name. Author.objects.filter(alias__isnull=True).update(alias=Lower(Left("name", 2))) self.assertQuerysetEqual( authors.order_by("name"), ["smithj", "rh"], lambda a: a.alias ) def test_invalid_length(self): with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"): Author.objects.annotate(raises=Left("name", 0)) def test_expressions(self): authors = Author.objects.annotate( name_part=Left("name", Value(3, output_field=IntegerField())) ) self.assertQuerysetEqual( authors.order_by("name"), ["Joh", "Rho"], lambda a: a.name_part )
e9ee22ae0abbaa8943787711bf1675532a73a61c8e38523b8b30abb0b10dbc76
from unittest import skipUnless from django.db import connection from django.db.models import CharField, TextField from django.db.models import Value as V from django.db.models.functions import Concat, ConcatPair, Upper from django.test import TestCase from django.utils import timezone from ..models import Article, Author lorem_ipsum = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" class ConcatTests(TestCase): def test_basic(self): Author.objects.create(name="Jayden") Author.objects.create(name="John Smith", alias="smithj", goes_by="John") Author.objects.create(name="Margaret", goes_by="Maggie") Author.objects.create(name="Rhonda", alias="adnohR") authors = Author.objects.annotate(joined=Concat("alias", "goes_by")) self.assertQuerysetEqual( authors.order_by("name"), [ "", "smithjJohn", "Maggie", "adnohR", ], lambda a: a.joined, ) def test_gt_two_expressions(self): with self.assertRaisesMessage( ValueError, "Concat must take at least two expressions" ): Author.objects.annotate(joined=Concat("alias")) def test_many(self): Author.objects.create(name="Jayden") Author.objects.create(name="John Smith", alias="smithj", goes_by="John") Author.objects.create(name="Margaret", goes_by="Maggie") Author.objects.create(name="Rhonda", alias="adnohR") authors = Author.objects.annotate( joined=Concat("name", V(" ("), "goes_by", V(")"), output_field=CharField()), ) self.assertQuerysetEqual( authors.order_by("name"), [ "Jayden ()", "John Smith (John)", "Margaret (Maggie)", "Rhonda ()", ], lambda a: a.joined, ) def test_mixed_char_text(self): Article.objects.create( title="The Title", text=lorem_ipsum, written=timezone.now() ) article = Article.objects.annotate( title_text=Concat("title", V(" - "), "text", output_field=TextField()), ).get(title="The Title") self.assertEqual(article.title + " - " + article.text, article.title_text) # Wrap the concat in something else to ensure that text is returned # rather than bytes. article = Article.objects.annotate( title_text=Upper( Concat("title", V(" - "), "text", output_field=TextField()) ), ).get(title="The Title") expected = article.title + " - " + article.text self.assertEqual(expected.upper(), article.title_text) @skipUnless(connection.vendor == "sqlite", "sqlite specific implementation detail.") def test_coalesce_idempotent(self): pair = ConcatPair(V("a"), V("b")) # Check nodes counts self.assertEqual(len(list(pair.flatten())), 3) self.assertEqual( len(list(pair.coalesce().flatten())), 7 ) # + 2 Coalesce + 2 Value() self.assertEqual(len(list(pair.flatten())), 3) def test_sql_generation_idempotency(self): qs = Article.objects.annotate(description=Concat("title", V(": "), "summary")) # Multiple compilations should not alter the generated query. self.assertEqual(str(qs.query), str(qs.all().query))
cd82d531a92e8946a98e6e79e5ad4aa00fc52257d9e10e352699c881489f62c8
from django.db import connection from django.db.models import CharField from django.db.models.functions import SHA1 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA1Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ] ) def test_basic(self): authors = ( Author.objects.annotate( sha1_alias=SHA1("alias"), ) .values_list("sha1_alias", flat=True) .order_by("pk") ) self.assertSequenceEqual( authors, [ "e61a3587b3f7a142b8c7b9263c82f8119398ecb7", "0781e0745a2503e6ded05ed5bc554c421d781b0c", "198d15ea139de04060caf95bc3e0ec5883cba881", "da39a3ee5e6b4b0d3255bfef95601890afd80709", "da39a3ee5e6b4b0d3255bfef95601890afd80709" if connection.features.interprets_empty_strings_as_nulls else None, ], ) def test_transform(self): with register_lookup(CharField, SHA1): authors = Author.objects.filter( alias__sha1="e61a3587b3f7a142b8c7b9263c82f8119398ecb7", ).values_list("alias", flat=True) self.assertSequenceEqual(authors, ["John Smith"])
ca35a6ce3c8e7aebf7a503d241eeeefe130b5dbfc069b6ad955c77afa3366dde
from django.db.models import CharField, Value from django.db.models.functions import Left, Ord from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class OrdTests(TestCase): @classmethod def setUpTestData(cls): cls.john = Author.objects.create(name="John Smith", alias="smithj") cls.elena = Author.objects.create(name="Élena Jordan", alias="elena") cls.rhonda = Author.objects.create(name="Rhonda") def test_basic(self): authors = Author.objects.annotate(name_part=Ord("name")) self.assertCountEqual( authors.filter(name_part__gt=Ord(Value("John"))), [self.elena, self.rhonda] ) self.assertCountEqual( authors.exclude(name_part__gt=Ord(Value("John"))), [self.john] ) def test_transform(self): with register_lookup(CharField, Ord): authors = Author.objects.annotate(first_initial=Left("name", 1)) self.assertCountEqual( authors.filter(first_initial__ord=ord("J")), [self.john] ) self.assertCountEqual( authors.exclude(first_initial__ord=ord("J")), [self.elena, self.rhonda] )
7de34abcacdadfb50751e72d7c4be4797c23790a147ac27e5c3079a196da85ae
from django.db.models import CharField from django.db.models.functions import Length from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class LengthTests(TestCase): def test_basic(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.annotate( name_length=Length("name"), alias_length=Length("alias"), ) self.assertQuerysetEqual( authors.order_by("name"), [(10, 6), (6, None)], lambda a: (a.name_length, a.alias_length), ) self.assertEqual(authors.filter(alias_length__lte=Length("name")).count(), 1) def test_ordering(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="John Smith", alias="smithj1") Author.objects.create(name="Rhonda", alias="ronny") authors = Author.objects.order_by(Length("name"), Length("alias")) self.assertQuerysetEqual( authors, [ ("Rhonda", "ronny"), ("John Smith", "smithj"), ("John Smith", "smithj1"), ], lambda a: (a.name, a.alias), ) def test_transform(self): with register_lookup(CharField, Length): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.filter(name__length__gt=7) self.assertQuerysetEqual( authors.order_by("name"), ["John Smith"], lambda a: a.name )
d11f31028c4e1f8e1c7c85fb4175e1726235e22425b8946478befd8cbc281e2b
from django.db.models import CharField from django.db.models.functions import Upper from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class UpperTests(TestCase): def test_basic(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.annotate(upper_name=Upper("name")) self.assertQuerysetEqual( authors.order_by("name"), [ "JOHN SMITH", "RHONDA", ], lambda a: a.upper_name, ) Author.objects.update(name=Upper("name")) self.assertQuerysetEqual( authors.order_by("name"), [ ("JOHN SMITH", "JOHN SMITH"), ("RHONDA", "RHONDA"), ], lambda a: (a.upper_name, a.name), ) def test_transform(self): with register_lookup(CharField, Upper): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.filter(name__upper__exact="JOHN SMITH") self.assertQuerysetEqual( authors.order_by("name"), [ "John Smith", ], lambda a: a.name, )
da23f56c397a0642c4b6ea1741ef09d2121ad0ce4e9a835cc874e15940c9114b
from django.db.models import Value as V from django.db.models.functions import Lower, StrIndex, Substr, Upper from django.test import TestCase from ..models import Author class SubstrTests(TestCase): def test_basic(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.annotate(name_part=Substr("name", 5, 3)) self.assertQuerysetEqual( authors.order_by("name"), [" Sm", "da"], lambda a: a.name_part ) authors = Author.objects.annotate(name_part=Substr("name", 2)) self.assertQuerysetEqual( authors.order_by("name"), ["ohn Smith", "honda"], lambda a: a.name_part ) # If alias is null, set to first 5 lower characters of the name. Author.objects.filter(alias__isnull=True).update( alias=Lower(Substr("name", 1, 5)), ) self.assertQuerysetEqual( authors.order_by("name"), ["smithj", "rhond"], lambda a: a.alias ) def test_start(self): Author.objects.create(name="John Smith", alias="smithj") a = Author.objects.annotate( name_part_1=Substr("name", 1), name_part_2=Substr("name", 2), ).get(alias="smithj") self.assertEqual(a.name_part_1[1:], a.name_part_2) def test_pos_gt_zero(self): with self.assertRaisesMessage(ValueError, "'pos' must be greater than 0"): Author.objects.annotate(raises=Substr("name", 0)) def test_expressions(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") substr = Substr(Upper("name"), StrIndex("name", V("h")), 5) authors = Author.objects.annotate(name_part=substr) self.assertQuerysetEqual( authors.order_by("name"), ["HN SM", "HONDA"], lambda a: a.name_part )
cd1aa1d700f5e21f3015b52f1dd5ff1c1b2c2e3dcfb01aeb7ebc19964e9b9c67
from django.db.models import CharField from django.db.models.functions import LTrim, RTrim, Trim from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class TrimTests(TestCase): def test_trim(self): Author.objects.create(name=" John ", alias="j") Author.objects.create(name="Rhonda", alias="r") authors = Author.objects.annotate( ltrim=LTrim("name"), rtrim=RTrim("name"), trim=Trim("name"), ) self.assertQuerysetEqual( authors.order_by("alias"), [ ("John ", " John", "John"), ("Rhonda", "Rhonda", "Rhonda"), ], lambda a: (a.ltrim, a.rtrim, a.trim), ) def test_trim_transform(self): Author.objects.create(name=" John ") Author.objects.create(name="Rhonda") tests = ( (LTrim, "John "), (RTrim, " John"), (Trim, "John"), ) for transform, trimmed_name in tests: with self.subTest(transform=transform): with register_lookup(CharField, transform): authors = Author.objects.filter( **{"name__%s" % transform.lookup_name: trimmed_name} ) self.assertQuerysetEqual(authors, [" John "], lambda a: a.name)
c8c4d16baf8e9e9cb82a3a83aa44d91d4770a19e8a96152f3d69496cae5512dd
from django.db import connection from django.db.models import CharField from django.db.models.functions import MD5 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class MD5Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ] ) def test_basic(self): authors = ( Author.objects.annotate( md5_alias=MD5("alias"), ) .values_list("md5_alias", flat=True) .order_by("pk") ) self.assertSequenceEqual( authors, [ "6117323d2cabbc17d44c2b44587f682c", "ca6d48f6772000141e66591aee49d56c", "bf2c13bc1154e3d2e7df848cbc8be73d", "d41d8cd98f00b204e9800998ecf8427e", "d41d8cd98f00b204e9800998ecf8427e" if connection.features.interprets_empty_strings_as_nulls else None, ], ) def test_transform(self): with register_lookup(CharField, MD5): authors = Author.objects.filter( alias__md5="6117323d2cabbc17d44c2b44587f682c", ).values_list("alias", flat=True) self.assertSequenceEqual(authors, ["John Smith"])
f08e0c93687462c11b1a785450fc16bf6523cf070d53e9c3c15b299b92573a86
from django.db import connection from django.db.models import Value from django.db.models.functions import Length, LPad, RPad from django.test import TestCase from ..models import Author class PadTests(TestCase): def test_pad(self): Author.objects.create(name="John", alias="j") none_value = ( "" if connection.features.interprets_empty_strings_as_nulls else None ) tests = ( (LPad("name", 7, Value("xy")), "xyxJohn"), (RPad("name", 7, Value("xy")), "Johnxyx"), (LPad("name", 6, Value("x")), "xxJohn"), (RPad("name", 6, Value("x")), "Johnxx"), # The default pad string is a space. (LPad("name", 6), " John"), (RPad("name", 6), "John "), # If string is longer than length it is truncated. (LPad("name", 2), "Jo"), (RPad("name", 2), "Jo"), (LPad("name", 0), ""), (RPad("name", 0), ""), (LPad("name", None), none_value), (RPad("name", None), none_value), (LPad(Value(None), 1), none_value), (RPad(Value(None), 1), none_value), (LPad("goes_by", 1), none_value), (RPad("goes_by", 1), none_value), ) for function, padded_name in tests: with self.subTest(function=function): authors = Author.objects.annotate(padded_name=function) self.assertQuerysetEqual( authors, [padded_name], lambda a: a.padded_name, ordered=False ) def test_pad_negative_length(self): for function in (LPad, RPad): with self.subTest(function=function): with self.assertRaisesMessage( ValueError, "'length' must be greater or equal to 0." ): function("name", -1) def test_combined_with_length(self): Author.objects.create(name="Rhonda", alias="john_smith") Author.objects.create(name="♥♣♠", alias="bytes") authors = Author.objects.annotate(filled=LPad("name", Length("alias"))) self.assertQuerysetEqual( authors.order_by("alias"), [" ♥♣♠", " Rhonda"], lambda a: a.filled, )
e665ebf244eb82408732fd8f2eb671fff2dda2058b656eaa601911f3f2804872
from django.db.models.functions import Lag, Lead, NthValue, Ntile from django.test import SimpleTestCase class ValidationTests(SimpleTestCase): def test_nth_negative_nth_value(self): msg = "NthValue requires a positive integer as for nth" with self.assertRaisesMessage(ValueError, msg): NthValue(expression="salary", nth=-1) def test_nth_null_expression(self): msg = "NthValue requires a non-null source expression" with self.assertRaisesMessage(ValueError, msg): NthValue(expression=None) def test_lag_negative_offset(self): msg = "Lag requires a positive integer for the offset" with self.assertRaisesMessage(ValueError, msg): Lag(expression="salary", offset=-1) def test_lead_negative_offset(self): msg = "Lead requires a positive integer for the offset" with self.assertRaisesMessage(ValueError, msg): Lead(expression="salary", offset=-1) def test_null_source_lead(self): msg = "Lead requires a non-null source expression" with self.assertRaisesMessage(ValueError, msg): Lead(expression=None) def test_null_source_lag(self): msg = "Lag requires a non-null source expression" with self.assertRaisesMessage(ValueError, msg): Lag(expression=None) def test_negative_num_buckets_ntile(self): msg = "num_buckets must be greater than 0" with self.assertRaisesMessage(ValueError, msg): Ntile(num_buckets=-1)
0be564951d2e1dd927da855988d04c56432ba92d9dad46be84c3e4ac559befcd
from datetime import datetime, timedelta from django.db.models.functions import Now from django.test import TestCase from django.utils import timezone from ..models import Article lorem_ipsum = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" class NowTests(TestCase): def test_basic(self): a1 = Article.objects.create( title="How to Django", text=lorem_ipsum, written=timezone.now(), ) a2 = Article.objects.create( title="How to Time Travel", text=lorem_ipsum, written=timezone.now(), ) num_updated = Article.objects.filter(id=a1.id, published=None).update( published=Now() ) self.assertEqual(num_updated, 1) num_updated = Article.objects.filter(id=a1.id, published=None).update( published=Now() ) self.assertEqual(num_updated, 0) a1.refresh_from_db() self.assertIsInstance(a1.published, datetime) a2.published = Now() + timedelta(days=2) a2.save() a2.refresh_from_db() self.assertIsInstance(a2.published, datetime) self.assertQuerysetEqual( Article.objects.filter(published__lte=Now()), ["How to Django"], lambda a: a.title, ) self.assertQuerysetEqual( Article.objects.filter(published__gt=Now()), ["How to Time Travel"], lambda a: a.title, )
90c0eccbb736fadd2fde3bd85c5073de18a447bb1e00dabf070ad7c1570db9fb
import unittest from datetime import datetime, timedelta from datetime import timezone as datetime_timezone try: import zoneinfo except ImportError: from backports import zoneinfo try: import pytz except ImportError: pytz = None from django.conf import settings from django.db.models import ( DateField, DateTimeField, F, IntegerField, Max, OuterRef, Subquery, TimeField, ) from django.db.models.functions import ( Extract, ExtractDay, ExtractHour, ExtractIsoWeekDay, ExtractIsoYear, ExtractMinute, ExtractMonth, ExtractQuarter, ExtractSecond, ExtractWeek, ExtractWeekDay, ExtractYear, Trunc, TruncDate, TruncDay, TruncHour, TruncMinute, TruncMonth, TruncQuarter, TruncSecond, TruncTime, TruncWeek, TruncYear, ) from django.test import ( TestCase, ignore_warnings, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from django.utils import timezone from django.utils.deprecation import RemovedInDjango50Warning from ..models import Author, DTModel, Fan HAS_PYTZ = pytz is not None if not HAS_PYTZ: needs_pytz = unittest.skip("Test requires pytz") else: def needs_pytz(f): return f ZONE_CONSTRUCTORS = (zoneinfo.ZoneInfo,) if HAS_PYTZ: ZONE_CONSTRUCTORS += (pytz.timezone,) def truncate_to(value, kind, tzinfo=None): # Convert to target timezone before truncation if tzinfo is not None: value = value.astimezone(tzinfo) def truncate(value, kind): if kind == "second": return value.replace(microsecond=0) if kind == "minute": return value.replace(second=0, microsecond=0) if kind == "hour": return value.replace(minute=0, second=0, microsecond=0) if kind == "day": if isinstance(value, datetime): return value.replace(hour=0, minute=0, second=0, microsecond=0) return value if kind == "week": if isinstance(value, datetime): return (value - timedelta(days=value.weekday())).replace( hour=0, minute=0, second=0, microsecond=0 ) return value - timedelta(days=value.weekday()) if kind == "month": if isinstance(value, datetime): return value.replace(day=1, hour=0, minute=0, second=0, microsecond=0) return value.replace(day=1) if kind == "quarter": month_in_quarter = value.month - (value.month - 1) % 3 if isinstance(value, datetime): return value.replace( month=month_in_quarter, day=1, hour=0, minute=0, second=0, microsecond=0, ) return value.replace(month=month_in_quarter, day=1) # otherwise, truncate to year if isinstance(value, datetime): return value.replace( month=1, day=1, hour=0, minute=0, second=0, microsecond=0 ) return value.replace(month=1, day=1) value = truncate(value, kind) if tzinfo is not None: # If there was a daylight saving transition, then reset the timezone. value = timezone.make_aware(value.replace(tzinfo=None), tzinfo) return value @override_settings(USE_TZ=False) class DateFunctionTests(TestCase): def create_model(self, start_datetime, end_datetime): return DTModel.objects.create( name=start_datetime.isoformat() if start_datetime else "None", start_datetime=start_datetime, end_datetime=end_datetime, start_date=start_datetime.date() if start_datetime else None, end_date=end_datetime.date() if end_datetime else None, start_time=start_datetime.time() if start_datetime else None, end_time=end_datetime.time() if end_datetime else None, duration=(end_datetime - start_datetime) if start_datetime and end_datetime else None, ) def test_extract_year_exact_lookup(self): """ Extract year uses a BETWEEN filter to compare the year to allow indexes to be used. """ start_datetime = datetime(2015, 6, 15, 14, 10) end_datetime = datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ("year", "iso_year"): with self.subTest(lookup): qs = DTModel.objects.filter( **{"start_datetime__%s__exact" % lookup: 2015} ) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(" between "), 1) self.assertEqual(query_string.count("extract"), 0) # exact is implied and should be the same qs = DTModel.objects.filter(**{"start_datetime__%s" % lookup: 2015}) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(" between "), 1) self.assertEqual(query_string.count("extract"), 0) # date and datetime fields should behave the same qs = DTModel.objects.filter(**{"start_date__%s" % lookup: 2015}) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(" between "), 1) self.assertEqual(query_string.count("extract"), 0) # an expression rhs cannot use the between optimization. qs = DTModel.objects.annotate( start_year=ExtractYear("start_datetime"), ).filter(end_datetime__year=F("start_year") + 1) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(" between "), 0) self.assertEqual(query_string.count("extract"), 3) def test_extract_year_greaterthan_lookup(self): start_datetime = datetime(2015, 6, 15, 14, 10) end_datetime = datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ("year", "iso_year"): with self.subTest(lookup): qs = DTModel.objects.filter(**{"start_datetime__%s__gt" % lookup: 2015}) self.assertEqual(qs.count(), 1) self.assertEqual(str(qs.query).lower().count("extract"), 0) qs = DTModel.objects.filter( **{"start_datetime__%s__gte" % lookup: 2015} ) self.assertEqual(qs.count(), 2) self.assertEqual(str(qs.query).lower().count("extract"), 0) qs = DTModel.objects.annotate( start_year=ExtractYear("start_datetime"), ).filter(**{"end_datetime__%s__gte" % lookup: F("start_year")}) self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count("extract"), 2) def test_extract_year_lessthan_lookup(self): start_datetime = datetime(2015, 6, 15, 14, 10) end_datetime = datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ("year", "iso_year"): with self.subTest(lookup): qs = DTModel.objects.filter(**{"start_datetime__%s__lt" % lookup: 2016}) self.assertEqual(qs.count(), 1) self.assertEqual(str(qs.query).count("extract"), 0) qs = DTModel.objects.filter( **{"start_datetime__%s__lte" % lookup: 2016} ) self.assertEqual(qs.count(), 2) self.assertEqual(str(qs.query).count("extract"), 0) qs = DTModel.objects.annotate( end_year=ExtractYear("end_datetime"), ).filter(**{"start_datetime__%s__lte" % lookup: F("end_year")}) self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count("extract"), 2) def test_extract_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) with self.assertRaisesMessage(ValueError, "lookup_name must be provided"): Extract("start_datetime") msg = ( "Extract input expression must be DateField, DateTimeField, TimeField, or " "DurationField." ) with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(extracted=Extract("name", "hour"))) with self.assertRaisesMessage( ValueError, "Cannot extract time component 'second' from DateField 'start_date'.", ): list(DTModel.objects.annotate(extracted=Extract("start_date", "second"))) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "year") ).order_by("start_datetime"), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "quarter") ).order_by("start_datetime"), [(start_datetime, 2), (end_datetime, 2)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "month") ).order_by("start_datetime"), [ (start_datetime, start_datetime.month), (end_datetime, end_datetime.month), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "day") ).order_by("start_datetime"), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "week") ).order_by("start_datetime"), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "week_day") ).order_by("start_datetime"), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "iso_week_day"), ).order_by("start_datetime"), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "hour") ).order_by("start_datetime"), [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "minute") ).order_by("start_datetime"), [ (start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "second") ).order_by("start_datetime"), [ (start_datetime, start_datetime.second), (end_datetime, end_datetime.second), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__year=Extract("start_datetime", "year") ).count(), 2, ) self.assertEqual( DTModel.objects.filter( start_datetime__hour=Extract("start_datetime", "hour") ).count(), 2, ) self.assertEqual( DTModel.objects.filter( start_date__month=Extract("start_date", "month") ).count(), 2, ) self.assertEqual( DTModel.objects.filter( start_time__hour=Extract("start_time", "hour") ).count(), 2, ) def test_extract_none(self): self.create_model(None, None) for t in ( Extract("start_datetime", "year"), Extract("start_date", "year"), Extract("start_time", "hour"), ): with self.subTest(t): self.assertIsNone( DTModel.objects.annotate(extracted=t).first().extracted ) def test_extract_outerref_validation(self): inner_qs = DTModel.objects.filter(name=ExtractMonth(OuterRef("name"))) msg = ( "Extract input expression must be DateField, DateTimeField, " "TimeField, or DurationField." ) with self.assertRaisesMessage(ValueError, msg): DTModel.objects.annotate(related_name=Subquery(inner_qs.values("name")[:1])) @skipUnlessDBFeature("has_native_duration_field") def test_extract_duration(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract("duration", "second")).order_by( "start_datetime" ), [ (start_datetime, (end_datetime - start_datetime).seconds % 60), (end_datetime, (start_datetime - end_datetime).seconds % 60), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.annotate( duration_days=Extract("duration", "day"), ) .filter(duration_days__gt=200) .count(), 1, ) @skipIfDBFeature("has_native_duration_field") def test_extract_duration_without_native_duration_field(self): msg = "Extract requires native DurationField database support." with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(extracted=Extract("duration", "second"))) def test_extract_duration_unsupported_lookups(self): msg = "Cannot extract component '%s' from DurationField 'duration'." for lookup in ( "year", "iso_year", "month", "week", "week_day", "iso_week_day", "quarter", ): with self.subTest(lookup): with self.assertRaisesMessage(ValueError, msg % lookup): DTModel.objects.annotate(extracted=Extract("duration", lookup)) def test_extract_year_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractYear("start_datetime")).order_by( "start_datetime" ), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractYear("start_date")).order_by( "start_datetime" ), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__year=ExtractYear("start_datetime") ).count(), 2, ) def test_extract_iso_year_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=ExtractIsoYear("start_datetime") ).order_by("start_datetime"), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractIsoYear("start_date")).order_by( "start_datetime" ), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) # Both dates are from the same week year. self.assertEqual( DTModel.objects.filter( start_datetime__iso_year=ExtractIsoYear("start_datetime") ).count(), 2, ) def test_extract_iso_year_func_boundaries(self): end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime) week_52_day_2014 = datetime(2014, 12, 27, 13, 0) # Sunday week_1_day_2014_2015 = datetime(2014, 12, 31, 13, 0) # Wednesday week_53_day_2015 = datetime(2015, 12, 31, 13, 0) # Thursday if settings.USE_TZ: week_1_day_2014_2015 = timezone.make_aware(week_1_day_2014_2015) week_52_day_2014 = timezone.make_aware(week_52_day_2014) week_53_day_2015 = timezone.make_aware(week_53_day_2015) days = [week_52_day_2014, week_1_day_2014_2015, week_53_day_2015] obj_1_iso_2014 = self.create_model(week_52_day_2014, end_datetime) obj_1_iso_2015 = self.create_model(week_1_day_2014_2015, end_datetime) obj_2_iso_2015 = self.create_model(week_53_day_2015, end_datetime) qs = ( DTModel.objects.filter(start_datetime__in=days) .annotate( extracted=ExtractIsoYear("start_datetime"), ) .order_by("start_datetime") ) self.assertQuerysetEqual( qs, [ (week_52_day_2014, 2014), (week_1_day_2014_2015, 2015), (week_53_day_2015, 2015), ], lambda m: (m.start_datetime, m.extracted), ) qs = DTModel.objects.filter( start_datetime__iso_year=2015, ).order_by("start_datetime") self.assertSequenceEqual(qs, [obj_1_iso_2015, obj_2_iso_2015]) qs = DTModel.objects.filter( start_datetime__iso_year__gt=2014, ).order_by("start_datetime") self.assertSequenceEqual(qs, [obj_1_iso_2015, obj_2_iso_2015]) qs = DTModel.objects.filter( start_datetime__iso_year__lte=2014, ).order_by("start_datetime") self.assertSequenceEqual(qs, [obj_1_iso_2014]) def test_extract_month_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractMonth("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.month), (end_datetime, end_datetime.month), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractMonth("start_date")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.month), (end_datetime, end_datetime.month), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__month=ExtractMonth("start_datetime") ).count(), 2, ) def test_extract_day_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractDay("start_datetime")).order_by( "start_datetime" ), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractDay("start_date")).order_by( "start_datetime" ), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__day=ExtractDay("start_datetime") ).count(), 2, ) def test_extract_week_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractWeek("start_datetime")).order_by( "start_datetime" ), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractWeek("start_date")).order_by( "start_datetime" ), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted), ) # both dates are from the same week. self.assertEqual( DTModel.objects.filter( start_datetime__week=ExtractWeek("start_datetime") ).count(), 2, ) def test_extract_quarter_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 8, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=ExtractQuarter("start_datetime") ).order_by("start_datetime"), [(start_datetime, 2), (end_datetime, 3)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractQuarter("start_date")).order_by( "start_datetime" ), [(start_datetime, 2), (end_datetime, 3)], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__quarter=ExtractQuarter("start_datetime") ).count(), 2, ) def test_extract_quarter_func_boundaries(self): end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime) last_quarter_2014 = datetime(2014, 12, 31, 13, 0) first_quarter_2015 = datetime(2015, 1, 1, 13, 0) if settings.USE_TZ: last_quarter_2014 = timezone.make_aware(last_quarter_2014) first_quarter_2015 = timezone.make_aware(first_quarter_2015) dates = [last_quarter_2014, first_quarter_2015] self.create_model(last_quarter_2014, end_datetime) self.create_model(first_quarter_2015, end_datetime) qs = ( DTModel.objects.filter(start_datetime__in=dates) .annotate( extracted=ExtractQuarter("start_datetime"), ) .order_by("start_datetime") ) self.assertQuerysetEqual( qs, [ (last_quarter_2014, 4), (first_quarter_2015, 1), ], lambda m: (m.start_datetime, m.extracted), ) def test_extract_week_func_boundaries(self): end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime) week_52_day_2014 = datetime(2014, 12, 27, 13, 0) # Sunday week_1_day_2014_2015 = datetime(2014, 12, 31, 13, 0) # Wednesday week_53_day_2015 = datetime(2015, 12, 31, 13, 0) # Thursday if settings.USE_TZ: week_1_day_2014_2015 = timezone.make_aware(week_1_day_2014_2015) week_52_day_2014 = timezone.make_aware(week_52_day_2014) week_53_day_2015 = timezone.make_aware(week_53_day_2015) days = [week_52_day_2014, week_1_day_2014_2015, week_53_day_2015] self.create_model(week_53_day_2015, end_datetime) self.create_model(week_52_day_2014, end_datetime) self.create_model(week_1_day_2014_2015, end_datetime) qs = ( DTModel.objects.filter(start_datetime__in=days) .annotate( extracted=ExtractWeek("start_datetime"), ) .order_by("start_datetime") ) self.assertQuerysetEqual( qs, [ (week_52_day_2014, 52), (week_1_day_2014_2015, 1), (week_53_day_2015, 53), ], lambda m: (m.start_datetime, m.extracted), ) def test_extract_weekday_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=ExtractWeekDay("start_datetime") ).order_by("start_datetime"), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractWeekDay("start_date")).order_by( "start_datetime" ), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__week_day=ExtractWeekDay("start_datetime") ).count(), 2, ) def test_extract_iso_weekday_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=ExtractIsoWeekDay("start_datetime"), ).order_by("start_datetime"), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=ExtractIsoWeekDay("start_date"), ).order_by("start_datetime"), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__week_day=ExtractWeekDay("start_datetime"), ).count(), 2, ) def test_extract_hour_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractHour("start_datetime")).order_by( "start_datetime" ), [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractHour("start_time")).order_by( "start_datetime" ), [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__hour=ExtractHour("start_datetime") ).count(), 2, ) def test_extract_minute_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=ExtractMinute("start_datetime") ).order_by("start_datetime"), [ (start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractMinute("start_time")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__minute=ExtractMinute("start_datetime") ).count(), 2, ) def test_extract_second_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=ExtractSecond("start_datetime") ).order_by("start_datetime"), [ (start_datetime, start_datetime.second), (end_datetime, end_datetime.second), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractSecond("start_time")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.second), (end_datetime, end_datetime.second), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__second=ExtractSecond("start_datetime") ).count(), 2, ) def test_extract_second_func_no_fractional(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 30, 50, 783) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) obj = self.create_model(start_datetime, end_datetime) self.assertSequenceEqual( DTModel.objects.filter(start_datetime__second=F("end_datetime__second")), [obj], ) self.assertSequenceEqual( DTModel.objects.filter(start_time__second=F("end_time__second")), [obj], ) def test_trunc_func(self): start_datetime = datetime(999, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) def test_datetime_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc( "start_datetime", kind, output_field=DateTimeField() ) ).order_by("start_datetime"), [ (start_datetime, truncate_to(start_datetime, kind)), (end_datetime, truncate_to(end_datetime, kind)), ], lambda m: (m.start_datetime, m.truncated), ) def test_date_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc("start_date", kind, output_field=DateField()) ).order_by("start_datetime"), [ (start_datetime, truncate_to(start_datetime.date(), kind)), (end_datetime, truncate_to(end_datetime.date(), kind)), ], lambda m: (m.start_datetime, m.truncated), ) def test_time_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc("start_time", kind, output_field=TimeField()) ).order_by("start_datetime"), [ (start_datetime, truncate_to(start_datetime.time(), kind)), (end_datetime, truncate_to(end_datetime.time(), kind)), ], lambda m: (m.start_datetime, m.truncated), ) def test_datetime_to_time_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc("start_datetime", kind, output_field=TimeField()), ).order_by("start_datetime"), [ (start_datetime, truncate_to(start_datetime.time(), kind)), (end_datetime, truncate_to(end_datetime.time(), kind)), ], lambda m: (m.start_datetime, m.truncated), ) test_date_kind("year") test_date_kind("quarter") test_date_kind("month") test_date_kind("day") test_time_kind("hour") test_time_kind("minute") test_time_kind("second") test_datetime_kind("year") test_datetime_kind("quarter") test_datetime_kind("month") test_datetime_kind("day") test_datetime_kind("hour") test_datetime_kind("minute") test_datetime_kind("second") test_datetime_to_time_kind("hour") test_datetime_to_time_kind("minute") test_datetime_to_time_kind("second") qs = DTModel.objects.filter( start_datetime__date=Trunc( "start_datetime", "day", output_field=DateField() ) ) self.assertEqual(qs.count(), 2) def _test_trunc_week(self, start_datetime, end_datetime): if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc("start_datetime", "week", output_field=DateTimeField()) ).order_by("start_datetime"), [ (start_datetime, truncate_to(start_datetime, "week")), (end_datetime, truncate_to(end_datetime, "week")), ], lambda m: (m.start_datetime, m.truncated), ) self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc("start_date", "week", output_field=DateField()) ).order_by("start_datetime"), [ (start_datetime, truncate_to(start_datetime.date(), "week")), (end_datetime, truncate_to(end_datetime.date(), "week")), ], lambda m: (m.start_datetime, m.truncated), ) def test_trunc_week(self): self._test_trunc_week( start_datetime=datetime(2015, 6, 15, 14, 30, 50, 321), end_datetime=datetime(2016, 6, 15, 14, 10, 50, 123), ) def test_trunc_week_before_1000(self): self._test_trunc_week( start_datetime=datetime(999, 6, 15, 14, 30, 50, 321), end_datetime=datetime(2016, 6, 15, 14, 10, 50, 123), ) def test_trunc_invalid_arguments(self): msg = "output_field must be either DateField, TimeField, or DateTimeField" with self.assertRaisesMessage(ValueError, msg): list( DTModel.objects.annotate( truncated=Trunc( "start_datetime", "year", output_field=IntegerField() ), ) ) msg = "'name' isn't a DateField, TimeField, or DateTimeField." with self.assertRaisesMessage(TypeError, msg): list( DTModel.objects.annotate( truncated=Trunc("name", "year", output_field=DateTimeField()), ) ) msg = "Cannot truncate DateField 'start_date' to DateTimeField" with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(truncated=Trunc("start_date", "second"))) with self.assertRaisesMessage(ValueError, msg): list( DTModel.objects.annotate( truncated=Trunc( "start_date", "month", output_field=DateTimeField() ), ) ) msg = "Cannot truncate TimeField 'start_time' to DateTimeField" with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(truncated=Trunc("start_time", "month"))) with self.assertRaisesMessage(ValueError, msg): list( DTModel.objects.annotate( truncated=Trunc( "start_time", "second", output_field=DateTimeField() ), ) ) def test_trunc_none(self): self.create_model(None, None) for t in ( Trunc("start_datetime", "year"), Trunc("start_date", "year"), Trunc("start_time", "hour"), ): with self.subTest(t): self.assertIsNone( DTModel.objects.annotate(truncated=t).first().truncated ) def test_trunc_year_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "year") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncYear("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "year")), (end_datetime, truncate_to(end_datetime, "year")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncYear("start_date")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime.date(), "year")), (end_datetime, truncate_to(end_datetime.date(), "year")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter(start_datetime=TruncYear("start_datetime")).count(), 1, ) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncYear("start_time"))) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncYear("start_time", output_field=TimeField()) ) ) def test_trunc_quarter_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 10, 15, 14, 10, 50, 123), "quarter") last_quarter_2015 = truncate_to( datetime(2015, 12, 31, 14, 10, 50, 123), "quarter" ) first_quarter_2016 = truncate_to( datetime(2016, 1, 1, 14, 10, 50, 123), "quarter" ) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) last_quarter_2015 = timezone.make_aware(last_quarter_2015) first_quarter_2016 = timezone.make_aware(first_quarter_2016) self.create_model(start_datetime=start_datetime, end_datetime=end_datetime) self.create_model(start_datetime=end_datetime, end_datetime=start_datetime) self.create_model(start_datetime=last_quarter_2015, end_datetime=end_datetime) self.create_model(start_datetime=first_quarter_2016, end_datetime=end_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncQuarter("start_date")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime.date(), "quarter")), (last_quarter_2015, truncate_to(last_quarter_2015.date(), "quarter")), (first_quarter_2016, truncate_to(first_quarter_2016.date(), "quarter")), (end_datetime, truncate_to(end_datetime.date(), "quarter")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncQuarter("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "quarter")), (last_quarter_2015, truncate_to(last_quarter_2015, "quarter")), (first_quarter_2016, truncate_to(first_quarter_2016, "quarter")), (end_datetime, truncate_to(end_datetime, "quarter")), ], lambda m: (m.start_datetime, m.extracted), ) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncQuarter("start_time"))) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncQuarter("start_time", output_field=TimeField()) ) ) def test_trunc_month_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "month") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncMonth("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "month")), (end_datetime, truncate_to(end_datetime, "month")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncMonth("start_date")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime.date(), "month")), (end_datetime, truncate_to(end_datetime.date(), "month")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter(start_datetime=TruncMonth("start_datetime")).count(), 1, ) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncMonth("start_time"))) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncMonth("start_time", output_field=TimeField()) ) ) def test_trunc_week_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "week") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncWeek("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "week")), (end_datetime, truncate_to(end_datetime, "week")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter(start_datetime=TruncWeek("start_datetime")).count(), 1, ) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncWeek("start_time"))) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncWeek("start_time", output_field=TimeField()) ) ) def test_trunc_date_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncDate("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.date()), (end_datetime, end_datetime.date()), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__date=TruncDate("start_datetime") ).count(), 2, ) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateField" ): list(DTModel.objects.annotate(truncated=TruncDate("start_time"))) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateField" ): list( DTModel.objects.annotate( truncated=TruncDate("start_time", output_field=TimeField()) ) ) def test_trunc_date_none(self): self.create_model(None, None) self.assertIsNone( DTModel.objects.annotate(truncated=TruncDate("start_datetime")) .first() .truncated ) def test_trunc_time_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncTime("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.time()), (end_datetime, end_datetime.time()), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__time=TruncTime("start_datetime") ).count(), 2, ) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to TimeField" ): list(DTModel.objects.annotate(truncated=TruncTime("start_date"))) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to TimeField" ): list( DTModel.objects.annotate( truncated=TruncTime("start_date", output_field=DateField()) ) ) def test_trunc_time_none(self): self.create_model(None, None) self.assertIsNone( DTModel.objects.annotate(truncated=TruncTime("start_datetime")) .first() .truncated ) def test_trunc_time_comparison(self): start_datetime = datetime(2015, 6, 15, 14, 30, 26) # 0 microseconds. end_datetime = datetime(2015, 6, 15, 14, 30, 26, 321) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.assertIs( DTModel.objects.filter( start_datetime__time=start_datetime.time(), end_datetime__time=end_datetime.time(), ).exists(), True, ) self.assertIs( DTModel.objects.annotate( extracted_start=TruncTime("start_datetime"), extracted_end=TruncTime("end_datetime"), ) .filter( extracted_start=start_datetime.time(), extracted_end=end_datetime.time(), ) .exists(), True, ) def test_trunc_day_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "day") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncDay("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "day")), (end_datetime, truncate_to(end_datetime, "day")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter(start_datetime=TruncDay("start_datetime")).count(), 1 ) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncDay("start_time"))) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncDay("start_time", output_field=TimeField()) ) ) def test_trunc_hour_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "hour") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncHour("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "hour")), (end_datetime, truncate_to(end_datetime, "hour")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncHour("start_time")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime.time(), "hour")), (end_datetime, truncate_to(end_datetime.time(), "hour")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter(start_datetime=TruncHour("start_datetime")).count(), 1, ) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncHour("start_date"))) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncHour("start_date", output_field=DateField()) ) ) def test_trunc_minute_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "minute") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncMinute("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "minute")), (end_datetime, truncate_to(end_datetime, "minute")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncMinute("start_time")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime.time(), "minute")), (end_datetime, truncate_to(end_datetime.time(), "minute")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime=TruncMinute("start_datetime") ).count(), 1, ) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncMinute("start_date"))) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncMinute("start_date", output_field=DateField()) ) ) def test_trunc_second_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "second") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncSecond("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "second")), (end_datetime, truncate_to(end_datetime, "second")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncSecond("start_time")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime.time(), "second")), (end_datetime, truncate_to(end_datetime.time(), "second")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime=TruncSecond("start_datetime") ).count(), 1, ) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncSecond("start_date"))) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncSecond("start_date", output_field=DateField()) ) ) def test_trunc_subquery_with_parameters(self): author_1 = Author.objects.create(name="J. R. R. Tolkien") author_2 = Author.objects.create(name="G. R. R. Martin") fan_since_1 = datetime(2016, 2, 3, 15, 0, 0) fan_since_2 = datetime(2015, 2, 3, 15, 0, 0) fan_since_3 = datetime(2017, 2, 3, 15, 0, 0) if settings.USE_TZ: fan_since_1 = timezone.make_aware(fan_since_1) fan_since_2 = timezone.make_aware(fan_since_2) fan_since_3 = timezone.make_aware(fan_since_3) Fan.objects.create(author=author_1, name="Tom", fan_since=fan_since_1) Fan.objects.create(author=author_1, name="Emma", fan_since=fan_since_2) Fan.objects.create(author=author_2, name="Isabella", fan_since=fan_since_3) inner = ( Fan.objects.filter( author=OuterRef("pk"), name__in=("Emma", "Isabella", "Tom") ) .values("author") .annotate(newest_fan=Max("fan_since")) .values("newest_fan") ) outer = Author.objects.annotate( newest_fan_year=TruncYear(Subquery(inner, output_field=DateTimeField())) ) tz = timezone.utc if settings.USE_TZ else None self.assertSequenceEqual( outer.order_by("name").values("name", "newest_fan_year"), [ { "name": "G. R. R. Martin", "newest_fan_year": datetime(2017, 1, 1, 0, 0, tzinfo=tz), }, { "name": "J. R. R. Tolkien", "newest_fan_year": datetime(2016, 1, 1, 0, 0, tzinfo=tz), }, ], ) def test_extract_outerref(self): datetime_1 = datetime(2000, 1, 1) datetime_2 = datetime(2001, 3, 5) datetime_3 = datetime(2002, 1, 3) if settings.USE_TZ: datetime_1 = timezone.make_aware(datetime_1) datetime_2 = timezone.make_aware(datetime_2) datetime_3 = timezone.make_aware(datetime_3) obj_1 = self.create_model(datetime_1, datetime_3) obj_2 = self.create_model(datetime_2, datetime_1) obj_3 = self.create_model(datetime_3, datetime_2) inner_qs = DTModel.objects.filter( start_datetime__year=2000, start_datetime__month=ExtractMonth(OuterRef("end_datetime")), ) qs = DTModel.objects.annotate( related_pk=Subquery(inner_qs.values("pk")[:1]), ) self.assertSequenceEqual( qs.order_by("name").values("pk", "related_pk"), [ {"pk": obj_1.pk, "related_pk": obj_1.pk}, {"pk": obj_2.pk, "related_pk": obj_1.pk}, {"pk": obj_3.pk, "related_pk": None}, ], ) @override_settings(USE_TZ=True, TIME_ZONE="UTC") class DateFunctionWithTimeZoneTests(DateFunctionTests): def get_timezones(self, key): for constructor in ZONE_CONSTRUCTORS: yield constructor(key) def test_extract_func_with_timezone(self): start_datetime = datetime(2015, 6, 15, 23, 30, 1, 321) end_datetime = datetime(2015, 6, 16, 13, 11, 27, 123) start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) delta_tzinfo_pos = datetime_timezone(timedelta(hours=5)) delta_tzinfo_neg = datetime_timezone(timedelta(hours=-5, minutes=17)) for melb in self.get_timezones("Australia/Melbourne"): with self.subTest(repr(melb)): qs = DTModel.objects.annotate( day=Extract("start_datetime", "day"), day_melb=Extract("start_datetime", "day", tzinfo=melb), week=Extract("start_datetime", "week", tzinfo=melb), isoyear=ExtractIsoYear("start_datetime", tzinfo=melb), weekday=ExtractWeekDay("start_datetime"), weekday_melb=ExtractWeekDay("start_datetime", tzinfo=melb), isoweekday=ExtractIsoWeekDay("start_datetime"), isoweekday_melb=ExtractIsoWeekDay("start_datetime", tzinfo=melb), quarter=ExtractQuarter("start_datetime", tzinfo=melb), hour=ExtractHour("start_datetime"), hour_melb=ExtractHour("start_datetime", tzinfo=melb), hour_with_delta_pos=ExtractHour( "start_datetime", tzinfo=delta_tzinfo_pos ), hour_with_delta_neg=ExtractHour( "start_datetime", tzinfo=delta_tzinfo_neg ), minute_with_delta_neg=ExtractMinute( "start_datetime", tzinfo=delta_tzinfo_neg ), ).order_by("start_datetime") utc_model = qs.get() self.assertEqual(utc_model.day, 15) self.assertEqual(utc_model.day_melb, 16) self.assertEqual(utc_model.week, 25) self.assertEqual(utc_model.isoyear, 2015) self.assertEqual(utc_model.weekday, 2) self.assertEqual(utc_model.weekday_melb, 3) self.assertEqual(utc_model.isoweekday, 1) self.assertEqual(utc_model.isoweekday_melb, 2) self.assertEqual(utc_model.quarter, 2) self.assertEqual(utc_model.hour, 23) self.assertEqual(utc_model.hour_melb, 9) self.assertEqual(utc_model.hour_with_delta_pos, 4) self.assertEqual(utc_model.hour_with_delta_neg, 18) self.assertEqual(utc_model.minute_with_delta_neg, 47) with timezone.override(melb): melb_model = qs.get() self.assertEqual(melb_model.day, 16) self.assertEqual(melb_model.day_melb, 16) self.assertEqual(melb_model.week, 25) self.assertEqual(melb_model.isoyear, 2015) self.assertEqual(melb_model.weekday, 3) self.assertEqual(melb_model.isoweekday, 2) self.assertEqual(melb_model.quarter, 2) self.assertEqual(melb_model.weekday_melb, 3) self.assertEqual(melb_model.isoweekday_melb, 2) self.assertEqual(melb_model.hour, 9) self.assertEqual(melb_model.hour_melb, 9) def test_extract_func_with_timezone_minus_no_offset(self): start_datetime = datetime(2015, 6, 15, 23, 30, 1, 321) end_datetime = datetime(2015, 6, 16, 13, 11, 27, 123) start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) for ust_nera in self.get_timezones("Asia/Ust-Nera"): with self.subTest(repr(ust_nera)): qs = DTModel.objects.annotate( hour=ExtractHour("start_datetime"), hour_tz=ExtractHour("start_datetime", tzinfo=ust_nera), ).order_by("start_datetime") utc_model = qs.get() self.assertEqual(utc_model.hour, 23) self.assertEqual(utc_model.hour_tz, 9) with timezone.override(ust_nera): ust_nera_model = qs.get() self.assertEqual(ust_nera_model.hour, 9) self.assertEqual(ust_nera_model.hour_tz, 9) def test_extract_func_explicit_timezone_priority(self): start_datetime = datetime(2015, 6, 15, 23, 30, 1, 321) end_datetime = datetime(2015, 6, 16, 13, 11, 27, 123) start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) for melb in self.get_timezones("Australia/Melbourne"): with self.subTest(repr(melb)): with timezone.override(melb): model = ( DTModel.objects.annotate( day_melb=Extract("start_datetime", "day"), day_utc=Extract( "start_datetime", "day", tzinfo=timezone.utc ), ) .order_by("start_datetime") .get() ) self.assertEqual(model.day_melb, 16) self.assertEqual(model.day_utc, 15) def test_extract_invalid_field_with_timezone(self): for melb in self.get_timezones("Australia/Melbourne"): with self.subTest(repr(melb)): msg = "tzinfo can only be used with DateTimeField." with self.assertRaisesMessage(ValueError, msg): DTModel.objects.annotate( day_melb=Extract("start_date", "day", tzinfo=melb), ).get() with self.assertRaisesMessage(ValueError, msg): DTModel.objects.annotate( hour_melb=Extract("start_time", "hour", tzinfo=melb), ).get() def test_trunc_timezone_applied_before_truncation(self): start_datetime = datetime(2016, 1, 1, 1, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) for melb, pacific in zip( self.get_timezones("Australia/Melbourne"), self.get_timezones("America/Los_Angeles"), ): with self.subTest((repr(melb), repr(pacific))): model = ( DTModel.objects.annotate( melb_year=TruncYear("start_datetime", tzinfo=melb), pacific_year=TruncYear("start_datetime", tzinfo=pacific), melb_date=TruncDate("start_datetime", tzinfo=melb), pacific_date=TruncDate("start_datetime", tzinfo=pacific), melb_time=TruncTime("start_datetime", tzinfo=melb), pacific_time=TruncTime("start_datetime", tzinfo=pacific), ) .order_by("start_datetime") .get() ) melb_start_datetime = start_datetime.astimezone(melb) pacific_start_datetime = start_datetime.astimezone(pacific) self.assertEqual(model.start_datetime, start_datetime) self.assertEqual( model.melb_year, truncate_to(start_datetime, "year", melb) ) self.assertEqual( model.pacific_year, truncate_to(start_datetime, "year", pacific) ) self.assertEqual(model.start_datetime.year, 2016) self.assertEqual(model.melb_year.year, 2016) self.assertEqual(model.pacific_year.year, 2015) self.assertEqual(model.melb_date, melb_start_datetime.date()) self.assertEqual(model.pacific_date, pacific_start_datetime.date()) self.assertEqual(model.melb_time, melb_start_datetime.time()) self.assertEqual(model.pacific_time, pacific_start_datetime.time()) @needs_pytz @ignore_warnings(category=RemovedInDjango50Warning) def test_trunc_ambiguous_and_invalid_times(self): sao = pytz.timezone("America/Sao_Paulo") utc = timezone.utc start_datetime = datetime(2016, 10, 16, 13, tzinfo=utc) end_datetime = datetime(2016, 2, 21, 1, tzinfo=utc) self.create_model(start_datetime, end_datetime) with timezone.override(sao): with self.assertRaisesMessage( pytz.NonExistentTimeError, "2016-10-16 00:00:00" ): model = DTModel.objects.annotate( truncated_start=TruncDay("start_datetime") ).get() with self.assertRaisesMessage( pytz.AmbiguousTimeError, "2016-02-20 23:00:00" ): model = DTModel.objects.annotate( truncated_end=TruncHour("end_datetime") ).get() model = DTModel.objects.annotate( truncated_start=TruncDay("start_datetime", is_dst=False), truncated_end=TruncHour("end_datetime", is_dst=False), ).get() self.assertEqual(model.truncated_start.dst(), timedelta(0)) self.assertEqual(model.truncated_end.dst(), timedelta(0)) model = DTModel.objects.annotate( truncated_start=TruncDay("start_datetime", is_dst=True), truncated_end=TruncHour("end_datetime", is_dst=True), ).get() self.assertEqual(model.truncated_start.dst(), timedelta(0, 3600)) self.assertEqual(model.truncated_end.dst(), timedelta(0, 3600)) def test_trunc_func_with_timezone(self): """ If the truncated datetime transitions to a different offset (daylight saving) then the returned value will have that new timezone/offset. """ start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for melb in self.get_timezones("Australia/Melbourne"): with self.subTest(repr(melb)): def test_datetime_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc( "start_datetime", kind, output_field=DateTimeField(), tzinfo=melb, ) ).order_by("start_datetime"), [ ( start_datetime, truncate_to( start_datetime.astimezone(melb), kind, melb ), ), ( end_datetime, truncate_to(end_datetime.astimezone(melb), kind, melb), ), ], lambda m: (m.start_datetime, m.truncated), ) def test_datetime_to_date_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc( "start_datetime", kind, output_field=DateField(), tzinfo=melb, ), ).order_by("start_datetime"), [ ( start_datetime, truncate_to( start_datetime.astimezone(melb).date(), kind ), ), ( end_datetime, truncate_to(end_datetime.astimezone(melb).date(), kind), ), ], lambda m: (m.start_datetime, m.truncated), ) def test_datetime_to_time_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc( "start_datetime", kind, output_field=TimeField(), tzinfo=melb, ) ).order_by("start_datetime"), [ ( start_datetime, truncate_to( start_datetime.astimezone(melb).time(), kind ), ), ( end_datetime, truncate_to(end_datetime.astimezone(melb).time(), kind), ), ], lambda m: (m.start_datetime, m.truncated), ) test_datetime_to_date_kind("year") test_datetime_to_date_kind("quarter") test_datetime_to_date_kind("month") test_datetime_to_date_kind("week") test_datetime_to_date_kind("day") test_datetime_to_time_kind("hour") test_datetime_to_time_kind("minute") test_datetime_to_time_kind("second") test_datetime_kind("year") test_datetime_kind("quarter") test_datetime_kind("month") test_datetime_kind("week") test_datetime_kind("day") test_datetime_kind("hour") test_datetime_kind("minute") test_datetime_kind("second") qs = DTModel.objects.filter( start_datetime__date=Trunc( "start_datetime", "day", output_field=DateField() ) ) self.assertEqual(qs.count(), 2) def test_trunc_invalid_field_with_timezone(self): for melb in self.get_timezones("Australia/Melbourne"): with self.subTest(repr(melb)): msg = "tzinfo can only be used with DateTimeField." with self.assertRaisesMessage(ValueError, msg): DTModel.objects.annotate( day_melb=Trunc("start_date", "day", tzinfo=melb), ).get() with self.assertRaisesMessage(ValueError, msg): DTModel.objects.annotate( hour_melb=Trunc("start_time", "hour", tzinfo=melb), ).get()
940156df24fd5c140a1b690eebba12703e593b1cf2521672c44d8e934911e520
from django.db import NotSupportedError from django.db.models import F, Value from django.db.models.functions import JSONObject, Lower from django.test import TestCase from django.test.testcases import skipIfDBFeature, skipUnlessDBFeature from django.utils import timezone from ..models import Article, Author @skipUnlessDBFeature("has_json_object_function") class JSONObjectTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name="Ivan Ivanov", alias="iivanov") def test_empty(self): obj = Author.objects.annotate(json_object=JSONObject()).first() self.assertEqual(obj.json_object, {}) def test_basic(self): obj = Author.objects.annotate(json_object=JSONObject(name="name")).first() self.assertEqual(obj.json_object, {"name": "Ivan Ivanov"}) def test_expressions(self): obj = Author.objects.annotate( json_object=JSONObject( name=Lower("name"), alias="alias", goes_by="goes_by", salary=Value(30000.15), age=F("age") * 2, ) ).first() self.assertEqual( obj.json_object, { "name": "ivan ivanov", "alias": "iivanov", "goes_by": None, "salary": 30000.15, "age": 60, }, ) def test_nested_json_object(self): obj = Author.objects.annotate( json_object=JSONObject( name="name", nested_json_object=JSONObject( alias="alias", age="age", ), ) ).first() self.assertEqual( obj.json_object, { "name": "Ivan Ivanov", "nested_json_object": { "alias": "iivanov", "age": 30, }, }, ) def test_nested_empty_json_object(self): obj = Author.objects.annotate( json_object=JSONObject( name="name", nested_json_object=JSONObject(), ) ).first() self.assertEqual( obj.json_object, { "name": "Ivan Ivanov", "nested_json_object": {}, }, ) def test_textfield(self): Article.objects.create( title="The Title", text="x" * 4000, written=timezone.now(), ) obj = Article.objects.annotate(json_object=JSONObject(text=F("text"))).first() self.assertEqual(obj.json_object, {"text": "x" * 4000}) @skipIfDBFeature("has_json_object_function") class JSONObjectNotSupportedTests(TestCase): def test_not_supported(self): msg = "JSONObject() is not supported on this database backend." with self.assertRaisesMessage(NotSupportedError, msg): Author.objects.annotate(json_object=JSONObject()).get()
add4154f4c536c53b4e328a5e3a890c258a09b864d8773c186e4cf63547dc924
from django.db.models import Subquery, TextField from django.db.models.functions import Coalesce, Lower from django.test import TestCase from django.utils import timezone from ..models import Article, Author lorem_ipsum = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" class CoalesceTests(TestCase): def test_basic(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.annotate(display_name=Coalesce("alias", "name")) self.assertQuerysetEqual( authors.order_by("name"), ["smithj", "Rhonda"], lambda a: a.display_name ) def test_gt_two_expressions(self): with self.assertRaisesMessage( ValueError, "Coalesce must take at least two expressions" ): Author.objects.annotate(display_name=Coalesce("alias")) def test_mixed_values(self): a1 = Author.objects.create(name="John Smith", alias="smithj") a2 = Author.objects.create(name="Rhonda") ar1 = Article.objects.create( title="How to Django", text=lorem_ipsum, written=timezone.now(), ) ar1.authors.add(a1) ar1.authors.add(a2) # mixed Text and Char article = Article.objects.annotate( headline=Coalesce("summary", "text", output_field=TextField()), ) self.assertQuerysetEqual( article.order_by("title"), [lorem_ipsum], lambda a: a.headline ) # mixed Text and Char wrapped article = Article.objects.annotate( headline=Coalesce( Lower("summary"), Lower("text"), output_field=TextField() ), ) self.assertQuerysetEqual( article.order_by("title"), [lorem_ipsum.lower()], lambda a: a.headline ) def test_ordering(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.order_by(Coalesce("alias", "name")) self.assertQuerysetEqual(authors, ["Rhonda", "John Smith"], lambda a: a.name) authors = Author.objects.order_by(Coalesce("alias", "name").asc()) self.assertQuerysetEqual(authors, ["Rhonda", "John Smith"], lambda a: a.name) authors = Author.objects.order_by(Coalesce("alias", "name").desc()) self.assertQuerysetEqual(authors, ["John Smith", "Rhonda"], lambda a: a.name) def test_empty_queryset(self): Author.objects.create(name="John Smith") tests = [ Author.objects.none(), Subquery(Author.objects.none()), ] for empty_query in tests: with self.subTest(empty_query.__class__.__name__): qs = Author.objects.annotate(annotation=Coalesce(empty_query, 42)) self.assertEqual(qs.first().annotation, 42)
2e6dcb34791f427f64d8918038a84ff8270c645d688982b2c169c32dec868cbe
import datetime import decimal import unittest from django.db import connection, models from django.db.models.functions import Cast from django.test import TestCase, ignore_warnings, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from ..models import Author, DTModel, Fan, FloatModel class CastTests(TestCase): @classmethod def setUpTestData(self): Author.objects.create(name="Bob", age=1, alias="1") def test_cast_from_value(self): numbers = Author.objects.annotate( cast_integer=Cast(models.Value("0"), models.IntegerField()) ) self.assertEqual(numbers.get().cast_integer, 0) def test_cast_from_field(self): numbers = Author.objects.annotate( cast_string=Cast("age", models.CharField(max_length=255)), ) self.assertEqual(numbers.get().cast_string, "1") def test_cast_to_char_field_without_max_length(self): numbers = Author.objects.annotate(cast_string=Cast("age", models.CharField())) self.assertEqual(numbers.get().cast_string, "1") # Silence "Truncated incorrect CHAR(1) value: 'Bob'". @ignore_warnings(module="django.db.backends.mysql.base") @skipUnlessDBFeature("supports_cast_with_precision") def test_cast_to_char_field_with_max_length(self): names = Author.objects.annotate( cast_string=Cast("name", models.CharField(max_length=1)) ) self.assertEqual(names.get().cast_string, "B") @skipUnlessDBFeature("supports_cast_with_precision") def test_cast_to_decimal_field(self): FloatModel.objects.create(f1=-1.934, f2=3.467) float_obj = FloatModel.objects.annotate( cast_f1_decimal=Cast( "f1", models.DecimalField(max_digits=8, decimal_places=2) ), cast_f2_decimal=Cast( "f2", models.DecimalField(max_digits=8, decimal_places=1) ), ).get() self.assertEqual(float_obj.cast_f1_decimal, decimal.Decimal("-1.93")) self.assertEqual(float_obj.cast_f2_decimal, decimal.Decimal("3.5")) author_obj = Author.objects.annotate( cast_alias_decimal=Cast( "alias", models.DecimalField(max_digits=8, decimal_places=2) ), ).get() self.assertEqual(author_obj.cast_alias_decimal, decimal.Decimal("1")) def test_cast_to_integer(self): for field_class in ( models.AutoField, models.BigAutoField, models.SmallAutoField, models.IntegerField, models.BigIntegerField, models.SmallIntegerField, models.PositiveBigIntegerField, models.PositiveIntegerField, models.PositiveSmallIntegerField, ): with self.subTest(field_class=field_class): numbers = Author.objects.annotate(cast_int=Cast("alias", field_class())) self.assertEqual(numbers.get().cast_int, 1) def test_cast_to_duration(self): duration = datetime.timedelta(days=1, seconds=2, microseconds=3) DTModel.objects.create(duration=duration) dtm = DTModel.objects.annotate( cast_duration=Cast("duration", models.DurationField()), cast_neg_duration=Cast(-duration, models.DurationField()), ).get() self.assertEqual(dtm.cast_duration, duration) self.assertEqual(dtm.cast_neg_duration, -duration) def test_cast_from_db_datetime_to_date(self): dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) DTModel.objects.create(start_datetime=dt_value) dtm = DTModel.objects.annotate( start_datetime_as_date=Cast("start_datetime", models.DateField()) ).first() self.assertEqual(dtm.start_datetime_as_date, datetime.date(2018, 9, 28)) def test_cast_from_db_datetime_to_time(self): dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) DTModel.objects.create(start_datetime=dt_value) dtm = DTModel.objects.annotate( start_datetime_as_time=Cast("start_datetime", models.TimeField()) ).first() rounded_ms = int( round(0.234567, connection.features.time_cast_precision) * 10**6 ) self.assertEqual( dtm.start_datetime_as_time, datetime.time(12, 42, 10, rounded_ms) ) def test_cast_from_db_date_to_datetime(self): dt_value = datetime.date(2018, 9, 28) DTModel.objects.create(start_date=dt_value) dtm = DTModel.objects.annotate( start_as_datetime=Cast("start_date", models.DateTimeField()) ).first() self.assertEqual( dtm.start_as_datetime, datetime.datetime(2018, 9, 28, 0, 0, 0, 0) ) def test_cast_from_db_datetime_to_date_group_by(self): author = Author.objects.create(name="John Smith", age=45) dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) Fan.objects.create(name="Margaret", age=50, author=author, fan_since=dt_value) fans = ( Fan.objects.values("author") .annotate( fan_for_day=Cast("fan_since", models.DateField()), fans=models.Count("*"), ) .values() ) self.assertEqual(fans[0]["fan_for_day"], datetime.date(2018, 9, 28)) self.assertEqual(fans[0]["fans"], 1) def test_cast_from_python_to_date(self): today = datetime.date.today() dates = Author.objects.annotate(cast_date=Cast(today, models.DateField())) self.assertEqual(dates.get().cast_date, today) def test_cast_from_python_to_datetime(self): now = datetime.datetime.now() dates = Author.objects.annotate(cast_datetime=Cast(now, models.DateTimeField())) time_precision = datetime.timedelta( microseconds=10 ** (6 - connection.features.time_cast_precision) ) self.assertAlmostEqual(dates.get().cast_datetime, now, delta=time_precision) def test_cast_from_python(self): numbers = Author.objects.annotate( cast_float=Cast(decimal.Decimal(0.125), models.FloatField()) ) cast_float = numbers.get().cast_float self.assertIsInstance(cast_float, float) self.assertEqual(cast_float, 0.125) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL test") def test_expression_wrapped_with_parentheses_on_postgresql(self): """ The SQL for the Cast expression is wrapped with parentheses in case it's a complex expression. """ with CaptureQueriesContext(connection) as captured_queries: list( Author.objects.annotate( cast_float=Cast(models.Avg("age"), models.FloatField()), ) ) self.assertIn( '(AVG("db_functions_author"."age"))::double precision', captured_queries[0]["sql"], ) def test_cast_to_text_field(self): self.assertEqual( Author.objects.values_list( Cast("age", models.TextField()), flat=True ).get(), "1", )
677a87fcabc88bd67192d87dcdfe1dbff554dd5963efb9a0581640465aa15276
from datetime import datetime, timedelta from decimal import Decimal from unittest import skipUnless from django.db import connection from django.db.models.expressions import RawSQL from django.db.models.functions import Coalesce, Greatest from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from django.utils import timezone from ..models import Article, Author, DecimalModel, Fan class GreatestTests(TestCase): def test_basic(self): now = timezone.now() before = now - timedelta(hours=1) Article.objects.create( title="Testing with Django", written=before, published=now ) articles = Article.objects.annotate( last_updated=Greatest("written", "published") ) self.assertEqual(articles.first().last_updated, now) @skipUnlessDBFeature("greatest_least_ignores_nulls") def test_ignores_null(self): now = timezone.now() Article.objects.create(title="Testing with Django", written=now) articles = Article.objects.annotate( last_updated=Greatest("written", "published") ) self.assertEqual(articles.first().last_updated, now) @skipIfDBFeature("greatest_least_ignores_nulls") def test_propagates_null(self): Article.objects.create(title="Testing with Django", written=timezone.now()) articles = Article.objects.annotate( last_updated=Greatest("written", "published") ) self.assertIsNone(articles.first().last_updated) def test_coalesce_workaround(self): past = datetime(1900, 1, 1) now = timezone.now() Article.objects.create(title="Testing with Django", written=now) articles = Article.objects.annotate( last_updated=Greatest( Coalesce("written", past), Coalesce("published", past), ), ) self.assertEqual(articles.first().last_updated, now) @skipUnless(connection.vendor == "mysql", "MySQL-specific workaround") def test_coalesce_workaround_mysql(self): past = datetime(1900, 1, 1) now = timezone.now() Article.objects.create(title="Testing with Django", written=now) past_sql = RawSQL("cast(%s as datetime)", (past,)) articles = Article.objects.annotate( last_updated=Greatest( Coalesce("written", past_sql), Coalesce("published", past_sql), ), ) self.assertEqual(articles.first().last_updated, now) def test_all_null(self): Article.objects.create(title="Testing with Django", written=timezone.now()) articles = Article.objects.annotate( last_updated=Greatest("published", "updated") ) self.assertIsNone(articles.first().last_updated) def test_one_expressions(self): with self.assertRaisesMessage( ValueError, "Greatest must take at least two expressions" ): Greatest("written") def test_related_field(self): author = Author.objects.create(name="John Smith", age=45) Fan.objects.create(name="Margaret", age=50, author=author) authors = Author.objects.annotate(highest_age=Greatest("age", "fans__age")) self.assertEqual(authors.first().highest_age, 50) def test_update(self): author = Author.objects.create(name="James Smith", goes_by="Jim") Author.objects.update(alias=Greatest("name", "goes_by")) author.refresh_from_db() self.assertEqual(author.alias, "Jim") def test_decimal_filter(self): obj = DecimalModel.objects.create(n1=Decimal("1.1"), n2=Decimal("1.2")) self.assertCountEqual( DecimalModel.objects.annotate( greatest=Greatest("n1", "n2"), ).filter(greatest=Decimal("1.2")), [obj], )
2a5b527fadac229a52ff092fedf7a5963135a0ded2e488ca7a9e6e03ae4cb0cd
from unittest import skipUnless from django.db import connection from django.db.models import Value from django.db.models.functions import NullIf from django.test import TestCase from ..models import Author class NullIfTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda", alias="Rhonda") def test_basic(self): authors = Author.objects.annotate(nullif=NullIf("alias", "name")).values_list( "nullif" ) self.assertSequenceEqual( authors, [ ("smithj",), ( "" if connection.features.interprets_empty_strings_as_nulls else None, ), ], ) def test_null_argument(self): authors = Author.objects.annotate( nullif=NullIf("name", Value(None)) ).values_list("nullif") self.assertSequenceEqual(authors, [("John Smith",), ("Rhonda",)]) def test_too_few_args(self): msg = "'NullIf' takes exactly 2 arguments (1 given)" with self.assertRaisesMessage(TypeError, msg): NullIf("name") @skipUnless(connection.vendor == "oracle", "Oracle specific test for NULL-literal") def test_null_literal(self): msg = "Oracle does not allow Value(None) for expression1." with self.assertRaisesMessage(ValueError, msg): list( Author.objects.annotate(nullif=NullIf(Value(None), "name")).values_list( "nullif" ) )
bf2338bc2d1ee91cc38e825d64d15bf47553d8e8bbf4ca9611967fe193f5aab0
from datetime import datetime, timedelta from decimal import Decimal from unittest import skipUnless from django.db import connection from django.db.models.expressions import RawSQL from django.db.models.functions import Coalesce, Least from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from django.utils import timezone from ..models import Article, Author, DecimalModel, Fan class LeastTests(TestCase): def test_basic(self): now = timezone.now() before = now - timedelta(hours=1) Article.objects.create( title="Testing with Django", written=before, published=now ) articles = Article.objects.annotate(first_updated=Least("written", "published")) self.assertEqual(articles.first().first_updated, before) @skipUnlessDBFeature("greatest_least_ignores_nulls") def test_ignores_null(self): now = timezone.now() Article.objects.create(title="Testing with Django", written=now) articles = Article.objects.annotate( first_updated=Least("written", "published"), ) self.assertEqual(articles.first().first_updated, now) @skipIfDBFeature("greatest_least_ignores_nulls") def test_propagates_null(self): Article.objects.create(title="Testing with Django", written=timezone.now()) articles = Article.objects.annotate(first_updated=Least("written", "published")) self.assertIsNone(articles.first().first_updated) def test_coalesce_workaround(self): future = datetime(2100, 1, 1) now = timezone.now() Article.objects.create(title="Testing with Django", written=now) articles = Article.objects.annotate( last_updated=Least( Coalesce("written", future), Coalesce("published", future), ), ) self.assertEqual(articles.first().last_updated, now) @skipUnless(connection.vendor == "mysql", "MySQL-specific workaround") def test_coalesce_workaround_mysql(self): future = datetime(2100, 1, 1) now = timezone.now() Article.objects.create(title="Testing with Django", written=now) future_sql = RawSQL("cast(%s as datetime)", (future,)) articles = Article.objects.annotate( last_updated=Least( Coalesce("written", future_sql), Coalesce("published", future_sql), ), ) self.assertEqual(articles.first().last_updated, now) def test_all_null(self): Article.objects.create(title="Testing with Django", written=timezone.now()) articles = Article.objects.annotate(first_updated=Least("published", "updated")) self.assertIsNone(articles.first().first_updated) def test_one_expressions(self): with self.assertRaisesMessage( ValueError, "Least must take at least two expressions" ): Least("written") def test_related_field(self): author = Author.objects.create(name="John Smith", age=45) Fan.objects.create(name="Margaret", age=50, author=author) authors = Author.objects.annotate(lowest_age=Least("age", "fans__age")) self.assertEqual(authors.first().lowest_age, 45) def test_update(self): author = Author.objects.create(name="James Smith", goes_by="Jim") Author.objects.update(alias=Least("name", "goes_by")) author.refresh_from_db() self.assertEqual(author.alias, "James Smith") def test_decimal_filter(self): obj = DecimalModel.objects.create(n1=Decimal("1.1"), n2=Decimal("1.2")) self.assertCountEqual( DecimalModel.objects.annotate( least=Least("n1", "n2"), ).filter(least=Decimal("1.1")), [obj], )
2aba87ef2a5033c321d2e0e55457cf3596b13d8a21c6372d7f59f5a218990212
from django.db import connection from django.db.models import F, Value from django.db.models.functions import Collate from django.test import TestCase from ..models import Author class CollateTests(TestCase): @classmethod def setUpTestData(cls): cls.author1 = Author.objects.create(alias="a", name="Jones 1") cls.author2 = Author.objects.create(alias="A", name="Jones 2") def test_collate_filter_ci(self): collation = connection.features.test_collations.get("ci") if not collation: self.skipTest("This backend does not support case-insensitive collations.") qs = Author.objects.filter(alias=Collate(Value("a"), collation)) self.assertEqual(qs.count(), 2) def test_collate_order_by_cs(self): collation = connection.features.test_collations.get("cs") if not collation: self.skipTest("This backend does not support case-sensitive collations.") qs = Author.objects.order_by(Collate("alias", collation)) self.assertSequenceEqual(qs, [self.author2, self.author1]) def test_language_collation_order_by(self): collation = connection.features.test_collations.get("swedish_ci") if not collation: self.skipTest("This backend does not support language collations.") author3 = Author.objects.create(alias="O", name="Jones") author4 = Author.objects.create(alias="Ö", name="Jones") author5 = Author.objects.create(alias="P", name="Jones") qs = Author.objects.order_by(Collate(F("alias"), collation), "name") self.assertSequenceEqual( qs, [self.author1, self.author2, author3, author5, author4], ) def test_invalid_collation(self): tests = [ None, "", 'et-x-icu" OR ', '"schema"."collation"', ] msg = "Invalid collation name: %r." for value in tests: with self.subTest(value), self.assertRaisesMessage(ValueError, msg % value): Collate(F("alias"), value)
02981a74c93a3c4e2c468e82a4d87583b6260704adb0df78dce5d3ff216e8971
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Sqrt from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class SqrtTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_sqrt=Sqrt("normal")).first() self.assertIsNone(obj.null_sqrt) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_sqrt=Sqrt("n1"), n2_sqrt=Sqrt("n2") ).first() self.assertIsInstance(obj.n1_sqrt, Decimal) self.assertIsInstance(obj.n2_sqrt, Decimal) self.assertAlmostEqual(obj.n1_sqrt, Decimal(math.sqrt(obj.n1))) self.assertAlmostEqual(obj.n2_sqrt, Decimal(math.sqrt(obj.n2))) def test_float(self): FloatModel.objects.create(f1=27.5, f2=0.33) obj = FloatModel.objects.annotate( f1_sqrt=Sqrt("f1"), f2_sqrt=Sqrt("f2") ).first() self.assertIsInstance(obj.f1_sqrt, float) self.assertIsInstance(obj.f2_sqrt, float) self.assertAlmostEqual(obj.f1_sqrt, math.sqrt(obj.f1)) self.assertAlmostEqual(obj.f2_sqrt, math.sqrt(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=20, normal=15, big=1) obj = IntegerModel.objects.annotate( small_sqrt=Sqrt("small"), normal_sqrt=Sqrt("normal"), big_sqrt=Sqrt("big"), ).first() self.assertIsInstance(obj.small_sqrt, float) self.assertIsInstance(obj.normal_sqrt, float) self.assertIsInstance(obj.big_sqrt, float) self.assertAlmostEqual(obj.small_sqrt, math.sqrt(obj.small)) self.assertAlmostEqual(obj.normal_sqrt, math.sqrt(obj.normal)) self.assertAlmostEqual(obj.big_sqrt, math.sqrt(obj.big)) def test_transform(self): with register_lookup(DecimalField, Sqrt): DecimalModel.objects.create(n1=Decimal("6.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__sqrt__gt=2).get() self.assertEqual(obj.n1, Decimal("6.0"))
50f0f77e69c8b0afd2129410ed426484ca1882b9cc2e99e920777a1f5881d94f
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Ceil from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class CeilTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_ceil=Ceil("normal")).first() self.assertIsNone(obj.null_ceil) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_ceil=Ceil("n1"), n2_ceil=Ceil("n2") ).first() self.assertIsInstance(obj.n1_ceil, Decimal) self.assertIsInstance(obj.n2_ceil, Decimal) self.assertEqual(obj.n1_ceil, Decimal(math.ceil(obj.n1))) self.assertEqual(obj.n2_ceil, Decimal(math.ceil(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-12.5, f2=21.33) obj = FloatModel.objects.annotate( f1_ceil=Ceil("f1"), f2_ceil=Ceil("f2") ).first() self.assertIsInstance(obj.f1_ceil, float) self.assertIsInstance(obj.f2_ceil, float) self.assertEqual(obj.f1_ceil, math.ceil(obj.f1)) self.assertEqual(obj.f2_ceil, math.ceil(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-11, normal=0, big=-100) obj = IntegerModel.objects.annotate( small_ceil=Ceil("small"), normal_ceil=Ceil("normal"), big_ceil=Ceil("big"), ).first() self.assertIsInstance(obj.small_ceil, int) self.assertIsInstance(obj.normal_ceil, int) self.assertIsInstance(obj.big_ceil, int) self.assertEqual(obj.small_ceil, math.ceil(obj.small)) self.assertEqual(obj.normal_ceil, math.ceil(obj.normal)) self.assertEqual(obj.big_ceil, math.ceil(obj.big)) def test_transform(self): with register_lookup(DecimalField, Ceil): DecimalModel.objects.create(n1=Decimal("3.12"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("1.25"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__ceil__gt=3).get() self.assertEqual(obj.n1, Decimal("3.12"))
57006f91c1c55910c2ef6c2a50b7c11d23beecb4ea0f38b142a36c5f3bf83700
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import ATan from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class ATanTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_atan=ATan("normal")).first() self.assertIsNone(obj.null_atan) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_atan=ATan("n1"), n2_atan=ATan("n2") ).first() self.assertIsInstance(obj.n1_atan, Decimal) self.assertIsInstance(obj.n2_atan, Decimal) self.assertAlmostEqual(obj.n1_atan, Decimal(math.atan(obj.n1))) self.assertAlmostEqual(obj.n2_atan, Decimal(math.atan(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate( f1_atan=ATan("f1"), f2_atan=ATan("f2") ).first() self.assertIsInstance(obj.f1_atan, float) self.assertIsInstance(obj.f2_atan, float) self.assertAlmostEqual(obj.f1_atan, math.atan(obj.f1)) self.assertAlmostEqual(obj.f2_atan, math.atan(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_atan=ATan("small"), normal_atan=ATan("normal"), big_atan=ATan("big"), ).first() self.assertIsInstance(obj.small_atan, float) self.assertIsInstance(obj.normal_atan, float) self.assertIsInstance(obj.big_atan, float) self.assertAlmostEqual(obj.small_atan, math.atan(obj.small)) self.assertAlmostEqual(obj.normal_atan, math.atan(obj.normal)) self.assertAlmostEqual(obj.big_atan, math.atan(obj.big)) def test_transform(self): with register_lookup(DecimalField, ATan): DecimalModel.objects.create(n1=Decimal("3.12"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-5"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__atan__gt=0).get() self.assertEqual(obj.n1, Decimal("3.12"))
1b207d330d4d1d48bd0d0531a02ba1ef2344105925b6d62fd0f43271f728e552
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Floor from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class FloorTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_floor=Floor("normal")).first() self.assertIsNone(obj.null_floor) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_floor=Floor("n1"), n2_floor=Floor("n2") ).first() self.assertIsInstance(obj.n1_floor, Decimal) self.assertIsInstance(obj.n2_floor, Decimal) self.assertEqual(obj.n1_floor, Decimal(math.floor(obj.n1))) self.assertEqual(obj.n2_floor, Decimal(math.floor(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate( f1_floor=Floor("f1"), f2_floor=Floor("f2") ).first() self.assertIsInstance(obj.f1_floor, float) self.assertIsInstance(obj.f2_floor, float) self.assertEqual(obj.f1_floor, math.floor(obj.f1)) self.assertEqual(obj.f2_floor, math.floor(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_floor=Floor("small"), normal_floor=Floor("normal"), big_floor=Floor("big"), ).first() self.assertIsInstance(obj.small_floor, int) self.assertIsInstance(obj.normal_floor, int) self.assertIsInstance(obj.big_floor, int) self.assertEqual(obj.small_floor, math.floor(obj.small)) self.assertEqual(obj.normal_floor, math.floor(obj.normal)) self.assertEqual(obj.big_floor, math.floor(obj.big)) def test_transform(self): with register_lookup(DecimalField, Floor): DecimalModel.objects.create(n1=Decimal("5.4"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("3.4"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__floor__gt=4).get() self.assertEqual(obj.n1, Decimal("5.4"))
e80d0b05bfb26bcddeeebb2c8f018a5c80be5c202d608d43bdc1b201d353201e
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import ACos from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class ACosTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_acos=ACos("normal")).first() self.assertIsNone(obj.null_acos) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-0.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_acos=ACos("n1"), n2_acos=ACos("n2") ).first() self.assertIsInstance(obj.n1_acos, Decimal) self.assertIsInstance(obj.n2_acos, Decimal) self.assertAlmostEqual(obj.n1_acos, Decimal(math.acos(obj.n1))) self.assertAlmostEqual(obj.n2_acos, Decimal(math.acos(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-0.5, f2=0.33) obj = FloatModel.objects.annotate( f1_acos=ACos("f1"), f2_acos=ACos("f2") ).first() self.assertIsInstance(obj.f1_acos, float) self.assertIsInstance(obj.f2_acos, float) self.assertAlmostEqual(obj.f1_acos, math.acos(obj.f1)) self.assertAlmostEqual(obj.f2_acos, math.acos(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=0, normal=1, big=-1) obj = IntegerModel.objects.annotate( small_acos=ACos("small"), normal_acos=ACos("normal"), big_acos=ACos("big"), ).first() self.assertIsInstance(obj.small_acos, float) self.assertIsInstance(obj.normal_acos, float) self.assertIsInstance(obj.big_acos, float) self.assertAlmostEqual(obj.small_acos, math.acos(obj.small)) self.assertAlmostEqual(obj.normal_acos, math.acos(obj.normal)) self.assertAlmostEqual(obj.big_acos, math.acos(obj.big)) def test_transform(self): with register_lookup(DecimalField, ACos): DecimalModel.objects.create(n1=Decimal("0.5"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-0.9"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__acos__lt=2).get() self.assertEqual(obj.n1, Decimal("0.5"))
9bfc9d93a1cc90e0febc14087aecc5ab1e35e43022b42d9cad6cb4da73cab47e
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Cos from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class CosTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_cos=Cos("normal")).first() self.assertIsNone(obj.null_cos) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate(n1_cos=Cos("n1"), n2_cos=Cos("n2")).first() self.assertIsInstance(obj.n1_cos, Decimal) self.assertIsInstance(obj.n2_cos, Decimal) self.assertAlmostEqual(obj.n1_cos, Decimal(math.cos(obj.n1))) self.assertAlmostEqual(obj.n2_cos, Decimal(math.cos(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate(f1_cos=Cos("f1"), f2_cos=Cos("f2")).first() self.assertIsInstance(obj.f1_cos, float) self.assertIsInstance(obj.f2_cos, float) self.assertAlmostEqual(obj.f1_cos, math.cos(obj.f1)) self.assertAlmostEqual(obj.f2_cos, math.cos(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_cos=Cos("small"), normal_cos=Cos("normal"), big_cos=Cos("big"), ).first() self.assertIsInstance(obj.small_cos, float) self.assertIsInstance(obj.normal_cos, float) self.assertIsInstance(obj.big_cos, float) self.assertAlmostEqual(obj.small_cos, math.cos(obj.small)) self.assertAlmostEqual(obj.normal_cos, math.cos(obj.normal)) self.assertAlmostEqual(obj.big_cos, math.cos(obj.big)) def test_transform(self): with register_lookup(DecimalField, Cos): DecimalModel.objects.create(n1=Decimal("-8.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("3.14"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__cos__gt=-0.2).get() self.assertEqual(obj.n1, Decimal("-8.0"))
f87c3b601e74de23dda999896dfa079418402304cf136a2d99d5d08c73656f8e
import unittest from decimal import Decimal from django.db import connection from django.db.models import DecimalField from django.db.models.functions import Pi, Round from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class RoundTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_round=Round("normal")).first() self.assertIsNone(obj.null_round) def test_null_with_precision(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_round=Round("normal", 5)).first() self.assertIsNone(obj.null_round) def test_null_with_negative_precision(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_round=Round("normal", -1)).first() self.assertIsNone(obj.null_round) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_round=Round("n1"), n2_round=Round("n2") ).first() self.assertIsInstance(obj.n1_round, Decimal) self.assertIsInstance(obj.n2_round, Decimal) self.assertAlmostEqual(obj.n1_round, obj.n1, places=0) self.assertAlmostEqual(obj.n2_round, obj.n2, places=0) def test_decimal_with_precision(self): DecimalModel.objects.create(n1=Decimal("-5.75"), n2=Pi()) obj = DecimalModel.objects.annotate( n1_round=Round("n1", 1), n2_round=Round("n2", 5), ).first() self.assertIsInstance(obj.n1_round, Decimal) self.assertIsInstance(obj.n2_round, Decimal) self.assertAlmostEqual(obj.n1_round, obj.n1, places=1) self.assertAlmostEqual(obj.n2_round, obj.n2, places=5) def test_decimal_with_negative_precision(self): DecimalModel.objects.create(n1=Decimal("365.25")) obj = DecimalModel.objects.annotate(n1_round=Round("n1", -1)).first() self.assertIsInstance(obj.n1_round, Decimal) self.assertEqual(obj.n1_round, 370) def test_float(self): FloatModel.objects.create(f1=-27.55, f2=0.55) obj = FloatModel.objects.annotate( f1_round=Round("f1"), f2_round=Round("f2") ).first() self.assertIsInstance(obj.f1_round, float) self.assertIsInstance(obj.f2_round, float) self.assertAlmostEqual(obj.f1_round, obj.f1, places=0) self.assertAlmostEqual(obj.f2_round, obj.f2, places=0) def test_float_with_precision(self): FloatModel.objects.create(f1=-5.75, f2=Pi()) obj = FloatModel.objects.annotate( f1_round=Round("f1", 1), f2_round=Round("f2", 5), ).first() self.assertIsInstance(obj.f1_round, float) self.assertIsInstance(obj.f2_round, float) self.assertAlmostEqual(obj.f1_round, obj.f1, places=1) self.assertAlmostEqual(obj.f2_round, obj.f2, places=5) def test_float_with_negative_precision(self): FloatModel.objects.create(f1=365.25) obj = FloatModel.objects.annotate(f1_round=Round("f1", -1)).first() self.assertIsInstance(obj.f1_round, float) self.assertEqual(obj.f1_round, 370) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_round=Round("small"), normal_round=Round("normal"), big_round=Round("big"), ).first() self.assertIsInstance(obj.small_round, int) self.assertIsInstance(obj.normal_round, int) self.assertIsInstance(obj.big_round, int) self.assertAlmostEqual(obj.small_round, obj.small, places=0) self.assertAlmostEqual(obj.normal_round, obj.normal, places=0) self.assertAlmostEqual(obj.big_round, obj.big, places=0) def test_integer_with_precision(self): IntegerModel.objects.create(small=-5, normal=3, big=-100) obj = IntegerModel.objects.annotate( small_round=Round("small", 1), normal_round=Round("normal", 5), big_round=Round("big", 2), ).first() self.assertIsInstance(obj.small_round, int) self.assertIsInstance(obj.normal_round, int) self.assertIsInstance(obj.big_round, int) self.assertAlmostEqual(obj.small_round, obj.small, places=1) self.assertAlmostEqual(obj.normal_round, obj.normal, places=5) self.assertAlmostEqual(obj.big_round, obj.big, places=2) def test_integer_with_negative_precision(self): IntegerModel.objects.create(normal=365) obj = IntegerModel.objects.annotate(normal_round=Round("normal", -1)).first() self.assertIsInstance(obj.normal_round, int) self.assertEqual(obj.normal_round, 370) def test_transform(self): with register_lookup(DecimalField, Round): DecimalModel.objects.create(n1=Decimal("2.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__round__gt=0).get() self.assertEqual(obj.n1, Decimal("2.0")) @unittest.skipUnless( connection.vendor == "sqlite", "SQLite doesn't support negative precision.", ) def test_unsupported_negative_precision(self): FloatModel.objects.create(f1=123.45) msg = "SQLite does not support negative precision." with self.assertRaisesMessage(ValueError, msg): FloatModel.objects.annotate(value=Round("f1", -1)).first()
8822d56401f068b5b687ac64018ca247d0108bed866bd6f3f7e5a61482dcb91f
from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Abs from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class AbsTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_abs=Abs("normal")).first() self.assertIsNone(obj.null_abs) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-0.8"), n2=Decimal("1.2")) obj = DecimalModel.objects.annotate(n1_abs=Abs("n1"), n2_abs=Abs("n2")).first() self.assertIsInstance(obj.n1_abs, Decimal) self.assertIsInstance(obj.n2_abs, Decimal) self.assertEqual(obj.n1, -obj.n1_abs) self.assertEqual(obj.n2, obj.n2_abs) def test_float(self): obj = FloatModel.objects.create(f1=-0.5, f2=12) obj = FloatModel.objects.annotate(f1_abs=Abs("f1"), f2_abs=Abs("f2")).first() self.assertIsInstance(obj.f1_abs, float) self.assertIsInstance(obj.f2_abs, float) self.assertEqual(obj.f1, -obj.f1_abs) self.assertEqual(obj.f2, obj.f2_abs) def test_integer(self): IntegerModel.objects.create(small=12, normal=0, big=-45) obj = IntegerModel.objects.annotate( small_abs=Abs("small"), normal_abs=Abs("normal"), big_abs=Abs("big"), ).first() self.assertIsInstance(obj.small_abs, int) self.assertIsInstance(obj.normal_abs, int) self.assertIsInstance(obj.big_abs, int) self.assertEqual(obj.small, obj.small_abs) self.assertEqual(obj.normal, obj.normal_abs) self.assertEqual(obj.big, -obj.big_abs) def test_transform(self): with register_lookup(DecimalField, Abs): DecimalModel.objects.create(n1=Decimal("-1.5"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-0.5"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__abs__gt=1).get() self.assertEqual(obj.n1, Decimal("-1.5"))
9f8bfa1795abde587d9826da4d2b6365a347dcd10559f17a2b839c0cdaa7eea8
from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Sign from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class SignTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_sign=Sign("normal")).first() self.assertIsNone(obj.null_sign) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_sign=Sign("n1"), n2_sign=Sign("n2") ).first() self.assertIsInstance(obj.n1_sign, Decimal) self.assertIsInstance(obj.n2_sign, Decimal) self.assertEqual(obj.n1_sign, Decimal("-1")) self.assertEqual(obj.n2_sign, Decimal("1")) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate( f1_sign=Sign("f1"), f2_sign=Sign("f2") ).first() self.assertIsInstance(obj.f1_sign, float) self.assertIsInstance(obj.f2_sign, float) self.assertEqual(obj.f1_sign, -1.0) self.assertEqual(obj.f2_sign, 1.0) def test_integer(self): IntegerModel.objects.create(small=-20, normal=0, big=20) obj = IntegerModel.objects.annotate( small_sign=Sign("small"), normal_sign=Sign("normal"), big_sign=Sign("big"), ).first() self.assertIsInstance(obj.small_sign, int) self.assertIsInstance(obj.normal_sign, int) self.assertIsInstance(obj.big_sign, int) self.assertEqual(obj.small_sign, -1) self.assertEqual(obj.normal_sign, 0) self.assertEqual(obj.big_sign, 1) def test_transform(self): with register_lookup(DecimalField, Sign): DecimalModel.objects.create(n1=Decimal("5.4"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-0.1"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__sign__lt=0, n2__sign=0).get() self.assertEqual(obj.n1, Decimal("-0.1"))
d0bab45457a40a1d5d5b8eda583bde234388f0f2ff4fc93076a3d885bbc5b2f5
import math from decimal import Decimal from django.db.models.functions import Log from django.test import TestCase from ..models import DecimalModel, FloatModel, IntegerModel class LogTests(TestCase): def test_null(self): IntegerModel.objects.create(big=100) obj = IntegerModel.objects.annotate( null_log_small=Log("small", "normal"), null_log_normal=Log("normal", "big"), null_log_big=Log("big", "normal"), ).first() self.assertIsNone(obj.null_log_small) self.assertIsNone(obj.null_log_normal) self.assertIsNone(obj.null_log_big) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("3.6")) obj = DecimalModel.objects.annotate(n_log=Log("n1", "n2")).first() self.assertIsInstance(obj.n_log, Decimal) self.assertAlmostEqual(obj.n_log, Decimal(math.log(obj.n2, obj.n1))) def test_float(self): FloatModel.objects.create(f1=2.0, f2=4.0) obj = FloatModel.objects.annotate(f_log=Log("f1", "f2")).first() self.assertIsInstance(obj.f_log, float) self.assertAlmostEqual(obj.f_log, math.log(obj.f2, obj.f1)) def test_integer(self): IntegerModel.objects.create(small=4, normal=8, big=2) obj = IntegerModel.objects.annotate( small_log=Log("small", "big"), normal_log=Log("normal", "big"), big_log=Log("big", "big"), ).first() self.assertIsInstance(obj.small_log, float) self.assertIsInstance(obj.normal_log, float) self.assertIsInstance(obj.big_log, float) self.assertAlmostEqual(obj.small_log, math.log(obj.big, obj.small)) self.assertAlmostEqual(obj.normal_log, math.log(obj.big, obj.normal)) self.assertAlmostEqual(obj.big_log, math.log(obj.big, obj.big))
23eb2f34d13b81721611c7572b5453ea5f519c611943227c20c6913eba589c59
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Cot from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class CotTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_cot=Cot("normal")).first() self.assertIsNone(obj.null_cot) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate(n1_cot=Cot("n1"), n2_cot=Cot("n2")).first() self.assertIsInstance(obj.n1_cot, Decimal) self.assertIsInstance(obj.n2_cot, Decimal) self.assertAlmostEqual(obj.n1_cot, Decimal(1 / math.tan(obj.n1))) self.assertAlmostEqual(obj.n2_cot, Decimal(1 / math.tan(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate(f1_cot=Cot("f1"), f2_cot=Cot("f2")).first() self.assertIsInstance(obj.f1_cot, float) self.assertIsInstance(obj.f2_cot, float) self.assertAlmostEqual(obj.f1_cot, 1 / math.tan(obj.f1)) self.assertAlmostEqual(obj.f2_cot, 1 / math.tan(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-5, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_cot=Cot("small"), normal_cot=Cot("normal"), big_cot=Cot("big"), ).first() self.assertIsInstance(obj.small_cot, float) self.assertIsInstance(obj.normal_cot, float) self.assertIsInstance(obj.big_cot, float) self.assertAlmostEqual(obj.small_cot, 1 / math.tan(obj.small)) self.assertAlmostEqual(obj.normal_cot, 1 / math.tan(obj.normal)) self.assertAlmostEqual(obj.big_cot, 1 / math.tan(obj.big)) def test_transform(self): with register_lookup(DecimalField, Cot): DecimalModel.objects.create(n1=Decimal("12.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__cot__gt=0).get() self.assertEqual(obj.n1, Decimal("1.0"))
4ec77cae105c360f00721a528e276cd76da7a98ddc5c791162ed8ba9a9ff1dc5
import math from decimal import Decimal from django.db.models.functions import ATan2 from django.test import TestCase from ..models import DecimalModel, FloatModel, IntegerModel class ATan2Tests(TestCase): def test_null(self): IntegerModel.objects.create(big=100) obj = IntegerModel.objects.annotate( null_atan2_sn=ATan2("small", "normal"), null_atan2_nb=ATan2("normal", "big"), null_atan2_bn=ATan2("big", "normal"), ).first() self.assertIsNone(obj.null_atan2_sn) self.assertIsNone(obj.null_atan2_nb) self.assertIsNone(obj.null_atan2_bn) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-9.9"), n2=Decimal("4.6")) obj = DecimalModel.objects.annotate(n_atan2=ATan2("n1", "n2")).first() self.assertIsInstance(obj.n_atan2, Decimal) self.assertAlmostEqual(obj.n_atan2, Decimal(math.atan2(obj.n1, obj.n2))) def test_float(self): FloatModel.objects.create(f1=-25, f2=0.33) obj = FloatModel.objects.annotate(f_atan2=ATan2("f1", "f2")).first() self.assertIsInstance(obj.f_atan2, float) self.assertAlmostEqual(obj.f_atan2, math.atan2(obj.f1, obj.f2)) def test_integer(self): IntegerModel.objects.create(small=0, normal=1, big=10) obj = IntegerModel.objects.annotate( atan2_sn=ATan2("small", "normal"), atan2_nb=ATan2("normal", "big"), ).first() self.assertIsInstance(obj.atan2_sn, float) self.assertIsInstance(obj.atan2_nb, float) self.assertAlmostEqual(obj.atan2_sn, math.atan2(obj.small, obj.normal)) self.assertAlmostEqual(obj.atan2_nb, math.atan2(obj.normal, obj.big))
fae39ebd6cc9af82a42123a33be9acac36722450bc937f86f5d76abd90aebe2a
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Degrees from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class DegreesTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_degrees=Degrees("normal")).first() self.assertIsNone(obj.null_degrees) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_degrees=Degrees("n1"), n2_degrees=Degrees("n2") ).first() self.assertIsInstance(obj.n1_degrees, Decimal) self.assertIsInstance(obj.n2_degrees, Decimal) self.assertAlmostEqual(obj.n1_degrees, Decimal(math.degrees(obj.n1))) self.assertAlmostEqual(obj.n2_degrees, Decimal(math.degrees(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate( f1_degrees=Degrees("f1"), f2_degrees=Degrees("f2") ).first() self.assertIsInstance(obj.f1_degrees, float) self.assertIsInstance(obj.f2_degrees, float) self.assertAlmostEqual(obj.f1_degrees, math.degrees(obj.f1)) self.assertAlmostEqual(obj.f2_degrees, math.degrees(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_degrees=Degrees("small"), normal_degrees=Degrees("normal"), big_degrees=Degrees("big"), ).first() self.assertIsInstance(obj.small_degrees, float) self.assertIsInstance(obj.normal_degrees, float) self.assertIsInstance(obj.big_degrees, float) self.assertAlmostEqual(obj.small_degrees, math.degrees(obj.small)) self.assertAlmostEqual(obj.normal_degrees, math.degrees(obj.normal)) self.assertAlmostEqual(obj.big_degrees, math.degrees(obj.big)) def test_transform(self): with register_lookup(DecimalField, Degrees): DecimalModel.objects.create(n1=Decimal("5.4"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-30"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__degrees__gt=0).get() self.assertEqual(obj.n1, Decimal("5.4"))
a1b410ab78358b12c274b669f60e166e11809fb92ce57abede451c31ed960017
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import ASin from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class ASinTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_asin=ASin("normal")).first() self.assertIsNone(obj.null_asin) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("0.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_asin=ASin("n1"), n2_asin=ASin("n2") ).first() self.assertIsInstance(obj.n1_asin, Decimal) self.assertIsInstance(obj.n2_asin, Decimal) self.assertAlmostEqual(obj.n1_asin, Decimal(math.asin(obj.n1))) self.assertAlmostEqual(obj.n2_asin, Decimal(math.asin(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-0.5, f2=0.87) obj = FloatModel.objects.annotate( f1_asin=ASin("f1"), f2_asin=ASin("f2") ).first() self.assertIsInstance(obj.f1_asin, float) self.assertIsInstance(obj.f2_asin, float) self.assertAlmostEqual(obj.f1_asin, math.asin(obj.f1)) self.assertAlmostEqual(obj.f2_asin, math.asin(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=0, normal=1, big=-1) obj = IntegerModel.objects.annotate( small_asin=ASin("small"), normal_asin=ASin("normal"), big_asin=ASin("big"), ).first() self.assertIsInstance(obj.small_asin, float) self.assertIsInstance(obj.normal_asin, float) self.assertIsInstance(obj.big_asin, float) self.assertAlmostEqual(obj.small_asin, math.asin(obj.small)) self.assertAlmostEqual(obj.normal_asin, math.asin(obj.normal)) self.assertAlmostEqual(obj.big_asin, math.asin(obj.big)) def test_transform(self): with register_lookup(DecimalField, ASin): DecimalModel.objects.create(n1=Decimal("0.1"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__asin__gt=1).get() self.assertEqual(obj.n1, Decimal("1.0"))
b2c3b61feda366ab9f2fa22f262d8080e42c98a9ef02473300622675a7c3e0be
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Tan from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class TanTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_tan=Tan("normal")).first() self.assertIsNone(obj.null_tan) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate(n1_tan=Tan("n1"), n2_tan=Tan("n2")).first() self.assertIsInstance(obj.n1_tan, Decimal) self.assertIsInstance(obj.n2_tan, Decimal) self.assertAlmostEqual(obj.n1_tan, Decimal(math.tan(obj.n1))) self.assertAlmostEqual(obj.n2_tan, Decimal(math.tan(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate(f1_tan=Tan("f1"), f2_tan=Tan("f2")).first() self.assertIsInstance(obj.f1_tan, float) self.assertIsInstance(obj.f2_tan, float) self.assertAlmostEqual(obj.f1_tan, math.tan(obj.f1)) self.assertAlmostEqual(obj.f2_tan, math.tan(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_tan=Tan("small"), normal_tan=Tan("normal"), big_tan=Tan("big"), ).first() self.assertIsInstance(obj.small_tan, float) self.assertIsInstance(obj.normal_tan, float) self.assertIsInstance(obj.big_tan, float) self.assertAlmostEqual(obj.small_tan, math.tan(obj.small)) self.assertAlmostEqual(obj.normal_tan, math.tan(obj.normal)) self.assertAlmostEqual(obj.big_tan, math.tan(obj.big)) def test_transform(self): with register_lookup(DecimalField, Tan): DecimalModel.objects.create(n1=Decimal("0.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("12.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__tan__lt=0).get() self.assertEqual(obj.n1, Decimal("12.0"))
d9c917d42c07df319a6d44daaa29426222d81498a31cf865cacafc0055573ba8
import math from decimal import Decimal from django.db.models.functions import Mod from django.test import TestCase from ..models import DecimalModel, FloatModel, IntegerModel class ModTests(TestCase): def test_null(self): IntegerModel.objects.create(big=100) obj = IntegerModel.objects.annotate( null_mod_small=Mod("small", "normal"), null_mod_normal=Mod("normal", "big"), ).first() self.assertIsNone(obj.null_mod_small) self.assertIsNone(obj.null_mod_normal) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-9.9"), n2=Decimal("4.6")) obj = DecimalModel.objects.annotate(n_mod=Mod("n1", "n2")).first() self.assertIsInstance(obj.n_mod, Decimal) self.assertAlmostEqual(obj.n_mod, Decimal(math.fmod(obj.n1, obj.n2))) def test_float(self): FloatModel.objects.create(f1=-25, f2=0.33) obj = FloatModel.objects.annotate(f_mod=Mod("f1", "f2")).first() self.assertIsInstance(obj.f_mod, float) self.assertAlmostEqual(obj.f_mod, math.fmod(obj.f1, obj.f2)) def test_integer(self): IntegerModel.objects.create(small=20, normal=15, big=1) obj = IntegerModel.objects.annotate( small_mod=Mod("small", "normal"), normal_mod=Mod("normal", "big"), big_mod=Mod("big", "small"), ).first() self.assertIsInstance(obj.small_mod, float) self.assertIsInstance(obj.normal_mod, float) self.assertIsInstance(obj.big_mod, float) self.assertEqual(obj.small_mod, math.fmod(obj.small, obj.normal)) self.assertEqual(obj.normal_mod, math.fmod(obj.normal, obj.big)) self.assertEqual(obj.big_mod, math.fmod(obj.big, obj.small))
981ffcd0a5aaf74911d7dbd7942b666fd135e0e5cf6f3764ad5a3482433ea9de
from decimal import Decimal from django.db.models.functions import Power from django.test import TestCase from ..models import DecimalModel, FloatModel, IntegerModel class PowerTests(TestCase): def test_null(self): IntegerModel.objects.create(big=100) obj = IntegerModel.objects.annotate( null_power_small=Power("small", "normal"), null_power_normal=Power("normal", "big"), null_power_big=Power("big", "normal"), ).first() self.assertIsNone(obj.null_power_small) self.assertIsNone(obj.null_power_normal) self.assertIsNone(obj.null_power_big) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("-0.6")) obj = DecimalModel.objects.annotate(n_power=Power("n1", "n2")).first() self.assertIsInstance(obj.n_power, Decimal) self.assertAlmostEqual(obj.n_power, Decimal(obj.n1**obj.n2)) def test_float(self): FloatModel.objects.create(f1=2.3, f2=1.1) obj = FloatModel.objects.annotate(f_power=Power("f1", "f2")).first() self.assertIsInstance(obj.f_power, float) self.assertAlmostEqual(obj.f_power, obj.f1**obj.f2) def test_integer(self): IntegerModel.objects.create(small=-1, normal=20, big=3) obj = IntegerModel.objects.annotate( small_power=Power("small", "normal"), normal_power=Power("normal", "big"), big_power=Power("big", "small"), ).first() self.assertIsInstance(obj.small_power, float) self.assertIsInstance(obj.normal_power, float) self.assertIsInstance(obj.big_power, float) self.assertAlmostEqual(obj.small_power, obj.small**obj.normal) self.assertAlmostEqual(obj.normal_power, obj.normal**obj.big) self.assertAlmostEqual(obj.big_power, obj.big**obj.small)
51c54801d981c22452cecca9ad4be52943ab4ed6ac2aebcd4cdb5b754b58f304
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Radians from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class RadiansTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_radians=Radians("normal")).first() self.assertIsNone(obj.null_radians) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate( n1_radians=Radians("n1"), n2_radians=Radians("n2") ).first() self.assertIsInstance(obj.n1_radians, Decimal) self.assertIsInstance(obj.n2_radians, Decimal) self.assertAlmostEqual(obj.n1_radians, Decimal(math.radians(obj.n1))) self.assertAlmostEqual(obj.n2_radians, Decimal(math.radians(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate( f1_radians=Radians("f1"), f2_radians=Radians("f2") ).first() self.assertIsInstance(obj.f1_radians, float) self.assertIsInstance(obj.f2_radians, float) self.assertAlmostEqual(obj.f1_radians, math.radians(obj.f1)) self.assertAlmostEqual(obj.f2_radians, math.radians(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_radians=Radians("small"), normal_radians=Radians("normal"), big_radians=Radians("big"), ).first() self.assertIsInstance(obj.small_radians, float) self.assertIsInstance(obj.normal_radians, float) self.assertIsInstance(obj.big_radians, float) self.assertAlmostEqual(obj.small_radians, math.radians(obj.small)) self.assertAlmostEqual(obj.normal_radians, math.radians(obj.normal)) self.assertAlmostEqual(obj.big_radians, math.radians(obj.big)) def test_transform(self): with register_lookup(DecimalField, Radians): DecimalModel.objects.create(n1=Decimal("2.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__radians__gt=0).get() self.assertEqual(obj.n1, Decimal("2.0"))
717c41686f6e34c915e2874570394e1f088c0b7d0f940e00d020b67e1c9ca5ad
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Sin from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class SinTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_sin=Sin("normal")).first() self.assertIsNone(obj.null_sin) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate(n1_sin=Sin("n1"), n2_sin=Sin("n2")).first() self.assertIsInstance(obj.n1_sin, Decimal) self.assertIsInstance(obj.n2_sin, Decimal) self.assertAlmostEqual(obj.n1_sin, Decimal(math.sin(obj.n1))) self.assertAlmostEqual(obj.n2_sin, Decimal(math.sin(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate(f1_sin=Sin("f1"), f2_sin=Sin("f2")).first() self.assertIsInstance(obj.f1_sin, float) self.assertIsInstance(obj.f2_sin, float) self.assertAlmostEqual(obj.f1_sin, math.sin(obj.f1)) self.assertAlmostEqual(obj.f2_sin, math.sin(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_sin=Sin("small"), normal_sin=Sin("normal"), big_sin=Sin("big"), ).first() self.assertIsInstance(obj.small_sin, float) self.assertIsInstance(obj.normal_sin, float) self.assertIsInstance(obj.big_sin, float) self.assertAlmostEqual(obj.small_sin, math.sin(obj.small)) self.assertAlmostEqual(obj.normal_sin, math.sin(obj.normal)) self.assertAlmostEqual(obj.big_sin, math.sin(obj.big)) def test_transform(self): with register_lookup(DecimalField, Sin): DecimalModel.objects.create(n1=Decimal("5.4"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("0.1"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__sin__lt=0).get() self.assertEqual(obj.n1, Decimal("5.4"))
61310782e52432106c185e92afa17b0ec7f603d324d73c6ecaaf57a449279799
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Exp from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class ExpTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_exp=Exp("normal")).first() self.assertIsNone(obj.null_exp) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate(n1_exp=Exp("n1"), n2_exp=Exp("n2")).first() self.assertIsInstance(obj.n1_exp, Decimal) self.assertIsInstance(obj.n2_exp, Decimal) self.assertAlmostEqual(obj.n1_exp, Decimal(math.exp(obj.n1))) self.assertAlmostEqual(obj.n2_exp, Decimal(math.exp(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate(f1_exp=Exp("f1"), f2_exp=Exp("f2")).first() self.assertIsInstance(obj.f1_exp, float) self.assertIsInstance(obj.f2_exp, float) self.assertAlmostEqual(obj.f1_exp, math.exp(obj.f1)) self.assertAlmostEqual(obj.f2_exp, math.exp(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_exp=Exp("small"), normal_exp=Exp("normal"), big_exp=Exp("big"), ).first() self.assertIsInstance(obj.small_exp, float) self.assertIsInstance(obj.normal_exp, float) self.assertIsInstance(obj.big_exp, float) self.assertAlmostEqual(obj.small_exp, math.exp(obj.small)) self.assertAlmostEqual(obj.normal_exp, math.exp(obj.normal)) self.assertAlmostEqual(obj.big_exp, math.exp(obj.big)) def test_transform(self): with register_lookup(DecimalField, Exp): DecimalModel.objects.create(n1=Decimal("12.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__exp__gt=10).get() self.assertEqual(obj.n1, Decimal("12.0"))
870099db34470e3c283eaff26a3e929f891cf5b92c4bbd28be2c409c1f0ce50f
import math from django.db.models.functions import Pi from django.test import TestCase from ..models import FloatModel class PiTests(TestCase): def test(self): FloatModel.objects.create(f1=2.5, f2=15.9) obj = FloatModel.objects.annotate(pi=Pi()).first() self.assertIsInstance(obj.pi, float) self.assertAlmostEqual(obj.pi, math.pi, places=5)
10dc87faa96c8a3d066eaabe342d28596bd0c58f485644f4643e1606f0b7c0bd
import math from decimal import Decimal from django.db.models import DecimalField from django.db.models.functions import Ln from django.test import TestCase from django.test.utils import register_lookup from ..models import DecimalModel, FloatModel, IntegerModel class LnTests(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_ln=Ln("normal")).first() self.assertIsNone(obj.null_ln) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate(n1_ln=Ln("n1"), n2_ln=Ln("n2")).first() self.assertIsInstance(obj.n1_ln, Decimal) self.assertIsInstance(obj.n2_ln, Decimal) self.assertAlmostEqual(obj.n1_ln, Decimal(math.log(obj.n1))) self.assertAlmostEqual(obj.n2_ln, Decimal(math.log(obj.n2))) def test_float(self): FloatModel.objects.create(f1=27.5, f2=0.33) obj = FloatModel.objects.annotate(f1_ln=Ln("f1"), f2_ln=Ln("f2")).first() self.assertIsInstance(obj.f1_ln, float) self.assertIsInstance(obj.f2_ln, float) self.assertAlmostEqual(obj.f1_ln, math.log(obj.f1)) self.assertAlmostEqual(obj.f2_ln, math.log(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=20, normal=15, big=1) obj = IntegerModel.objects.annotate( small_ln=Ln("small"), normal_ln=Ln("normal"), big_ln=Ln("big"), ).first() self.assertIsInstance(obj.small_ln, float) self.assertIsInstance(obj.normal_ln, float) self.assertIsInstance(obj.big_ln, float) self.assertAlmostEqual(obj.small_ln, math.log(obj.small)) self.assertAlmostEqual(obj.normal_ln, math.log(obj.normal)) self.assertAlmostEqual(obj.big_ln, math.log(obj.big)) def test_transform(self): with register_lookup(DecimalField, Ln): DecimalModel.objects.create(n1=Decimal("12.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__ln__gt=0).get() self.assertEqual(obj.n1, Decimal("12.0"))
286a11190609b0414dfedd63d324713b1d134f0c67ae81e5212e02044938885d
#!/usr/bin/env python """ Helper script to update sampleproject's translation catalogs. When a bug has been identified related to i18n, this helps capture the issue by using catalogs created from management commands. Example: The string "Two %% Three %%%" renders differently using translate and blocktranslate. This issue is difficult to debug, it could be a problem with extraction, interpolation, or both. How this script helps: * Add {% translate "Two %% Three %%%" %} and blocktranslate equivalent to templates. * Run this script. * Test extraction - verify the new msgid in sampleproject's django.po. * Add a translation to sampleproject's django.po. * Run this script. * Test interpolation - verify templatetag rendering, test each in a template that is rendered using an activated language from sampleproject's locale. * Tests should fail, issue captured. * Fix issue. * Run this script. * Tests all pass. """ import os import re import sys proj_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.abspath(os.path.join(proj_dir, "..", "..", ".."))) def update_translation_catalogs(): """Run makemessages and compilemessages in sampleproject.""" from django.core.management import call_command prev_cwd = os.getcwd() os.chdir(proj_dir) call_command("makemessages") call_command("compilemessages") # keep the diff friendly - remove 'POT-Creation-Date' pofile = os.path.join(proj_dir, "locale", "fr", "LC_MESSAGES", "django.po") with open(pofile) as f: content = f.read() content = re.sub(r'^"POT-Creation-Date.+$\s', "", content, flags=re.MULTILINE) with open(pofile, "w") as f: f.write(content) os.chdir(prev_cwd) if __name__ == "__main__": update_translation_catalogs()
d8efd86c5bced5d3b692945ec658fda38bec2183f4f594a8de2a3ca1cb36e855
#!/usr/bin/env python import os import sys sys.path.append(os.path.abspath(os.path.join("..", "..", ".."))) if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sampleproject.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
1fc80d8d9097979ced777a81b17b1036aa0413a3f68aaf6322afb2429b1a1cbe
from django.utils.translation import gettext as _ string1 = _("This is a translatable string.") string2 = _("This is another translatable string.")
785dfcb3151dab3eacb78c4e89e5e447e2e89f7127d888f6645fa9154e608208
from django.utils.translation import gettext as _ from django.utils.translation import ngettext # Translators: This comment should be extracted dummy1 = _("This is a translatable string.") # This comment should not be extracted dummy2 = _("This is another translatable string.") # This file has a literal with plural forms. When processed first, makemessages # shouldn't create a .po file with duplicate `Plural-Forms` headers number = 3 dummy3 = ngettext("%(number)s Foo", "%(number)s Foos", number) % {"number": number} dummy4 = _("Size") # This string is intentionally duplicated in test.html dummy5 = _("This literal should be included.")
5dfc4af3a583ebbd3d4dcea37e3af5f09ccdfda3a743b1393343f7ed0ec8bbf4
import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponse, HttpResponsePermanentRedirect from django.middleware.locale import LocaleMiddleware from django.template import Context, Template from django.test import SimpleTestCase, override_settings from django.test.client import RequestFactory from django.test.utils import override_script_prefix from django.urls import clear_url_caches, reverse, translate_url from django.utils import translation class PermanentRedirectLocaleMiddleWare(LocaleMiddleware): response_redirect_class = HttpResponsePermanentRedirect @override_settings( USE_I18N=True, LOCALE_PATHS=[ os.path.join(os.path.dirname(__file__), "locale"), ], LANGUAGE_CODE="en-us", LANGUAGES=[ ("nl", "Dutch"), ("en", "English"), ("pt-br", "Brazilian Portuguese"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.patterns.urls.default", TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(os.path.dirname(__file__), "templates")], "OPTIONS": { "context_processors": [ "django.template.context_processors.i18n", ], }, } ], ) class URLTestCaseBase(SimpleTestCase): """ TestCase base-class for the URL tests. """ def setUp(self): # Make sure the cache is empty before we are doing our tests. clear_url_caches() def tearDown(self): # Make sure we will leave an empty cache for other testcases. clear_url_caches() class URLPrefixTests(URLTestCaseBase): """ Tests if the `i18n_patterns` is adding the prefix correctly. """ def test_not_prefixed(self): with translation.override("en"): self.assertEqual(reverse("not-prefixed"), "/not-prefixed/") self.assertEqual( reverse("not-prefixed-included-url"), "/not-prefixed-include/foo/" ) with translation.override("nl"): self.assertEqual(reverse("not-prefixed"), "/not-prefixed/") self.assertEqual( reverse("not-prefixed-included-url"), "/not-prefixed-include/foo/" ) def test_prefixed(self): with translation.override("en"): self.assertEqual(reverse("prefixed"), "/en/prefixed/") with translation.override("nl"): self.assertEqual(reverse("prefixed"), "/nl/prefixed/") with translation.override(None): self.assertEqual( reverse("prefixed"), "/%s/prefixed/" % settings.LANGUAGE_CODE ) @override_settings(ROOT_URLCONF="i18n.patterns.urls.wrong") def test_invalid_prefix_use(self): msg = "Using i18n_patterns in an included URLconf is not allowed." with self.assertRaisesMessage(ImproperlyConfigured, msg): reverse("account:register") @override_settings(ROOT_URLCONF="i18n.patterns.urls.disabled") class URLDisabledTests(URLTestCaseBase): @override_settings(USE_I18N=False) def test_prefixed_i18n_disabled(self): with translation.override("en"): self.assertEqual(reverse("prefixed"), "/prefixed/") with translation.override("nl"): self.assertEqual(reverse("prefixed"), "/prefixed/") class RequestURLConfTests(SimpleTestCase): @override_settings(ROOT_URLCONF="i18n.patterns.urls.path_unused") def test_request_urlconf_considered(self): request = RequestFactory().get("/nl/") request.urlconf = "i18n.patterns.urls.default" middleware = LocaleMiddleware(lambda req: HttpResponse()) with translation.override("nl"): middleware.process_request(request) self.assertEqual(request.LANGUAGE_CODE, "nl") @override_settings(ROOT_URLCONF="i18n.patterns.urls.path_unused") class PathUnusedTests(URLTestCaseBase): """ If no i18n_patterns is used in root URLconfs, then no language activation activation happens based on url prefix. """ def test_no_lang_activate(self): response = self.client.get("/nl/foo/") self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["content-language"], "en") self.assertEqual(response.context["LANGUAGE_CODE"], "en") class URLTranslationTests(URLTestCaseBase): """ Tests if the pattern-strings are translated correctly (within the `i18n_patterns` and the normal `patterns` function). """ def test_no_prefix_translated(self): with translation.override("en"): self.assertEqual(reverse("no-prefix-translated"), "/translated/") self.assertEqual( reverse("no-prefix-translated-slug", kwargs={"slug": "yeah"}), "/translated/yeah/", ) with translation.override("nl"): self.assertEqual(reverse("no-prefix-translated"), "/vertaald/") self.assertEqual( reverse("no-prefix-translated-slug", kwargs={"slug": "yeah"}), "/vertaald/yeah/", ) with translation.override("pt-br"): self.assertEqual(reverse("no-prefix-translated"), "/traduzidos/") self.assertEqual( reverse("no-prefix-translated-slug", kwargs={"slug": "yeah"}), "/traduzidos/yeah/", ) def test_users_url(self): with translation.override("en"): self.assertEqual(reverse("users"), "/en/users/") with translation.override("nl"): self.assertEqual(reverse("users"), "/nl/gebruikers/") self.assertEqual(reverse("prefixed_xml"), "/nl/prefixed.xml") with translation.override("pt-br"): self.assertEqual(reverse("users"), "/pt-br/usuarios/") def test_translate_url_utility(self): with translation.override("en"): self.assertEqual( translate_url("/en/nonexistent/", "nl"), "/en/nonexistent/" ) self.assertEqual(translate_url("/en/users/", "nl"), "/nl/gebruikers/") # Namespaced URL self.assertEqual( translate_url("/en/account/register/", "nl"), "/nl/profiel/registreren/" ) # path() URL pattern self.assertEqual( translate_url("/en/account/register-as-path/", "nl"), "/nl/profiel/registreren-als-pad/", ) self.assertEqual(translation.get_language(), "en") # URL with parameters. self.assertEqual( translate_url("/en/with-arguments/regular-argument/", "nl"), "/nl/with-arguments/regular-argument/", ) self.assertEqual( translate_url( "/en/with-arguments/regular-argument/optional.html", "nl" ), "/nl/with-arguments/regular-argument/optional.html", ) with translation.override("nl"): self.assertEqual(translate_url("/nl/gebruikers/", "en"), "/en/users/") self.assertEqual(translation.get_language(), "nl") class URLNamespaceTests(URLTestCaseBase): """ Tests if the translations are still working within namespaces. """ def test_account_register(self): with translation.override("en"): self.assertEqual(reverse("account:register"), "/en/account/register/") self.assertEqual( reverse("account:register-as-path"), "/en/account/register-as-path/" ) with translation.override("nl"): self.assertEqual(reverse("account:register"), "/nl/profiel/registreren/") self.assertEqual( reverse("account:register-as-path"), "/nl/profiel/registreren-als-pad/" ) class URLRedirectTests(URLTestCaseBase): """ Tests if the user gets redirected to the right URL when there is no language-prefix in the request URL. """ def test_no_prefix_response(self): response = self.client.get("/not-prefixed/") self.assertEqual(response.status_code, 200) def test_en_redirect(self): response = self.client.get("/account/register/", HTTP_ACCEPT_LANGUAGE="en") self.assertRedirects(response, "/en/account/register/") response = self.client.get(response.headers["location"]) self.assertEqual(response.status_code, 200) def test_en_redirect_wrong_url(self): response = self.client.get("/profiel/registreren/", HTTP_ACCEPT_LANGUAGE="en") self.assertEqual(response.status_code, 404) def test_nl_redirect(self): response = self.client.get("/profiel/registreren/", HTTP_ACCEPT_LANGUAGE="nl") self.assertRedirects(response, "/nl/profiel/registreren/") response = self.client.get(response.headers["location"]) self.assertEqual(response.status_code, 200) def test_nl_redirect_wrong_url(self): response = self.client.get("/account/register/", HTTP_ACCEPT_LANGUAGE="nl") self.assertEqual(response.status_code, 404) def test_pt_br_redirect(self): response = self.client.get("/conta/registre-se/", HTTP_ACCEPT_LANGUAGE="pt-br") self.assertRedirects(response, "/pt-br/conta/registre-se/") response = self.client.get(response.headers["location"]) self.assertEqual(response.status_code, 200) def test_pl_pl_redirect(self): # language from outside of the supported LANGUAGES list response = self.client.get("/account/register/", HTTP_ACCEPT_LANGUAGE="pl-pl") self.assertRedirects(response, "/en/account/register/") response = self.client.get(response.headers["location"]) self.assertEqual(response.status_code, 200) @override_settings( MIDDLEWARE=[ "i18n.patterns.tests.PermanentRedirectLocaleMiddleWare", "django.middleware.common.CommonMiddleware", ], ) def test_custom_redirect_class(self): response = self.client.get("/account/register/", HTTP_ACCEPT_LANGUAGE="en") self.assertRedirects(response, "/en/account/register/", 301) class URLVaryAcceptLanguageTests(URLTestCaseBase): """ 'Accept-Language' is not added to the Vary header when using prefixed URLs. """ def test_no_prefix_response(self): response = self.client.get("/not-prefixed/") self.assertEqual(response.status_code, 200) self.assertEqual(response.get("Vary"), "Accept-Language") def test_en_redirect(self): """ The redirect to a prefixed URL depends on 'Accept-Language' and 'Cookie', but once prefixed no header is set. """ response = self.client.get("/account/register/", HTTP_ACCEPT_LANGUAGE="en") self.assertRedirects(response, "/en/account/register/") self.assertEqual(response.get("Vary"), "Accept-Language, Cookie") response = self.client.get(response.headers["location"]) self.assertEqual(response.status_code, 200) self.assertFalse(response.get("Vary")) class URLRedirectWithoutTrailingSlashTests(URLTestCaseBase): """ Tests the redirect when the requested URL doesn't end with a slash (`settings.APPEND_SLASH=True`). """ def test_not_prefixed_redirect(self): response = self.client.get("/not-prefixed", HTTP_ACCEPT_LANGUAGE="en") self.assertRedirects(response, "/not-prefixed/", 301) def test_en_redirect(self): response = self.client.get( "/account/register", HTTP_ACCEPT_LANGUAGE="en", follow=True ) # We only want one redirect, bypassing CommonMiddleware self.assertEqual(response.redirect_chain, [("/en/account/register/", 302)]) self.assertRedirects(response, "/en/account/register/", 302) response = self.client.get( "/prefixed.xml", HTTP_ACCEPT_LANGUAGE="en", follow=True ) self.assertRedirects(response, "/en/prefixed.xml", 302) class URLRedirectWithoutTrailingSlashSettingTests(URLTestCaseBase): """ Tests the redirect when the requested URL doesn't end with a slash (`settings.APPEND_SLASH=False`). """ @override_settings(APPEND_SLASH=False) def test_not_prefixed_redirect(self): response = self.client.get("/not-prefixed", HTTP_ACCEPT_LANGUAGE="en") self.assertEqual(response.status_code, 404) @override_settings(APPEND_SLASH=False) def test_en_redirect(self): response = self.client.get( "/account/register-without-slash", HTTP_ACCEPT_LANGUAGE="en" ) self.assertRedirects(response, "/en/account/register-without-slash", 302) response = self.client.get(response.headers["location"]) self.assertEqual(response.status_code, 200) class URLResponseTests(URLTestCaseBase): """Tests if the response has the correct language code.""" def test_not_prefixed_with_prefix(self): response = self.client.get("/en/not-prefixed/") self.assertEqual(response.status_code, 404) def test_en_url(self): response = self.client.get("/en/account/register/") self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["content-language"], "en") self.assertEqual(response.context["LANGUAGE_CODE"], "en") def test_nl_url(self): response = self.client.get("/nl/profiel/registreren/") self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["content-language"], "nl") self.assertEqual(response.context["LANGUAGE_CODE"], "nl") def test_wrong_en_prefix(self): response = self.client.get("/en/profiel/registreren/") self.assertEqual(response.status_code, 404) def test_wrong_nl_prefix(self): response = self.client.get("/nl/account/register/") self.assertEqual(response.status_code, 404) def test_pt_br_url(self): response = self.client.get("/pt-br/conta/registre-se/") self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["content-language"], "pt-br") self.assertEqual(response.context["LANGUAGE_CODE"], "pt-br") def test_en_path(self): response = self.client.get("/en/account/register-as-path/") self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["content-language"], "en") self.assertEqual(response.context["LANGUAGE_CODE"], "en") def test_nl_path(self): response = self.client.get("/nl/profiel/registreren-als-pad/") self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["content-language"], "nl") self.assertEqual(response.context["LANGUAGE_CODE"], "nl") class URLRedirectWithScriptAliasTests(URLTestCaseBase): """ #21579 - LocaleMiddleware should respect the script prefix. """ def test_language_prefix_with_script_prefix(self): prefix = "/script_prefix" with override_script_prefix(prefix): response = self.client.get( "/prefixed/", HTTP_ACCEPT_LANGUAGE="en", SCRIPT_NAME=prefix ) self.assertRedirects( response, "%s/en/prefixed/" % prefix, target_status_code=404 ) class URLTagTests(URLTestCaseBase): """ Test if the language tag works. """ def test_strings_only(self): t = Template( """{% load i18n %} {% language 'nl' %}{% url 'no-prefix-translated' %}{% endlanguage %} {% language 'pt-br' %}{% url 'no-prefix-translated' %}{% endlanguage %}""" ) self.assertEqual( t.render(Context({})).strip().split(), ["/vertaald/", "/traduzidos/"] ) def test_context(self): ctx = Context({"lang1": "nl", "lang2": "pt-br"}) tpl = Template( """{% load i18n %} {% language lang1 %}{% url 'no-prefix-translated' %}{% endlanguage %} {% language lang2 %}{% url 'no-prefix-translated' %}{% endlanguage %}""" ) self.assertEqual( tpl.render(ctx).strip().split(), ["/vertaald/", "/traduzidos/"] ) def test_args(self): tpl = Template( """ {% load i18n %} {% language 'nl' %} {% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %} {% language 'pt-br' %} {% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %} """ ) self.assertEqual( tpl.render(Context({})).strip().split(), ["/vertaald/apo/", "/traduzidos/apo/"], ) def test_kwargs(self): tpl = Template( """ {% load i18n %} {% language 'nl' %} {% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %} {% language 'pt-br' %} {% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %} """ ) self.assertEqual( tpl.render(Context({})).strip().split(), ["/vertaald/apo/", "/traduzidos/apo/"], )
ff01444544149afd075e49c7940503655e93675d1970c50eb466f7b616a2dc45
from django.apps import AppConfig class LoadingAppConfig(AppConfig): name = "i18n.loading_app"
d6d981d39221cfafaef2815c45e5ffecb77215eec92029025378c99f2859f596
import os from django.contrib.contenttypes.models import ContentType from django.test import TestCase, override_settings from django.utils import translation @override_settings( USE_I18N=True, LOCALE_PATHS=[ os.path.join(os.path.dirname(__file__), "locale"), ], LANGUAGE_CODE="en", LANGUAGES=[ ("en", "English"), ("fr", "French"), ], ) class ContentTypeTests(TestCase): def test_verbose_name(self): company_type = ContentType.objects.get(app_label="i18n", model="company") with translation.override("en"): self.assertEqual(str(company_type), "i18n | Company") with translation.override("fr"): self.assertEqual(str(company_type), "i18n | Société")