Debian Codegraph @

tests/gis_tests/geoapp/test_expressions.py

raw
1 from django.contrib.gis.db.models import F, GeometryField, Value, functions
2 from django.contrib.gis.geos import Point, Polygon
3 from django.db import connection
4 from django.db.models import Count, Min
5 from django.test import TestCase, skipUnlessDBFeature
6
7 from .models import City, ManyPointModel, MultiFields
8
9
10 class GeoExpressionsTests(TestCase):
11 fixtures = ["initial"]
12
13 def test_geometry_value_annotation(self):
14 p = Point(1, 1, srid=4326)
15 point = City.objects.annotate(p=Value(p, GeometryField(srid=4326))).first().p
16 self.assertEqual(point, p)
17
18 @skipUnlessDBFeature("supports_transform")
19 def test_geometry_value_annotation_different_srid(self):
20 p = Point(1, 1, srid=32140)
21 point = City.objects.annotate(p=Value(p, GeometryField(srid=4326))).first().p
22 self.assertTrue(point.equals_exact(p.transform(4326, clone=True), 10**-5))
23 self.assertEqual(point.srid, 4326)
24
25 @skipUnlessDBFeature("supports_geography")
26 def test_geography_value(self):
27 p = Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1)))
28 area = (
29 City.objects.annotate(
30 a=functions.Area(Value(p, GeometryField(srid=4326, geography=True)))
31 )
32 .first()
33 .a
34 )
35 self.assertAlmostEqual(area.sq_km, 12305.1, 0)
36
37 def test_update_from_other_field(self):
38 p1 = Point(1, 1, srid=4326)
39 p2 = Point(2, 2, srid=4326)
40 obj = ManyPointModel.objects.create(
41 point1=p1,
42 point2=p2,
43 point3=p2.transform(3857, clone=True),
44 )
45 # Updating a point to a point of the same SRID.
46 ManyPointModel.objects.filter(pk=obj.pk).update(point2=F("point1"))
47 obj.refresh_from_db()
48 self.assertEqual(obj.point2, p1)
49 # Updating a point to a point with a different SRID.
50 if connection.features.supports_transform:
51 ManyPointModel.objects.filter(pk=obj.pk).update(point3=F("point1"))
52 obj.refresh_from_db()
53 self.assertTrue(
54 obj.point3.equals_exact(p1.transform(3857, clone=True), 0.1)
55 )
56
57 def test_multiple_annotation(self):
58 multi_field = MultiFields.objects.create(
59 point=Point(1, 1),
60 city=City.objects.get(name="Houston"),
61 poly=Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))),
62 )
63 qs = (
64 City.objects.values("name")
65 .order_by("name")
66 .annotate(
67 distance=Min(
68 functions.Distance("multifields__point", multi_field.city.point)
69 ),
70 )
71 .annotate(count=Count("multifields"))
72 )
73 self.assertTrue(qs.first())
74
75 @skipUnlessDBFeature("has_Translate_function")
76 def test_update_with_expression(self):
77 city = City.objects.create(point=Point(1, 1, srid=4326))
78 City.objects.filter(pk=city.pk).update(point=functions.Translate("point", 1, 1))
79 city.refresh_from_db()
80 self.assertEqual(city.point, Point(2, 2, srid=4326))