repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/test_querystring.py
tests/template_tests/syntax_tests/test_querystring.py
from django.http import QueryDict from django.template import RequestContext from django.template.base import TemplateSyntaxError from django.test import RequestFactory, SimpleTestCase from ..utils import setup class QueryStringTagTests(SimpleTestCase): request_factory = RequestFactory() def assertRenderEqual(self, template_name, context, expected): output = self.engine.render_to_string(template_name, context) self.assertEqual(output, expected) def assertTemplateSyntaxError(self, template_name, context, expected): with self.assertRaisesMessage(TemplateSyntaxError, expected): self.engine.render_to_string(template_name, context) @setup({"querystring_empty_get_params": "{% querystring %}"}) def test_querystring_empty_get_params(self): context = RequestContext(self.request_factory.get("/")) self.assertRenderEqual("querystring_empty_get_params", context, expected="?") @setup({"querystring_remove_all_params": "{% querystring a=None %}"}) def test_querystring_remove_all_params(self): non_empty_context = RequestContext(self.request_factory.get("/?a=b")) empty_context = RequestContext(self.request_factory.get("/")) for context in [non_empty_context, empty_context]: with self.subTest(context=context): self.assertRenderEqual("querystring_remove_all_params", context, "?") @setup( { "querystring_remove_all_params_custom_querydict": ( "{% querystring my_query_dict my_dict a=None %}" ) } ) def test_querystring_remove_all_params_custom_querydict(self): context = {"my_query_dict": QueryDict("a=1&b=2"), "my_dict": {"b": None}} self.assertRenderEqual( "querystring_remove_all_params_custom_querydict", context, "?" ) @setup({"querystring_non_empty_get_params": "{% querystring %}"}) def test_querystring_non_empty_get_params(self): request = self.request_factory.get("/", {"a": "b"}) context = RequestContext(request) self.assertRenderEqual( "querystring_non_empty_get_params", context, expected="?a=b" ) @setup({"querystring_multiple": "{% querystring %}"}) def test_querystring_multiple(self): request = self.request_factory.get("/", {"x": "y", "a": "b"}) context = RequestContext(request) self.assertRenderEqual("querystring_multiple", context, expected="?x=y&a=b") @setup({"querystring_multiple_lists": "{% querystring %}"}) def test_querystring_multiple_lists(self): request = self.request_factory.get("/", {"x": ["y", "z"], "a": ["b", "c"]}) context = RequestContext(request) expected = "?x=y&x=z&a=b&a=c" self.assertRenderEqual("querystring_multiple_lists", context, expected=expected) @setup({"querystring_lists_with_replacement": "{% querystring a=1 %}"}) def test_querystring_lists_with_replacement(self): request = self.request_factory.get("/", {"x": ["y", "z"], "a": ["b", "c"]}) context = RequestContext(request) expected = "?x=y&x=z&a=1" self.assertRenderEqual( "querystring_lists_with_replacement", context, expected=expected ) @setup({"querystring_empty_params": "{% querystring qd %}"}) def test_querystring_empty_params(self): cases = [{}, QueryDict()] request = self.request_factory.get("/") qs = "?a=b" request_with_qs = self.request_factory.get(f"/{qs}") for param in cases: # Empty `query_dict` and nothing on `request.GET`. with self.subTest(param=param): context = RequestContext(request, {"qd": param}) self.assertRenderEqual( "querystring_empty_params", context, expected="?" ) # Empty `query_dict` and a query string in `request.GET`. with self.subTest(param=param, qs=qs): context = RequestContext(request_with_qs, {"qd": param}) expected = "?" if param is not None else qs self.assertRenderEqual("querystring_empty_params", context, expected) @setup({"querystring_replace": "{% querystring a=1 %}"}) def test_querystring_replace(self): request = self.request_factory.get("/", {"x": "y", "a": "b"}) context = RequestContext(request) self.assertRenderEqual("querystring_replace", context, expected="?x=y&a=1") @setup({"querystring_add": "{% querystring test_new='something' %}"}) def test_querystring_add(self): request = self.request_factory.get("/", {"a": "b"}) context = RequestContext(request) self.assertRenderEqual( "querystring_add", context, expected="?a=b&test_new=something" ) @setup({"querystring_remove": "{% querystring test=None a=1 %}"}) def test_querystring_remove(self): request = self.request_factory.get("/", {"test": "value", "a": "1"}) context = RequestContext(request) self.assertRenderEqual("querystring_remove", context, expected="?a=1") @setup({"querystring_remove_nonexistent": "{% querystring nonexistent=None a=1 %}"}) def test_querystring_remove_nonexistent(self): request = self.request_factory.get("/", {"x": "y", "a": "1"}) context = RequestContext(request) self.assertRenderEqual( "querystring_remove_nonexistent", context, expected="?x=y&a=1" ) @setup({"querystring_remove_dict": "{% querystring my_dict a=1 %}"}) def test_querystring_remove_from_dict(self): request = self.request_factory.get("/", {"test": "value"}) context = RequestContext(request, {"my_dict": {"test": None}}) self.assertRenderEqual("querystring_remove_dict", context, expected="?a=1") @setup({"querystring_remove_querydict": "{% querystring request my_query_dict %}"}) def test_querystring_remove_querydict(self): request = self.request_factory.get("/", {"x": "1"}) my_qd = QueryDict(mutable=True) my_qd["x"] = None context = RequestContext( request, {"request": request.GET, "my_query_dict": my_qd} ) self.assertRenderEqual("querystring_remove_querydict", context, expected="?") @setup( {"querystring_remove_querydict_many": "{% querystring request my_query_dict %}"} ) def test_querystring_remove_querydict_many(self): request = self.request_factory.get( "/", {"test": ["value1", "value2"], "a": [1, 2]} ) qd_none = QueryDict(mutable=True) qd_none["test"] = None qd_list_none = QueryDict(mutable=True) qd_list_none.setlist("test", [None, None]) qd_empty_list = QueryDict(mutable=True) qd_empty_list.setlist("test", []) for qd in (qd_none, qd_list_none, qd_empty_list): with self.subTest(my_query_dict=qd): context = RequestContext( request, {"request": request.GET, "my_query_dict": qd} ) self.assertRenderEqual( "querystring_remove_querydict_many", context, expected="?a=1&a=2", ) @setup({"querystring_variable": "{% querystring a=a %}"}) def test_querystring_variable(self): request = self.request_factory.get("/") context = RequestContext(request, {"a": 1}) self.assertRenderEqual("querystring_variable", context, expected="?a=1") @setup({"querystring_dict": "{% querystring my_dict %}"}) def test_querystring_dict(self): context = {"my_dict": {"a": 1}} self.assertRenderEqual("querystring_dict", context, expected="?a=1") @setup({"querystring_dict_list": "{% querystring my_dict %}"}) def test_querystring_dict_list_values(self): context = {"my_dict": {"a": [1, 2]}} self.assertRenderEqual( "querystring_dict_list", context, expected="?a=1&a=2" ) @setup( { "querystring_multiple_args_override": ( "{% querystring my_dict my_query_dict x=3 y=None %}" ) } ) def test_querystring_multiple_args_override(self): context = {"my_dict": {"x": 0, "y": 42}, "my_query_dict": QueryDict("a=1&b=2")} self.assertRenderEqual( "querystring_multiple_args_override", context, expected="?x=3&a=1&b=2", ) @setup({"querystring_request_get_ignored": "{% querystring my_mapping %}"}) def test_querystring_request_get_ignored(self): cases = [({"y": "x"}, "?y=x"), ({}, "?")] request = self.request_factory.get("/", {"x": "y", "a": "b"}) for param, expected in cases: with self.subTest(param=param): context = RequestContext(request, {"my_mapping": param}) self.assertRenderEqual( "querystring_request_get_ignored", context, expected=expected ) @setup({"querystring_same_arg": "{% querystring a=1 a=2 %}"}) def test_querystring_same_arg(self): msg = "'querystring' received multiple values for keyword argument 'a'" self.assertTemplateSyntaxError("querystring_same_arg", {}, msg) @setup({"querystring_non_mapping_args": "{% querystring somevar %}"}) def test_querystring_non_mapping_args(self): cases = [None, 0, "", []] request = self.request_factory.get("/") msg = ( "querystring requires mappings for positional arguments (got %r " "instead)." ) for param in cases: with self.subTest(param=param): context = RequestContext(request, {"somevar": param}) self.assertTemplateSyntaxError( "querystring_non_mapping_args", context, msg % param ) @setup({"querystring_non_string_dict_keys": "{% querystring my_dict %}"}) def test_querystring_non_string_dict_keys(self): context = {"my_dict": {0: 1}} msg = "querystring requires strings for mapping keys (got 0 instead)." self.assertTemplateSyntaxError("querystring_non_string_dict_keys", context, msg) @setup({"querystring_list": "{% querystring a=my_list %}"}) def test_querystring_add_list(self): request = self.request_factory.get("/") context = RequestContext(request, {"my_list": [2, 3]}) self.assertRenderEqual("querystring_list", context, expected="?a=2&a=3") @setup({"querystring_dict": "{% querystring a=my_dict %}"}) def test_querystring_add_dict(self): request = self.request_factory.get("/") context = RequestContext(request, {"my_dict": {i: i * 2 for i in range(3)}}) self.assertRenderEqual( "querystring_dict", context, expected="?a=0&a=1&a=2" ) @setup({"querystring_query_dict": "{% querystring request.GET a=2 %}"}) def test_querystring_with_explicit_query_dict(self): request = self.request_factory.get("/", {"a": 1}) self.assertRenderEqual( "querystring_query_dict", {"request": request}, expected="?a=2" ) @setup({"querystring_query_dict_no_request": "{% querystring my_query_dict a=2 %}"}) def test_querystring_with_explicit_query_dict_and_no_request(self): context = {"my_query_dict": QueryDict("a=1&b=2")} self.assertRenderEqual( "querystring_query_dict_no_request", context, expected="?a=2&b=2" ) @setup({"querystring_no_request_no_query_dict": "{% querystring %}"}) def test_querystring_without_request_or_explicit_query_dict(self): msg = "'Context' object has no attribute 'request'" with self.assertRaisesMessage(AttributeError, msg): self.engine.render_to_string("querystring_no_request_no_query_dict")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/test_for.py
tests/template_tests/syntax_tests/test_for.py
from django.template import TemplateSyntaxError from django.template.defaulttags import ForNode from django.test import SimpleTestCase from ..utils import setup class ForTagTests(SimpleTestCase): libraries = {"custom": "template_tests.templatetags.custom"} @setup({"for-tag01": "{% for val in values %}{{ val }}{% endfor %}"}) def test_for_tag01(self): output = self.engine.render_to_string("for-tag01", {"values": [1, 2, 3]}) self.assertEqual(output, "123") @setup({"for-tag02": "{% for val in values reversed %}{{ val }}{% endfor %}"}) def test_for_tag02(self): output = self.engine.render_to_string("for-tag02", {"values": [1, 2, 3]}) self.assertEqual(output, "321") @setup( {"for-tag-vars01": "{% for val in values %}{{ forloop.counter }}{% endfor %}"} ) def test_for_tag_vars01(self): output = self.engine.render_to_string("for-tag-vars01", {"values": [6, 6, 6]}) self.assertEqual(output, "123") @setup( {"for-tag-vars02": "{% for val in values %}{{ forloop.counter0 }}{% endfor %}"} ) def test_for_tag_vars02(self): output = self.engine.render_to_string("for-tag-vars02", {"values": [6, 6, 6]}) self.assertEqual(output, "012") @setup( { "for-tag-vars03": ( "{% for val in values %}{{ forloop.revcounter }}{% endfor %}" ) } ) def test_for_tag_vars03(self): output = self.engine.render_to_string("for-tag-vars03", {"values": [6, 6, 6]}) self.assertEqual(output, "321") @setup( { "for-tag-vars04": ( "{% for val in values %}{{ forloop.revcounter0 }}{% endfor %}" ) } ) def test_for_tag_vars04(self): output = self.engine.render_to_string("for-tag-vars04", {"values": [6, 6, 6]}) self.assertEqual(output, "210") @setup( { "for-tag-vars05": "{% for val in values %}" "{% if forloop.first %}f{% else %}x{% endif %}{% endfor %}" } ) def test_for_tag_vars05(self): output = self.engine.render_to_string("for-tag-vars05", {"values": [6, 6, 6]}) self.assertEqual(output, "fxx") @setup( { "for-tag-vars06": "{% for val in values %}" "{% if forloop.last %}l{% else %}x{% endif %}{% endfor %}" } ) def test_for_tag_vars06(self): output = self.engine.render_to_string("for-tag-vars06", {"values": [6, 6, 6]}) self.assertEqual(output, "xxl") @setup( { "for-tag-unpack01": ( "{% for key,value in items %}{{ key }}:{{ value }}/{% endfor %}" ) } ) def test_for_tag_unpack01(self): output = self.engine.render_to_string( "for-tag-unpack01", {"items": (("one", 1), ("two", 2))} ) self.assertEqual(output, "one:1/two:2/") @setup( { "for-tag-unpack03": ( "{% for key, value in items %}{{ key }}:{{ value }}/{% endfor %}" ) } ) def test_for_tag_unpack03(self): output = self.engine.render_to_string( "for-tag-unpack03", {"items": (("one", 1), ("two", 2))} ) self.assertEqual(output, "one:1/two:2/") @setup( { "for-tag-unpack04": ( "{% for key , value in items %}{{ key }}:{{ value }}/{% endfor %}" ) } ) def test_for_tag_unpack04(self): output = self.engine.render_to_string( "for-tag-unpack04", {"items": (("one", 1), ("two", 2))} ) self.assertEqual(output, "one:1/two:2/") @setup( { "for-tag-unpack05": ( "{% for key ,value in items %}{{ key }}:{{ value }}/{% endfor %}" ) } ) def test_for_tag_unpack05(self): output = self.engine.render_to_string( "for-tag-unpack05", {"items": (("one", 1), ("two", 2))} ) self.assertEqual(output, "one:1/two:2/") @setup( { "for-tag-unpack06": ( "{% for key value in items %}{{ key }}:{{ value }}/{% endfor %}" ) } ) def test_for_tag_unpack06(self): msg = "'for' tag received an invalid argument: for key value in items" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string( "for-tag-unpack06", {"items": (("one", 1), ("two", 2))} ) @setup( { "for-tag-unpack07": ( "{% for key,,value in items %}{{ key }}:{{ value }}/{% endfor %}" ) } ) def test_for_tag_unpack07(self): msg = "'for' tag received an invalid argument: for key,,value in items" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string( "for-tag-unpack07", {"items": (("one", 1), ("two", 2))} ) @setup( { "for-tag-unpack08": ( "{% for key,value, in items %}{{ key }}:{{ value }}/{% endfor %}" ) } ) def test_for_tag_unpack08(self): msg = "'for' tag received an invalid argument: for key,value, in items" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string( "for-tag-unpack08", {"items": (("one", 1), ("two", 2))} ) @setup({"double-quote": '{% for "k" in items %}{{ "k" }}/{% endfor %}'}) def test_unpack_double_quote(self): msg = """'for' tag received an invalid argument: for "k" in items""" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("double-quote", {"items": (1, 2)}) @setup({"single-quote": "{% for 'k' in items %}{{ k }}/{% endfor %}"}) def test_unpack_single_quote(self): msg = """'for' tag received an invalid argument: for 'k' in items""" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("single-quote", {"items": (1, 2)}) @setup({"vertical-bar": "{% for k|upper in items %}{{ k|upper }}/{% endfor %}"}) def test_unpack_vertical_bar(self): msg = "'for' tag received an invalid argument: for k|upper in items" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("vertical-bar", {"items": (1, 2)}) @setup( { "for-tag-unpack09": ( "{% for val in items %}{{ val.0 }}:{{ val.1 }}/{% endfor %}" ) } ) def test_for_tag_unpack09(self): """ A single loopvar doesn't truncate the list in val. """ output = self.engine.render_to_string( "for-tag-unpack09", {"items": (("one", 1), ("two", 2))} ) self.assertEqual(output, "one:1/two:2/") @setup( { "for-tag-unpack13": ( "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}" ) } ) def test_for_tag_unpack13(self): output = self.engine.render_to_string( "for-tag-unpack13", {"items": (("one", 1, "carrot"), ("two", 2, "cheese"))} ) if self.engine.string_if_invalid: self.assertEqual(output, "one:1,carrot/two:2,cheese/") else: self.assertEqual(output, "one:1,carrot/two:2,cheese/") @setup( { "for-tag-empty01": ( "{% for val in values %}{{ val }}{% empty %}empty text{% endfor %}" ) } ) def test_for_tag_empty01(self): output = self.engine.render_to_string("for-tag-empty01", {"values": [1, 2, 3]}) self.assertEqual(output, "123") @setup( { "for-tag-empty02": ( "{% for val in values %}{{ val }}{% empty %}values array empty" "{% endfor %}" ) } ) def test_for_tag_empty02(self): output = self.engine.render_to_string("for-tag-empty02", {"values": []}) self.assertEqual(output, "values array empty") @setup( { "for-tag-empty03": "{% for val in values %}" "{{ val }}{% empty %}values array not found{% endfor %}" } ) def test_for_tag_empty03(self): output = self.engine.render_to_string("for-tag-empty03") self.assertEqual(output, "values array not found") @setup( { "for-tag-filter-ws": ( "{% load custom %}{% for x in s|noop:'x y' %}{{ x }}{% endfor %}" ) } ) def test_for_tag_filter_ws(self): """ #19882 """ output = self.engine.render_to_string("for-tag-filter-ws", {"s": "abc"}) self.assertEqual(output, "abc") @setup( {"for-tag-unpack-strs": "{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}"} ) def test_for_tag_unpack_strs(self): output = self.engine.render_to_string( "for-tag-unpack-strs", {"items": ("ab", "ac")} ) self.assertEqual(output, "a:b/a:c/") @setup({"for-tag-unpack10": "{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}"}) def test_for_tag_unpack10(self): with self.assertRaisesMessage( ValueError, "Need 2 values to unpack in for loop; got 3." ): self.engine.render_to_string( "for-tag-unpack10", {"items": (("one", 1, "carrot"), ("two", 2, "orange"))}, ) @setup( { "for-tag-unpack11": ( "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}" ) } ) def test_for_tag_unpack11(self): with self.assertRaisesMessage( ValueError, "Need 3 values to unpack in for loop; got 2." ): self.engine.render_to_string( "for-tag-unpack11", {"items": (("one", 1), ("two", 2))}, ) @setup( { "for-tag-unpack12": ( "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}" ) } ) def test_for_tag_unpack12(self): with self.assertRaisesMessage( ValueError, "Need 3 values to unpack in for loop; got 2." ): self.engine.render_to_string( "for-tag-unpack12", {"items": (("one", 1, "carrot"), ("two", 2))} ) @setup({"for-tag-unpack14": "{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}"}) def test_for_tag_unpack14(self): with self.assertRaisesMessage( ValueError, "Need 2 values to unpack in for loop; got 1." ): self.engine.render_to_string("for-tag-unpack14", {"items": (1, 2)}) @setup( { "main": '{% with alpha=alpha.values %}{% include "base" %}{% endwith %}_' '{% with alpha=alpha.extra %}{% include "base" %}{% endwith %}', "base": "{% for x, y in alpha %}{{ x }}:{{ y }},{% endfor %}", } ) def test_for_tag_context(self): """ ForNode.render() pops the values it pushes to the context (#28001). """ output = self.engine.render_to_string( "main", { "alpha": { "values": [("two", 2), ("four", 4)], "extra": [("six", 6), ("eight", 8)], }, }, ) self.assertEqual(output, "two:2,four:4,_six:6,eight:8,") @setup({"invalid_for_loop": "{% for x items %}{{ x }}{% endfor %}"}) def test_invalid_arg(self): msg = "'for' statements should have at least four words: for x items" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("invalid_for_loop", {"items": (1, 2)}) @setup({"invalid_for_loop": "{% for x from items %}{{ x }}{% endfor %}"}) def test_invalid_in_keyword(self): msg = "'for' statements should use the format 'for x in y': for x from items" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("invalid_for_loop", {"items": (1, 2)}) @setup( { "forloop-length": "{% for val in values %}{{ forloop.length }}{% endfor %}", "forloop-length-reversed": "{% for val in values reversed %}" "{{ forloop.length }}{% endfor %}", } ) def test_forloop_length(self): cases = [ ([1, 2, 3], "333"), ([1, 2, 3, 4, 5, 6], "666666"), ([], ""), ] for values, expected_output in cases: for template in ["forloop-length", "forloop-length-reversed"]: with self.subTest(expected_output=expected_output, template=template): output = self.engine.render_to_string(template, {"values": values}) self.assertEqual(output, expected_output) class ForNodeTests(SimpleTestCase): def test_repr(self): node = ForNode( "x", "sequence", is_reversed=True, nodelist_loop=["val"], nodelist_empty=["val2"], ) self.assertEqual( repr(node), "<ForNode: for x in sequence, tail_len: 1 reversed>" )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/test_partials.py
tests/template_tests/syntax_tests/test_partials.py
from django.template import ( Context, TemplateDoesNotExist, TemplateSyntaxError, VariableDoesNotExist, ) from django.template.base import Token, TokenType from django.test import SimpleTestCase from django.views.debug import ExceptionReporter from ..utils import setup partial_templates = { "partial_base.html": ( "<main>{% block main %}Default main content.{% endblock main %}</main>" ), "partial_included.html": ( "INCLUDED TEMPLATE START\n" "{% partialdef included-partial %}\n" "THIS IS CONTENT FROM THE INCLUDED PARTIAL\n" "{% endpartialdef %}\n\n" "Now using the partial: {% partial included-partial %}\n" "INCLUDED TEMPLATE END\n" ), } valid_partialdef_names = ( "dot.in.name", "'space in name'", "exclamation!", "@at", "slash/something", "inline", "inline-inline", "INLINE" "with+plus", "with&amp", "with%percent", "with,comma", "with:colon", "with;semicolon", "[brackets]", "(parens)", "{curly}", ) def gen_partial_template(name, *args, **kwargs): if args or kwargs: extra = " ".join((args, *("{k}={v}" for k, v in kwargs.items()))) + " " else: extra = "" return ( f"{{% partialdef {name} {extra}%}}TEST with {name}!{{% endpartialdef %}}" f"{{% partial {name} %}}" ) class PartialTagTests(SimpleTestCase): libraries = {"bad_tag": "template_tests.templatetags.bad_tag"} @setup({name: gen_partial_template(name) for name in valid_partialdef_names}) def test_valid_partialdef_names(self): for template_name in valid_partialdef_names: with self.subTest(template_name=template_name): output = self.engine.render_to_string(template_name) self.assertEqual(output, f"TEST with {template_name}!") @setup( { "basic": ( "{% partialdef testing-name %}" "HERE IS THE TEST CONTENT" "{% endpartialdef %}" "{% partial testing-name %}" ), "basic_inline": ( "{% partialdef testing-name inline %}" "HERE IS THE TEST CONTENT" "{% endpartialdef %}" ), "inline_inline": ( "{% partialdef inline inline %}" "HERE IS THE TEST CONTENT" "{% endpartialdef %}" ), "with_newlines": ( "{% partialdef testing-name %}\n" "HERE IS THE TEST CONTENT\n" "{% endpartialdef testing-name %}\n" "{% partial testing-name %}" ), } ) def test_basic_usage(self): for template_name in ( "basic", "basic_inline", "inline_inline", "with_newlines", ): with self.subTest(template_name=template_name): output = self.engine.render_to_string(template_name) self.assertEqual(output.strip(), "HERE IS THE TEST CONTENT") @setup( { "inline_partial_with_context": ( "BEFORE\n" "{% partialdef testing-name inline %}" "HERE IS THE TEST CONTENT" "{% endpartialdef %}\n" "AFTER" ) } ) def test_partial_inline_only_with_before_and_after_content(self): output = self.engine.render_to_string("inline_partial_with_context") self.assertEqual(output.strip(), "BEFORE\nHERE IS THE TEST CONTENT\nAFTER") @setup( { "inline_partial_explicit_end": ( "{% partialdef testing-name inline %}" "HERE IS THE TEST CONTENT" "{% endpartialdef testing-name %}\n" "{% partial testing-name %}" ) } ) def test_partial_inline_and_used_once(self): output = self.engine.render_to_string("inline_partial_explicit_end") self.assertEqual(output, "HERE IS THE TEST CONTENT\nHERE IS THE TEST CONTENT") @setup( { "inline_partial_with_usage": ( "BEFORE\n" "{% partialdef content_snippet inline %}" "HERE IS THE TEST CONTENT" "{% endpartialdef %}\n" "AFTER\n" "{% partial content_snippet %}" ) } ) def test_partial_inline_and_used_once_with_before_and_after_content(self): output = self.engine.render_to_string("inline_partial_with_usage") self.assertEqual( output.strip(), "BEFORE\nHERE IS THE TEST CONTENT\nAFTER\nHERE IS THE TEST CONTENT", ) @setup( { "partial_used_before_definition": ( "TEMPLATE START\n" "{% partial testing-name %}\n" "MIDDLE CONTENT\n" "{% partialdef testing-name %}\n" "THIS IS THE PARTIAL CONTENT\n" "{% endpartialdef %}\n" "TEMPLATE END" ), } ) def test_partial_used_before_definition(self): output = self.engine.render_to_string("partial_used_before_definition") expected = ( "TEMPLATE START\n\nTHIS IS THE PARTIAL CONTENT\n\n" "MIDDLE CONTENT\n\nTEMPLATE END" ) self.assertEqual(output, expected) @setup( { "partial_with_extends": ( "{% extends 'partial_base.html' %}" "{% partialdef testing-name %}Inside Content{% endpartialdef %}" "{% block main %}" "Main content with {% partial testing-name %}" "{% endblock %}" ), }, partial_templates, ) def test_partial_defined_outside_main_block(self): output = self.engine.render_to_string("partial_with_extends") self.assertIn("<main>Main content with Inside Content</main>", output) @setup( { "partial_with_extends_and_block_super": ( "{% extends 'partial_base.html' %}" "{% partialdef testing-name %}Inside Content{% endpartialdef %}" "{% block main %}{{ block.super }} " "Main content with {% partial testing-name %}" "{% endblock %}" ), }, partial_templates, ) def test_partial_used_with_block_super(self): output = self.engine.render_to_string("partial_with_extends_and_block_super") self.assertIn( "<main>Default main content. Main content with Inside Content</main>", output, ) @setup( { "partial_with_include": ( "MAIN TEMPLATE START\n" "{% include 'partial_included.html' %}\n" "MAIN TEMPLATE END" ) }, partial_templates, ) def test_partial_in_included_template(self): output = self.engine.render_to_string("partial_with_include") expected = ( "MAIN TEMPLATE START\nINCLUDED TEMPLATE START\n\n\n" "Now using the partial: \n" "THIS IS CONTENT FROM THE INCLUDED PARTIAL\n\n" "INCLUDED TEMPLATE END\n\nMAIN TEMPLATE END" ) self.assertEqual(output, expected) @setup( { "partial_as_include_in_other_template": ( "MAIN TEMPLATE START\n" "{% include 'partial_included.html#included-partial' %}\n" "MAIN TEMPLATE END" ) }, partial_templates, ) def test_partial_as_include_in_template(self): output = self.engine.render_to_string("partial_as_include_in_other_template") expected = ( "MAIN TEMPLATE START\n\n" "THIS IS CONTENT FROM THE INCLUDED PARTIAL\n\n" "MAIN TEMPLATE END" ) self.assertEqual(output, expected) @setup( { "nested_simple": ( "{% extends 'base.html' %}" "{% block content %}" "This is my main page." "{% partialdef outer inline %}" " It hosts a couple of partials.\n" " {% partialdef inner inline %}" " And an inner one." " {% endpartialdef inner %}" "{% endpartialdef outer %}" "{% endblock content %}" ), "use_outer": "{% include 'nested_simple#outer' %}", "use_inner": "{% include 'nested_simple#inner' %}", } ) def test_nested_partials(self): with self.subTest(template_name="use_outer"): output = self.engine.render_to_string("use_outer") self.assertEqual( [line.strip() for line in output.split("\n")], ["It hosts a couple of partials.", "And an inner one."], ) with self.subTest(template_name="use_inner"): output = self.engine.render_to_string("use_inner") self.assertEqual(output.strip(), "And an inner one.") @setup( { "partial_undefined_name": "{% partial undefined %}", "partial_missing_name": "{% partial %}", "partial_closing_tag": ( "{% partialdef testing-name %}TEST{% endpartialdef %}" "{% partial testing-name %}{% endpartial %}" ), "partialdef_missing_name": "{% partialdef %}{% endpartialdef %}", "partialdef_missing_close_tag": "{% partialdef name %}TEST", "partialdef_opening_closing_name_mismatch": ( "{% partialdef testing-name %}TEST{% endpartialdef invalid %}" ), "partialdef_invalid_name": gen_partial_template("with\nnewline"), "partialdef_extra_params": ( "{% partialdef testing-name inline extra %}TEST{% endpartialdef %}" ), "partialdef_duplicated_names": ( "{% partialdef testing-name %}TEST{% endpartialdef %}" "{% partialdef testing-name %}TEST{% endpartialdef %}" "{% partial testing-name %}" ), "partialdef_duplicated_nested_names": ( "{% partialdef testing-name %}" "TEST" "{% partialdef testing-name %}TEST{% endpartialdef %}" "{% endpartialdef %}" "{% partial testing-name %}" ), }, ) def test_basic_parse_errors(self): for template_name, error_msg in ( ( "partial_undefined_name", "Partial 'undefined' is not defined in the current template.", ), ("partial_missing_name", "'partial' tag requires a single argument"), ("partial_closing_tag", "Invalid block tag on line 1: 'endpartial'"), ("partialdef_missing_name", "'partialdef' tag requires a name"), ("partialdef_missing_close_tag", "Unclosed tag on line 1: 'partialdef'"), ( "partialdef_opening_closing_name_mismatch", "expected 'endpartialdef' or 'endpartialdef testing-name'.", ), ("partialdef_invalid_name", "Invalid block tag on line 3: 'endpartialdef'"), ("partialdef_extra_params", "'partialdef' tag takes at most 2 arguments"), ( "partialdef_duplicated_names", "Partial 'testing-name' is already defined in the " "'partialdef_duplicated_names' template.", ), ( "partialdef_duplicated_nested_names", "Partial 'testing-name' is already defined in the " "'partialdef_duplicated_nested_names' template.", ), ): with ( self.subTest(template_name=template_name), self.assertRaisesMessage(TemplateSyntaxError, error_msg), ): self.engine.render_to_string(template_name) @setup( { "with_params": ( "{% partialdef testing-name inline=true %}TEST{% endpartialdef %}" ), "uppercase": "{% partialdef testing-name INLINE %}TEST{% endpartialdef %}", } ) def test_partialdef_invalid_inline(self): error_msg = "The 'inline' argument does not have any parameters" for template_name in ("with_params", "uppercase"): with ( self.subTest(template_name=template_name), self.assertRaisesMessage(TemplateSyntaxError, error_msg), ): self.engine.render_to_string(template_name) @setup( { "partial_broken_unclosed": ( "<div>Before partial</div>" "{% partialdef unclosed_partial %}" "<p>This partial has no closing tag</p>" "<div>After partial content</div>" ) } ) def test_broken_partial_unclosed_exception_info(self): with self.assertRaises(TemplateSyntaxError) as cm: self.engine.get_template("partial_broken_unclosed") self.assertIn("endpartialdef", str(cm.exception)) self.assertIn("Unclosed tag", str(cm.exception)) reporter = ExceptionReporter(None, cm.exception.__class__, cm.exception, None) traceback_data = reporter.get_traceback_data() exception_value = str(traceback_data.get("exception_value", "")) self.assertIn("Unclosed tag", exception_value) @setup( { "partial_with_variable_error": ( "<h1>Title</h1>\n" "{% partialdef testing-name %}\n" "<p>{{ nonexistent|default:alsonotthere }}</p>\n" "{% endpartialdef %}\n" "<h2>Sub Title</h2>\n" "{% partial testing-name %}\n" ), } ) def test_partial_runtime_exception_has_debug_info(self): template = self.engine.get_template("partial_with_variable_error") context = Context({}) if hasattr(self.engine, "string_if_invalid") and self.engine.string_if_invalid: output = template.render(context) # The variable should be replaced with INVALID self.assertIn("INVALID", output) else: with self.assertRaises(VariableDoesNotExist) as cm: template.render(context) if self.engine.debug: exc_info = cm.exception.template_debug self.assertEqual( exc_info["during"], "{{ nonexistent|default:alsonotthere }}" ) self.assertEqual(exc_info["line"], 3) self.assertEqual(exc_info["name"], "partial_with_variable_error") self.assertIn("Failed lookup", exc_info["message"]) @setup( { "partial_exception_info_test": ( "<h1>Title</h1>\n" "{% partialdef testing-name %}\n" "<p>Content</p>\n" "{% endpartialdef %}\n" ), } ) def test_partial_template_get_exception_info_delegation(self): if self.engine.debug: template = self.engine.get_template("partial_exception_info_test") partial_template = template.extra_data["partials"]["testing-name"] test_exc = Exception("Test exception") token = Token( token_type=TokenType.VAR, contents="test", position=(0, 4), ) exc_info = partial_template.get_exception_info(test_exc, token) self.assertIn("message", exc_info) self.assertIn("line", exc_info) self.assertIn("name", exc_info) self.assertEqual(exc_info["name"], "partial_exception_info_test") self.assertEqual(exc_info["message"], "Test exception") @setup( { "partial_with_undefined_reference": ( "<h1>Header</h1>\n" "{% partial undefined %}\n" "<p>After undefined partial</p>\n" ), } ) def test_undefined_partial_exception_info(self): template = self.engine.get_template("partial_with_undefined_reference") with self.assertRaises(TemplateSyntaxError) as cm: template.render(Context()) self.assertIn("undefined", str(cm.exception)) self.assertIn("is not defined", str(cm.exception)) if self.engine.debug: exc_debug = cm.exception.template_debug self.assertEqual(exc_debug["during"], "{% partial undefined %}") self.assertEqual(exc_debug["line"], 2) self.assertEqual(exc_debug["name"], "partial_with_undefined_reference") self.assertIn("undefined", exc_debug["message"]) @setup( { "existing_template": ( "<h1>Header</h1><p>This template has no partials defined</p>" ), } ) def test_undefined_partial_exception_info_template_does_not_exist(self): with self.assertRaises(TemplateDoesNotExist) as cm: self.engine.get_template("existing_template#undefined") self.assertIn("undefined", str(cm.exception)) @setup( { "partial_with_syntax_error": ( "<h1>Title</h1>\n" "{% partialdef syntax_error_partial %}\n" " {% if user %}\n" " <p>User: {{ user.name }}</p>\n" " {% endif\n" " <p>Missing closing tag above</p>\n" "{% endpartialdef %}\n" "{% partial syntax_error_partial %}\n" ), } ) def test_partial_with_syntax_error_exception_info(self): with self.assertRaises(TemplateSyntaxError) as cm: self.engine.get_template("partial_with_syntax_error") self.assertIn("endif", str(cm.exception).lower()) if self.engine.debug: exc_debug = cm.exception.template_debug self.assertIn("endpartialdef", exc_debug["during"]) self.assertEqual(exc_debug["name"], "partial_with_syntax_error") self.assertIn("endif", exc_debug["message"].lower()) @setup( { "partial_with_runtime_error": ( "<h1>Title</h1>\n" "{% load bad_tag %}\n" "{% partialdef runtime_error_partial %}\n" " <p>This will raise an error:</p>\n" " {% badsimpletag %}\n" "{% endpartialdef %}\n" "{% partial runtime_error_partial %}\n" ), } ) def test_partial_runtime_error_exception_info(self): template = self.engine.get_template("partial_with_runtime_error") context = Context() with self.assertRaises(RuntimeError) as cm: template.render(context) if self.engine.debug: exc_debug = cm.exception.template_debug self.assertIn("badsimpletag", exc_debug["during"]) self.assertEqual(exc_debug["line"], 5) # Line 5 is where badsimpletag is self.assertEqual(exc_debug["name"], "partial_with_runtime_error") self.assertIn("bad simpletag", exc_debug["message"]) @setup( { "nested_partial_with_undefined_var": ( "<h1>Title</h1>\n" "{% partialdef outer_partial %}\n" ' <div class="outer">\n' " {% partialdef inner_partial %}\n" " <p>{{ undefined_var }}</p>\n" " {% endpartialdef %}\n" " {% partial inner_partial %}\n" " </div>\n" "{% endpartialdef %}\n" "{% partial outer_partial %}\n" ), } ) def test_nested_partial_error_exception_info(self): template = self.engine.get_template("nested_partial_with_undefined_var") context = Context() output = template.render(context) # When string_if_invalid is set, it will show INVALID # When not set, undefined variables just render as empty string if hasattr(self.engine, "string_if_invalid") and self.engine.string_if_invalid: self.assertIn("INVALID", output) else: self.assertIn("<p>", output) self.assertIn("</p>", output) @setup( { "parent.html": ( "<!DOCTYPE html>\n" "<html>\n" "<head>{% block title %}Default Title{% endblock %}</head>\n" "<body>\n" " {% block content %}{% endblock %}\n" "</body>\n" "</html>\n" ), "child.html": ( "{% extends 'parent.html' %}\n" "{% block content %}\n" " {% partialdef content_partial %}\n" " <p>{{ missing_variable|undefined_filter }}</p>\n" " {% endpartialdef %}\n" " {% partial content_partial %}\n" "{% endblock %}\n" ), } ) def test_partial_in_extended_template_error(self): with self.assertRaises(TemplateSyntaxError) as cm: self.engine.get_template("child.html") self.assertIn("undefined_filter", str(cm.exception)) if self.engine.debug: exc_debug = cm.exception.template_debug self.assertIn("undefined_filter", exc_debug["during"]) self.assertEqual(exc_debug["name"], "child.html") self.assertIn("undefined_filter", exc_debug["message"]) @setup( { "partial_broken_nesting": ( "<div>Before partial</div>\n" "{% partialdef outer %}\n" "{% partialdef inner %}...{% endpartialdef outer %}\n" "{% endpartialdef inner %}\n" "<div>After partial content</div>" ) } ) def test_broken_partial_nesting(self): with self.assertRaises(TemplateSyntaxError) as cm: self.engine.get_template("partial_broken_nesting") self.assertIn("endpartialdef", str(cm.exception)) self.assertIn("Invalid block tag", str(cm.exception)) self.assertIn("'endpartialdef inner'", str(cm.exception)) reporter = ExceptionReporter(None, cm.exception.__class__, cm.exception, None) traceback_data = reporter.get_traceback_data() exception_value = str(traceback_data.get("exception_value", "")) self.assertIn("Invalid block tag", exception_value) self.assertIn("'endpartialdef inner'", str(cm.exception)) @setup( { "partial_broken_nesting_mixed": ( "<div>Before partial</div>\n" "{% partialdef outer %}\n" "{% partialdef inner %}...{% endpartialdef %}\n" "{% endpartialdef inner %}\n" "<div>After partial content</div>" ) } ) def test_broken_partial_nesting_mixed(self): with self.assertRaises(TemplateSyntaxError) as cm: self.engine.get_template("partial_broken_nesting_mixed") self.assertIn("endpartialdef", str(cm.exception)) self.assertIn("Invalid block tag", str(cm.exception)) self.assertIn("'endpartialdef outer'", str(cm.exception)) reporter = ExceptionReporter(None, cm.exception.__class__, cm.exception, None) traceback_data = reporter.get_traceback_data() exception_value = str(traceback_data.get("exception_value", "")) self.assertIn("Invalid block tag", exception_value) self.assertIn("'endpartialdef outer'", str(cm.exception))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/test_debug.py
tests/template_tests/syntax_tests/test_debug.py
from django.contrib.auth.models import Group from django.test import SimpleTestCase, override_settings from ..utils import setup @override_settings(DEBUG=True) class DebugTests(SimpleTestCase): @override_settings(DEBUG=False) @setup({"non_debug": "{% debug %}"}) def test_non_debug(self): output = self.engine.render_to_string("non_debug", {}) self.assertEqual(output, "") @setup({"modules": "{% debug %}"}) def test_modules(self): output = self.engine.render_to_string("modules", {}) self.assertIn( "&#x27;django&#x27;: &lt;module &#x27;django&#x27; ", output, ) @setup({"plain": "{% debug %}"}) def test_plain(self): output = self.engine.render_to_string("plain", {"a": 1}) self.assertTrue( output.startswith( "{&#x27;a&#x27;: 1}" "{&#x27;False&#x27;: False, &#x27;None&#x27;: None, " "&#x27;True&#x27;: True}\n\n{" ) ) @setup({"non_ascii": "{% debug %}"}) def test_non_ascii(self): group = Group(name="清風") output = self.engine.render_to_string("non_ascii", {"group": group}) self.assertTrue(output.startswith("{&#x27;group&#x27;: &lt;Group: 清風&gt;}")) @setup({"script": "{% debug %}"}) def test_script(self): output = self.engine.render_to_string("script", {"frag": "<script>"}) self.assertTrue( output.startswith("{&#x27;frag&#x27;: &#x27;&lt;script&gt;&#x27;}") )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/test_exceptions.py
tests/template_tests/syntax_tests/test_exceptions.py
from django.template import Template, TemplateDoesNotExist, TemplateSyntaxError from django.test import SimpleTestCase from ..utils import setup from .test_extends import inheritance_templates class ExceptionsTests(SimpleTestCase): @setup({"exception01": "{% extends 'nonexistent' %}"}) def test_exception01(self): """ Raise exception for invalid template name """ with self.assertRaises(TemplateDoesNotExist): self.engine.render_to_string("exception01") @setup({"exception02": "{% extends nonexistent %}"}) def test_exception02(self): """ Raise exception for invalid variable template name """ if self.engine.string_if_invalid: with self.assertRaises(TemplateDoesNotExist): self.engine.render_to_string("exception02") else: with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string("exception02") @setup( { "exception03": "{% extends 'inheritance01' %}" "{% block first %}2{% endblock %}{% extends 'inheritance16' %}" }, inheritance_templates, ) def test_exception03(self): """ Raise exception for extra {% extends %} tags """ with self.assertRaises(TemplateSyntaxError): self.engine.get_template("exception03") @setup( { "exception04": ( "{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678" "{% endblock %}" ) }, inheritance_templates, ) def test_exception04(self): """ Raise exception for custom tags used in child with {% load %} tag in parent, not in child """ with self.assertRaises(TemplateSyntaxError): self.engine.get_template("exception04") @setup({"exception05": "{% block first %}{{ block.super }}{% endblock %}"}) def test_exception05(self): """ Raise exception for block.super used in base template """ with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string("exception05") def test_unknown_origin_relative_path(self): files = ["./nonexistent.html", "../nonexistent.html"] for template_name in files: with self.subTest(template_name=template_name): msg = ( f"The relative path '{template_name}' cannot be evaluated due to " "an unknown template origin." ) with self.assertRaisesMessage(TemplateSyntaxError, msg): Template(f"{{% extends '{template_name}' %}}")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/test_resetcycle.py
tests/template_tests/syntax_tests/test_resetcycle.py
from django.template import TemplateSyntaxError from django.test import SimpleTestCase from ..utils import setup class ResetCycleTagTests(SimpleTestCase): @setup({"resetcycle01": "{% resetcycle %}"}) def test_resetcycle01(self): with self.assertRaisesMessage(TemplateSyntaxError, "No cycles in template."): self.engine.get_template("resetcycle01") @setup({"resetcycle02": "{% resetcycle undefinedcycle %}"}) def test_resetcycle02(self): with self.assertRaisesMessage( TemplateSyntaxError, "Named cycle 'undefinedcycle' does not exist." ): self.engine.get_template("resetcycle02") @setup({"resetcycle03": "{% cycle 'a' 'b' %}{% resetcycle undefinedcycle %}"}) def test_resetcycle03(self): with self.assertRaisesMessage( TemplateSyntaxError, "Named cycle 'undefinedcycle' does not exist." ): self.engine.get_template("resetcycle03") @setup({"resetcycle04": "{% cycle 'a' 'b' as ab %}{% resetcycle undefinedcycle %}"}) def test_resetcycle04(self): with self.assertRaisesMessage( TemplateSyntaxError, "Named cycle 'undefinedcycle' does not exist." ): self.engine.get_template("resetcycle04") @setup( { "resetcycle05": ( "{% for i in test %}{% cycle 'a' 'b' %}{% resetcycle %}{% endfor %}" ) } ) def test_resetcycle05(self): output = self.engine.render_to_string("resetcycle05", {"test": list(range(5))}) self.assertEqual(output, "aaaaa") @setup( { "resetcycle06": "{% cycle 'a' 'b' 'c' as abc %}" "{% for i in test %}" "{% cycle abc %}" "{% cycle '-' '+' %}" "{% resetcycle %}" "{% endfor %}" } ) def test_resetcycle06(self): output = self.engine.render_to_string("resetcycle06", {"test": list(range(5))}) self.assertEqual(output, "ab-c-a-b-c-") @setup( { "resetcycle07": "{% cycle 'a' 'b' 'c' as abc %}" "{% for i in test %}" "{% resetcycle abc %}" "{% cycle abc %}" "{% cycle '-' '+' %}" "{% endfor %}" } ) def test_resetcycle07(self): output = self.engine.render_to_string("resetcycle07", {"test": list(range(5))}) self.assertEqual(output, "aa-a+a-a+a-") @setup( { "resetcycle08": "{% for i in outer %}" "{% for j in inner %}" "{% cycle 'a' 'b' %}" "{% endfor %}" "{% resetcycle %}" "{% endfor %}" } ) def test_resetcycle08(self): output = self.engine.render_to_string( "resetcycle08", {"outer": list(range(2)), "inner": list(range(3))} ) self.assertEqual(output, "abaaba") @setup( { "resetcycle09": "{% for i in outer %}" "{% cycle 'a' 'b' %}" "{% for j in inner %}" "{% cycle 'X' 'Y' %}" "{% endfor %}" "{% resetcycle %}" "{% endfor %}" } ) def test_resetcycle09(self): output = self.engine.render_to_string( "resetcycle09", {"outer": list(range(2)), "inner": list(range(3))} ) self.assertEqual(output, "aXYXbXYX") @setup( { "resetcycle10": "{% for i in test %}" "{% cycle 'X' 'Y' 'Z' as XYZ %}" "{% cycle 'a' 'b' 'c' as abc %}" "{% if i == 1 %}" "{% resetcycle abc %}" "{% endif %}" "{% endfor %}" } ) def test_resetcycle10(self): output = self.engine.render_to_string("resetcycle10", {"test": list(range(5))}) self.assertEqual(output, "XaYbZaXbYc") @setup( { "resetcycle11": "{% for i in test %}" "{% cycle 'X' 'Y' 'Z' as XYZ %}" "{% cycle 'a' 'b' 'c' as abc %}" "{% if i == 1 %}" "{% resetcycle XYZ %}" "{% endif %}" "{% endfor %}" } ) def test_resetcycle11(self): output = self.engine.render_to_string("resetcycle11", {"test": list(range(5))}) self.assertEqual(output, "XaYbXcYaZb")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/test_spaceless.py
tests/template_tests/syntax_tests/test_spaceless.py
from django.test import SimpleTestCase from ..utils import setup class SpacelessTagTests(SimpleTestCase): @setup( { "spaceless01": ( "{% spaceless %} <b> <i> text </i> </b> {% endspaceless %}" ) } ) def test_spaceless01(self): output = self.engine.render_to_string("spaceless01") self.assertEqual(output, "<b><i> text </i></b>") @setup( { "spaceless02": ( "{% spaceless %} <b> \n <i> text </i> \n </b> {% endspaceless %}" ) } ) def test_spaceless02(self): output = self.engine.render_to_string("spaceless02") self.assertEqual(output, "<b><i> text </i></b>") @setup({"spaceless03": "{% spaceless %}<b><i>text</i></b>{% endspaceless %}"}) def test_spaceless03(self): output = self.engine.render_to_string("spaceless03") self.assertEqual(output, "<b><i>text</i></b>") @setup( { "spaceless04": ( "{% spaceless %}<b> <i>{{ text }}</i> </b>{% endspaceless %}" ) } ) def test_spaceless04(self): output = self.engine.render_to_string("spaceless04", {"text": "This & that"}) self.assertEqual(output, "<b><i>This &amp; that</i></b>") @setup( { "spaceless05": "{% autoescape off %}{% spaceless %}" "<b> <i>{{ text }}</i> </b>{% endspaceless %}" "{% endautoescape %}" } ) def test_spaceless05(self): output = self.engine.render_to_string("spaceless05", {"text": "This & that"}) self.assertEqual(output, "<b><i>This & that</i></b>") @setup( { "spaceless06": ( "{% spaceless %}<b> <i>{{ text|safe }}</i> </b>{% endspaceless %}" ) } ) def test_spaceless06(self): output = self.engine.render_to_string("spaceless06", {"text": "This & that"}) self.assertEqual(output, "<b><i>This & that</i></b>")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/test_with.py
tests/template_tests/syntax_tests/test_with.py
from django.template import TemplateSyntaxError from django.template.defaulttags import WithNode from django.test import SimpleTestCase from ..utils import setup class WithTagTests(SimpleTestCase): at_least_with_one_msg = "'with' expected at least one variable assignment" @setup({"with01": "{% with key=dict.key %}{{ key }}{% endwith %}"}) def test_with01(self): output = self.engine.render_to_string("with01", {"dict": {"key": 50}}) self.assertEqual(output, "50") @setup({"legacywith01": "{% with dict.key as key %}{{ key }}{% endwith %}"}) def test_legacywith01(self): output = self.engine.render_to_string("legacywith01", {"dict": {"key": 50}}) self.assertEqual(output, "50") @setup( { "with02": "{{ key }}{% with key=dict.key %}" "{{ key }}-{{ dict.key }}-{{ key }}" "{% endwith %}{{ key }}" } ) def test_with02(self): output = self.engine.render_to_string("with02", {"dict": {"key": 50}}) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID50-50-50INVALID") else: self.assertEqual(output, "50-50-50") @setup( { "legacywith02": "{{ key }}{% with dict.key as key %}" "{{ key }}-{{ dict.key }}-{{ key }}" "{% endwith %}{{ key }}" } ) def test_legacywith02(self): output = self.engine.render_to_string("legacywith02", {"dict": {"key": 50}}) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID50-50-50INVALID") else: self.assertEqual(output, "50-50-50") @setup({"with03": "{% with a=alpha b=beta %}{{ a }}{{ b }}{% endwith %}"}) def test_with03(self): output = self.engine.render_to_string("with03", {"alpha": "A", "beta": "B"}) self.assertEqual(output, "AB") @setup({"with-error01": "{% with dict.key xx key %}{{ key }}{% endwith %}"}) def test_with_error01(self): with self.assertRaisesMessage(TemplateSyntaxError, self.at_least_with_one_msg): self.engine.render_to_string("with-error01", {"dict": {"key": 50}}) @setup({"with-error02": "{% with dict.key as %}{{ key }}{% endwith %}"}) def test_with_error02(self): with self.assertRaisesMessage(TemplateSyntaxError, self.at_least_with_one_msg): self.engine.render_to_string("with-error02", {"dict": {"key": 50}}) class WithNodeTests(SimpleTestCase): def test_repr(self): node = WithNode(nodelist=[], name="a", var="dict.key") self.assertEqual(repr(node), "<WithNode>")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/test_basic.py
tests/template_tests/syntax_tests/test_basic.py
from django.template.base import Origin, Template, TemplateSyntaxError from django.template.context import Context from django.template.loader_tags import BlockContext, BlockNode from django.test import SimpleTestCase from django.views.debug import ExceptionReporter from ..utils import SilentAttrClass, SilentGetItemClass, SomeClass, setup basic_templates = { "basic-syntax01": "something cool", "basic-syntax02": "{{ headline }}", "basic-syntax03": "{{ first }} --- {{ second }}", } class BasicSyntaxTests(SimpleTestCase): @setup(basic_templates) def test_basic_syntax01(self): """ Plain text should go through the template parser untouched. """ output = self.engine.render_to_string("basic-syntax01") self.assertEqual(output, "something cool") @setup(basic_templates) def test_basic_syntax02(self): """ Variables should be replaced with their value in the current context """ output = self.engine.render_to_string("basic-syntax02", {"headline": "Success"}) self.assertEqual(output, "Success") @setup(basic_templates) def test_basic_syntax03(self): """ More than one replacement variable is allowed in a template """ output = self.engine.render_to_string( "basic-syntax03", {"first": 1, "second": 2} ) self.assertEqual(output, "1 --- 2") @setup({"basic-syntax04": "as{{ missing }}df"}) def test_basic_syntax04(self): """ Fail silently when a variable is not found in the current context """ output = self.engine.render_to_string("basic-syntax04") if self.engine.string_if_invalid: self.assertEqual(output, "asINVALIDdf") else: self.assertEqual(output, "asdf") @setup({"basic-syntax06": "{{ multi word variable }}"}) def test_basic_syntax06(self): """ A variable may not contain more than one word """ with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax06") @setup({"basic-syntax07": "{{ }}"}) def test_basic_syntax07(self): """ Raise TemplateSyntaxError for empty variable tags. """ with self.assertRaisesMessage( TemplateSyntaxError, "Empty variable tag on line 1" ): self.engine.get_template("basic-syntax07") @setup({"basic-syntax08": "{{ }}"}) def test_basic_syntax08(self): """ Raise TemplateSyntaxError for empty variable tags. """ with self.assertRaisesMessage( TemplateSyntaxError, "Empty variable tag on line 1" ): self.engine.get_template("basic-syntax08") @setup({"basic-syntax09": "{{ var.method }}"}) def test_basic_syntax09(self): """ Attribute syntax allows a template to call an object's attribute """ output = self.engine.render_to_string("basic-syntax09", {"var": SomeClass()}) self.assertEqual(output, "SomeClass.method") @setup({"basic-syntax10": "{{ var.otherclass.method }}"}) def test_basic_syntax10(self): """ Multiple levels of attribute access are allowed. """ output = self.engine.render_to_string("basic-syntax10", {"var": SomeClass()}) self.assertEqual(output, "OtherClass.method") @setup({"basic-syntax11": "{{ var.blech }}"}) def test_basic_syntax11(self): """ Fail silently when a variable's attribute isn't found. """ output = self.engine.render_to_string("basic-syntax11", {"var": SomeClass()}) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") @setup({"basic-syntax12": "{{ var.__dict__ }}"}) def test_basic_syntax12(self): """ Raise TemplateSyntaxError when trying to access a variable beginning with an underscore. """ with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax12") # Raise TemplateSyntaxError when trying to access a variable # containing an illegal character. @setup({"basic-syntax13": "{{ va>r }}"}) def test_basic_syntax13(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax13") @setup({"basic-syntax14": "{{ (var.r) }}"}) def test_basic_syntax14(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax14") @setup({"basic-syntax15": "{{ sp%am }}"}) def test_basic_syntax15(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax15") @setup({"basic-syntax16": "{{ eggs! }}"}) def test_basic_syntax16(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax16") @setup({"basic-syntax17": "{{ moo? }}"}) def test_basic_syntax17(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax17") @setup({"basic-syntax18": "{{ foo.bar }}"}) def test_basic_syntax18(self): """ Attribute syntax allows a template to call a dictionary key's value. """ output = self.engine.render_to_string("basic-syntax18", {"foo": {"bar": "baz"}}) self.assertEqual(output, "baz") @setup({"basic-syntax19": "{{ foo.spam }}"}) def test_basic_syntax19(self): """ Fail silently when a variable's dictionary key isn't found. """ output = self.engine.render_to_string("basic-syntax19", {"foo": {"bar": "baz"}}) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") @setup({"basic-syntax20": "{{ var.method2 }}"}) def test_basic_syntax20(self): """ Fail silently when accessing a non-simple method """ output = self.engine.render_to_string("basic-syntax20", {"var": SomeClass()}) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") @setup({"basic-syntax20b": "{{ var.method5 }}"}) def test_basic_syntax20b(self): """ Don't silence a TypeError if it was raised inside a callable. """ template = self.engine.get_template("basic-syntax20b") with self.assertRaises(TypeError): template.render(Context({"var": SomeClass()})) # Don't get confused when parsing something that is almost, but not # quite, a template tag. @setup({"basic-syntax21": "a {{ moo %} b"}) def test_basic_syntax21(self): output = self.engine.render_to_string("basic-syntax21") self.assertEqual(output, "a {{ moo %} b") @setup({"basic-syntax22": "{{ moo #}"}) def test_basic_syntax22(self): output = self.engine.render_to_string("basic-syntax22") self.assertEqual(output, "{{ moo #}") @setup({"basic-syntax23": "{{ moo #} {{ cow }}"}) def test_basic_syntax23(self): """ Treat "moo #} {{ cow" as the variable. Not ideal, but costly to work around, so this triggers an error. """ with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax23") @setup({"basic-syntax24": "{{ moo\n }}"}) def test_basic_syntax24(self): """ Embedded newlines make it not-a-tag. """ output = self.engine.render_to_string("basic-syntax24") self.assertEqual(output, "{{ moo\n }}") # Literal strings are permitted inside variables, mostly for i18n # purposes. @setup({"basic-syntax25": '{{ "fred" }}'}) def test_basic_syntax25(self): output = self.engine.render_to_string("basic-syntax25") self.assertEqual(output, "fred") @setup({"basic-syntax26": r'{{ "\"fred\"" }}'}) def test_basic_syntax26(self): output = self.engine.render_to_string("basic-syntax26") self.assertEqual(output, '"fred"') @setup({"basic-syntax27": r'{{ _("\"fred\"") }}'}) def test_basic_syntax27(self): output = self.engine.render_to_string("basic-syntax27") self.assertEqual(output, '"fred"') # #12554 -- Make sure a silent_variable_failure Exception is # suppressed on dictionary and attribute lookup. @setup({"basic-syntax28": "{{ a.b }}"}) def test_basic_syntax28(self): output = self.engine.render_to_string( "basic-syntax28", {"a": SilentGetItemClass()} ) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") @setup({"basic-syntax29": "{{ a.b }}"}) def test_basic_syntax29(self): output = self.engine.render_to_string( "basic-syntax29", {"a": SilentAttrClass()} ) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") # Something that starts like a number but has an extra lookup works # as a lookup. @setup({"basic-syntax30": "{{ 1.2.3 }}"}) def test_basic_syntax30(self): output = self.engine.render_to_string( "basic-syntax30", {"1": {"2": {"3": "d"}}} ) self.assertEqual(output, "d") @setup({"basic-syntax31": "{{ 1.2.3 }}"}) def test_basic_syntax31(self): output = self.engine.render_to_string( "basic-syntax31", {"1": {"2": ("a", "b", "c", "d")}}, ) self.assertEqual(output, "d") @setup({"basic-syntax32": "{{ 1.2.3 }}"}) def test_basic_syntax32(self): output = self.engine.render_to_string( "basic-syntax32", {"1": (("x", "x", "x", "x"), ("y", "y", "y", "y"), ("a", "b", "c", "d"))}, ) self.assertEqual(output, "d") @setup({"basic-syntax33": "{{ 1.2.3 }}"}) def test_basic_syntax33(self): output = self.engine.render_to_string( "basic-syntax33", {"1": ("xxxx", "yyyy", "abcd")}, ) self.assertEqual(output, "d") @setup({"basic-syntax34": "{{ 1.2.3 }}"}) def test_basic_syntax34(self): output = self.engine.render_to_string( "basic-syntax34", {"1": ({"x": "x"}, {"y": "y"}, {"z": "z", "3": "d"})} ) self.assertEqual(output, "d") # Numbers are numbers even if their digits are in the context. @setup({"basic-syntax35": "{{ 1 }}"}) def test_basic_syntax35(self): output = self.engine.render_to_string("basic-syntax35", {"1": "abc"}) self.assertEqual(output, "1") @setup({"basic-syntax36": "{{ 1.2 }}"}) def test_basic_syntax36(self): output = self.engine.render_to_string("basic-syntax36", {"1": "abc"}) self.assertEqual(output, "1.2") @setup({"basic-syntax37": "{{ callable }}"}) def test_basic_syntax37(self): """ Call methods in the top level of the context. """ output = self.engine.render_to_string( "basic-syntax37", {"callable": lambda: "foo bar"} ) self.assertEqual(output, "foo bar") @setup({"basic-syntax38": "{{ var.callable }}"}) def test_basic_syntax38(self): """ Call methods returned from dictionary lookups. """ output = self.engine.render_to_string( "basic-syntax38", {"var": {"callable": lambda: "foo bar"}} ) self.assertEqual(output, "foo bar") @setup({"template": "{% block content %}"}) def test_unclosed_block(self): msg = "Unclosed tag on line 1: 'block'. Looking for one of: endblock." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup({"template": "{% if a %}"}) def test_unclosed_block2(self): msg = "Unclosed tag on line 1: 'if'. Looking for one of: elif, else, endif." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup({"tpl-str": "%s", "tpl-percent": "%%", "tpl-weird-percent": "% %s"}) def test_ignores_strings_that_look_like_format_interpolation(self): output = self.engine.render_to_string("tpl-str") self.assertEqual(output, "%s") output = self.engine.render_to_string("tpl-percent") self.assertEqual(output, "%%") output = self.engine.render_to_string("tpl-weird-percent") self.assertEqual(output, "% %s") @setup( {"template": "{{ class_var.class_property }} | {{ class_var.class_method }}"} ) def test_subscriptable_class(self): class MyClass(list): # As of Python 3.9 list defines __class_getitem__ which makes it # subscriptable. class_property = "Example property" do_not_call_in_templates = True @classmethod def class_method(cls): return "Example method" for case in (MyClass, lambda: MyClass): with self.subTest(case=case): output = self.engine.render_to_string("template", {"class_var": case}) self.assertEqual(output, "Example property | Example method") @setup({"template": "{{ meals.lunch }}"}) def test_access_class_property_if_getitem_is_defined_in_metaclass(self): """ If the metaclass defines __getitem__, the template system should use it to resolve the dot notation. """ class MealMeta(type): def __getitem__(cls, name): return getattr(cls, name) + " is yummy." class Meals(metaclass=MealMeta): lunch = "soup" do_not_call_in_templates = True # Make class type subscriptable. def __class_getitem__(cls, key): from types import GenericAlias return GenericAlias(cls, key) self.assertEqual(Meals.lunch, "soup") self.assertEqual(Meals["lunch"], "soup is yummy.") output = self.engine.render_to_string("template", {"meals": Meals}) self.assertEqual(output, "soup is yummy.") class BlockContextTests(SimpleTestCase): def test_repr(self): block_context = BlockContext() block_context.add_blocks({"content": BlockNode("content", [])}) self.assertEqual( repr(block_context), "<BlockContext: blocks=defaultdict(<class 'list'>, " "{'content': [<Block Node: content. Contents: []>]})>", ) class TemplateNameInExceptionTests(SimpleTestCase): template_error_msg = ( "Invalid block tag on line 1: 'endfor'. Did you forget to register or " "load this tag?" ) def test_template_name_in_error_message(self): msg = f"Template: test.html, {self.template_error_msg}" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template("{% endfor %}", origin=Origin("test.html")) def test_template_name_not_in_debug_view(self): try: Template("{% endfor %}", origin=Origin("test.html")) except TemplateSyntaxError as e: reporter = ExceptionReporter(None, e.__class__, e, None) traceback_data = reporter.get_traceback_data() self.assertEqual(traceback_data["exception_value"], self.template_error_msg) def test_unknown_source_template(self): try: Template("{% endfor %}") except TemplateSyntaxError as e: self.assertEqual(str(e), self.template_error_msg)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/test_simple_tag.py
tests/template_tests/syntax_tests/test_simple_tag.py
from django.template import TemplateSyntaxError from django.test import SimpleTestCase from ..utils import setup class SimpleTagTests(SimpleTestCase): libraries = {"custom": "template_tests.templatetags.custom"} @setup({"simpletag-renamed01": "{% load custom %}{% minusone 7 %}"}) def test_simpletag_renamed01(self): output = self.engine.render_to_string("simpletag-renamed01") self.assertEqual(output, "6") @setup({"simpletag-renamed02": "{% load custom %}{% minustwo 7 %}"}) def test_simpletag_renamed02(self): output = self.engine.render_to_string("simpletag-renamed02") self.assertEqual(output, "5") @setup({"simpletag-renamed03": "{% load custom %}{% minustwo_overridden_name 7 %}"}) def test_simpletag_renamed03(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("simpletag-renamed03")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/test_template_tag.py
tests/template_tests/syntax_tests/test_template_tag.py
from django.template import TemplateSyntaxError from django.test import SimpleTestCase from ..utils import setup class TemplateTagTests(SimpleTestCase): @setup({"templatetag01": "{% templatetag openblock %}"}) def test_templatetag01(self): output = self.engine.render_to_string("templatetag01") self.assertEqual(output, "{%") @setup({"templatetag02": "{% templatetag closeblock %}"}) def test_templatetag02(self): output = self.engine.render_to_string("templatetag02") self.assertEqual(output, "%}") @setup({"templatetag03": "{% templatetag openvariable %}"}) def test_templatetag03(self): output = self.engine.render_to_string("templatetag03") self.assertEqual(output, "{{") @setup({"templatetag04": "{% templatetag closevariable %}"}) def test_templatetag04(self): output = self.engine.render_to_string("templatetag04") self.assertEqual(output, "}}") @setup({"templatetag05": "{% templatetag %}"}) def test_templatetag05(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("templatetag05") @setup({"templatetag06": "{% templatetag foo %}"}) def test_templatetag06(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("templatetag06") @setup({"templatetag07": "{% templatetag openbrace %}"}) def test_templatetag07(self): output = self.engine.render_to_string("templatetag07") self.assertEqual(output, "{") @setup({"templatetag08": "{% templatetag closebrace %}"}) def test_templatetag08(self): output = self.engine.render_to_string("templatetag08") self.assertEqual(output, "}") @setup({"templatetag09": "{% templatetag openbrace %}{% templatetag openbrace %}"}) def test_templatetag09(self): output = self.engine.render_to_string("templatetag09") self.assertEqual(output, "{{") @setup( {"templatetag10": "{% templatetag closebrace %}{% templatetag closebrace %}"} ) def test_templatetag10(self): output = self.engine.render_to_string("templatetag10") self.assertEqual(output, "}}") @setup({"templatetag11": "{% templatetag opencomment %}"}) def test_templatetag11(self): output = self.engine.render_to_string("templatetag11") self.assertEqual(output, "{#") @setup({"templatetag12": "{% templatetag closecomment %}"}) def test_templatetag12(self): output = self.engine.render_to_string("templatetag12") self.assertEqual(output, "#}")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py
tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py
from django.template import Context, Template from django.test import SimpleTestCase from django.utils import translation from ...utils import setup from .base import MultipleLocaleActivationTestCase class MultipleLocaleActivationTests(MultipleLocaleActivationTestCase): def test_single_locale_activation(self): """ Simple baseline behavior with one locale for all the supported i18n constructs. """ with translation.override("fr"): self.assertEqual(Template("{{ _('Yes') }}").render(Context({})), "Oui") # Literal marked up with _() in a filter expression def test_multiple_locale_filter(self): with translation.override("de"): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") with translation.override(self._old_language), translation.override("nl"): self.assertEqual(t.render(Context({})), "nee") def test_multiple_locale_filter_deactivate(self): with translation.override("de", deactivate=True): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "nee") def test_multiple_locale_filter_direct_switch(self): with translation.override("de"): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "nee") # Literal marked up with _() def test_multiple_locale(self): with translation.override("de"): t = Template("{{ _('No') }}") with translation.override(self._old_language), translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_deactivate(self): with translation.override("de", deactivate=True): t = Template("{{ _('No') }}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_direct_switch(self): with translation.override("de"): t = Template("{{ _('No') }}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") # Literal marked up with _(), loading the i18n template tag library def test_multiple_locale_loadi18n(self): with translation.override("de"): t = Template("{% load i18n %}{{ _('No') }}") with translation.override(self._old_language), translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_loadi18n_deactivate(self): with translation.override("de", deactivate=True): t = Template("{% load i18n %}{{ _('No') }}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_loadi18n_direct_switch(self): with translation.override("de"): t = Template("{% load i18n %}{{ _('No') }}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") class I18nStringLiteralTests(SimpleTestCase): """translation of constant strings""" libraries = {"i18n": "django.templatetags.i18n"} @setup({"i18n13": '{{ _("Password") }}'}) def test_i18n13(self): with translation.override("de"): output = self.engine.render_to_string("i18n13") self.assertEqual(output, "Passwort") @setup( { "i18n14": ( '{% cycle "foo" _("Password") _(\'Password\') as c %} {% cycle c %} ' "{% cycle c %}" ) } ) def test_i18n14(self): with translation.override("de"): output = self.engine.render_to_string("i18n14") self.assertEqual(output, "foo Passwort Passwort") @setup({"i18n15": '{{ absent|default:_("Password") }}'}) def test_i18n15(self): with translation.override("de"): output = self.engine.render_to_string("i18n15", {"absent": ""}) self.assertEqual(output, "Passwort") @setup({"i18n16": '{{ _("<") }}'}) def test_i18n16(self): with translation.override("de"): output = self.engine.render_to_string("i18n16") self.assertEqual(output, "<")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/i18n/test_get_available_languages.py
tests/template_tests/syntax_tests/i18n/test_get_available_languages.py
from django.template import TemplateSyntaxError from django.test import SimpleTestCase from ...utils import setup class GetAvailableLanguagesTagTests(SimpleTestCase): libraries = {"i18n": "django.templatetags.i18n"} @setup( { "i18n12": "{% load i18n %}" "{% get_available_languages as langs %}{% for lang in langs %}" '{% if lang.0 == "de" %}{{ lang.0 }}{% endif %}{% endfor %}' } ) def test_i18n12(self): output = self.engine.render_to_string("i18n12") self.assertEqual(output, "de") @setup({"syntax_i18n": "{% load i18n %}{% get_available_languages a langs %}"}) def test_no_as_var(self): msg = ( "'get_available_languages' requires 'as variable' (got " "['get_available_languages', 'a', 'langs'])" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("syntax_i18n")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/i18n/test_translate.py
tests/template_tests/syntax_tests/i18n/test_translate.py
import inspect from functools import partial, wraps from asgiref.local import Local from django.template import Context, Template, TemplateSyntaxError from django.templatetags.l10n import LocalizeNode from django.test import SimpleTestCase, override_settings from django.utils import translation from django.utils.safestring import mark_safe from django.utils.translation import trans_real from ...utils import setup as base_setup from .base import MultipleLocaleActivationTestCase, extended_locale_paths def setup(templates, *args, **kwargs): translate_setup = base_setup(templates, *args, **kwargs) trans_setup = base_setup( { name: template.replace("{% translate ", "{% trans ") for name, template in templates.items() } ) tags = { "trans": trans_setup, "translate": translate_setup, } def decorator(func): @wraps(func) def inner(self, *args): signature = inspect.signature(func) for tag_name, setup_func in tags.items(): if "tag_name" in signature.parameters: setup_func(partial(func, tag_name=tag_name))(self) else: setup_func(func)(self) return inner return decorator class I18nTransTagTests(SimpleTestCase): libraries = {"i18n": "django.templatetags.i18n"} @setup({"i18n01": "{% load i18n %}{% translate 'xxxyyyxxx' %}"}) def test_i18n01(self): """simple translation of a string delimited by '.""" output = self.engine.render_to_string("i18n01") self.assertEqual(output, "xxxyyyxxx") @setup({"i18n02": '{% load i18n %}{% translate "xxxyyyxxx" %}'}) def test_i18n02(self): """simple translation of a string delimited by ".""" output = self.engine.render_to_string("i18n02") self.assertEqual(output, "xxxyyyxxx") @setup({"i18n06": '{% load i18n %}{% translate "Page not found" %}'}) def test_i18n06(self): """simple translation of a string to German""" with translation.override("de"): output = self.engine.render_to_string("i18n06") self.assertEqual(output, "Seite nicht gefunden") @setup({"i18n09": '{% load i18n %}{% translate "Page not found" noop %}'}) def test_i18n09(self): """simple non-translation (only marking) of a string to German""" with translation.override("de"): output = self.engine.render_to_string("i18n09") self.assertEqual(output, "Page not found") @setup({"i18n20": "{% load i18n %}{% translate andrew %}"}) def test_i18n20(self): output = self.engine.render_to_string("i18n20", {"andrew": "a & b"}) self.assertEqual(output, "a &amp; b") @setup({"i18n22": "{% load i18n %}{% translate andrew %}"}) def test_i18n22(self): output = self.engine.render_to_string("i18n22", {"andrew": mark_safe("a & b")}) self.assertEqual(output, "a & b") @setup( { "i18n23": ( '{% load i18n %}{% translate "Page not found"|capfirst|slice:"6:" %}' ) } ) def test_i18n23(self): """Using filters with the {% translate %} tag (#5972).""" with translation.override("de"): output = self.engine.render_to_string("i18n23") self.assertEqual(output, "nicht gefunden") @setup({"i18n24": "{% load i18n %}{% translate 'Page not found'|upper %}"}) def test_i18n24(self): with translation.override("de"): output = self.engine.render_to_string("i18n24") self.assertEqual(output, "SEITE NICHT GEFUNDEN") @setup({"i18n25": "{% load i18n %}{% translate somevar|upper %}"}) def test_i18n25(self): with translation.override("de"): output = self.engine.render_to_string( "i18n25", {"somevar": "Page not found"} ) self.assertEqual(output, "SEITE NICHT GEFUNDEN") # trans tag with as var @setup( { "i18n35": ( '{% load i18n %}{% translate "Page not found" as page_not_found %}' "{{ page_not_found }}" ) } ) def test_i18n35(self): with translation.override("de"): output = self.engine.render_to_string("i18n35") self.assertEqual(output, "Seite nicht gefunden") @setup( { "i18n36": ( '{% load i18n %}{% translate "Page not found" noop as page_not_found %}' "{{ page_not_found }}" ) } ) def test_i18n36(self): with translation.override("de"): output = self.engine.render_to_string("i18n36") self.assertEqual(output, "Page not found") @setup({"template": "{% load i18n %}{% translate %}A}"}) def test_syntax_error_no_arguments(self, tag_name): msg = "'{}' takes at least one argument".format(tag_name) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup({"template": '{% load i18n %}{% translate "Yes" badoption %}'}) def test_syntax_error_bad_option(self, tag_name): msg = "Unknown argument for '{}' tag: 'badoption'".format(tag_name) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup({"template": '{% load i18n %}{% translate "Yes" as %}'}) def test_syntax_error_missing_assignment(self, tag_name): msg = "No argument provided to the '{}' tag for the as option.".format(tag_name) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup({"template": '{% load i18n %}{% translate "Yes" as var context %}'}) def test_syntax_error_missing_context(self, tag_name): msg = "No argument provided to the '{}' tag for the context option.".format( tag_name ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup({"template": '{% load i18n %}{% translate "Yes" context as var %}'}) def test_syntax_error_context_as(self, tag_name): msg = ( f"Invalid argument 'as' provided to the '{tag_name}' tag for the context " f"option" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup({"template": '{% load i18n %}{% translate "Yes" context noop %}'}) def test_syntax_error_context_noop(self, tag_name): msg = ( f"Invalid argument 'noop' provided to the '{tag_name}' tag for the context " f"option" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup({"template": '{% load i18n %}{% translate "Yes" noop noop %}'}) def test_syntax_error_duplicate_option(self): msg = "The 'noop' option was specified more than once." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup({"template": '{% load i18n %}{% translate "%s" %}'}) def test_trans_tag_using_a_string_that_looks_like_str_fmt(self): output = self.engine.render_to_string("template") self.assertEqual(output, "%s") class TranslationTransTagTests(SimpleTestCase): tag_name = "trans" def get_template(self, template_string): return Template( template_string.replace("{{% translate ", "{{% {}".format(self.tag_name)) ) @override_settings(LOCALE_PATHS=extended_locale_paths) def test_template_tags_pgettext(self): """{% translate %} takes message contexts into account (#14806).""" trans_real._active = Local() trans_real._translations = {} with translation.override("de"): # Nonexistent context... t = self.get_template( '{% load i18n %}{% translate "May" context "nonexistent" %}' ) rendered = t.render(Context()) self.assertEqual(rendered, "May") # Existing context... using a literal t = self.get_template( '{% load i18n %}{% translate "May" context "month name" %}' ) rendered = t.render(Context()) self.assertEqual(rendered, "Mai") t = self.get_template('{% load i18n %}{% translate "May" context "verb" %}') rendered = t.render(Context()) self.assertEqual(rendered, "Kann") # Using a variable t = self.get_template( '{% load i18n %}{% translate "May" context message_context %}' ) rendered = t.render(Context({"message_context": "month name"})) self.assertEqual(rendered, "Mai") t = self.get_template( '{% load i18n %}{% translate "May" context message_context %}' ) rendered = t.render(Context({"message_context": "verb"})) self.assertEqual(rendered, "Kann") # Using a filter t = self.get_template( '{% load i18n %}{% translate "May" context message_context|lower %}' ) rendered = t.render(Context({"message_context": "MONTH NAME"})) self.assertEqual(rendered, "Mai") t = self.get_template( '{% load i18n %}{% translate "May" context message_context|lower %}' ) rendered = t.render(Context({"message_context": "VERB"})) self.assertEqual(rendered, "Kann") # Using 'as' t = self.get_template( '{% load i18n %}{% translate "May" context "month name" as var %}' "Value: {{ var }}" ) rendered = t.render(Context()) self.assertEqual(rendered, "Value: Mai") t = self.get_template( '{% load i18n %}{% translate "May" as var context "verb" %}Value: ' "{{ var }}" ) rendered = t.render(Context()) self.assertEqual(rendered, "Value: Kann") class TranslationTranslateTagTests(TranslationTransTagTests): tag_name = "translate" class MultipleLocaleActivationTransTagTests(MultipleLocaleActivationTestCase): tag_name = "trans" def get_template(self, template_string): return Template( template_string.replace("{{% translate ", "{{% {}".format(self.tag_name)) ) def test_single_locale_activation(self): """ Simple baseline behavior with one locale for all the supported i18n constructs. """ with translation.override("fr"): self.assertEqual( self.get_template("{% load i18n %}{% translate 'Yes' %}").render( Context({}) ), "Oui", ) def test_multiple_locale_trans(self): with translation.override("de"): t = self.get_template("{% load i18n %}{% translate 'No' %}") with translation.override(self._old_language), translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_deactivate_trans(self): with translation.override("de", deactivate=True): t = self.get_template("{% load i18n %}{% translate 'No' %}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_direct_switch_trans(self): with translation.override("de"): t = self.get_template("{% load i18n %}{% translate 'No' %}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") class MultipleLocaleActivationTranslateTagTests(MultipleLocaleActivationTransTagTests): tag_name = "translate" class LocalizeNodeTests(SimpleTestCase): def test_repr(self): node = LocalizeNode(nodelist=[], use_l10n=True) self.assertEqual(repr(node), "<LocalizeNode>")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/i18n/test_blocktranslate.py
tests/template_tests/syntax_tests/i18n/test_blocktranslate.py
import inspect import os from functools import partial, wraps from asgiref.local import Local from django.template import Context, Template, TemplateSyntaxError from django.template.base import Token, TokenType from django.templatetags.i18n import BlockTranslateNode from django.test import SimpleTestCase, override_settings from django.utils import translation from django.utils.safestring import mark_safe from django.utils.translation import trans_real from ...utils import setup as base_setup from .base import MultipleLocaleActivationTestCase, extended_locale_paths, here def setup(templates, *args, **kwargs): blocktranslate_setup = base_setup(templates, *args, **kwargs) blocktrans_setup = base_setup( { name: template.replace("{% blocktranslate ", "{% blocktrans ").replace( "{% endblocktranslate %}", "{% endblocktrans %}" ) for name, template in templates.items() } ) tags = { "blocktrans": blocktrans_setup, "blocktranslate": blocktranslate_setup, } def decorator(func): @wraps(func) def inner(self, *args): signature = inspect.signature(func) for tag_name, setup_func in tags.items(): if "tag_name" in signature.parameters: setup_func(partial(func, tag_name=tag_name))(self) else: setup_func(func)(self) return inner return decorator class I18nBlockTransTagTests(SimpleTestCase): libraries = {"i18n": "django.templatetags.i18n"} @setup( { "i18n03": ( "{% load i18n %}{% blocktranslate %}{{ anton }}{% endblocktranslate %}" ) } ) def test_i18n03(self): """simple translation of a variable""" output = self.engine.render_to_string("i18n03", {"anton": "Å"}) self.assertEqual(output, "Å") @setup( { "i18n04": ( "{% load i18n %}{% blocktranslate with berta=anton|lower %}{{ berta }}" "{% endblocktranslate %}" ) } ) def test_i18n04(self): """simple translation of a variable and filter""" output = self.engine.render_to_string("i18n04", {"anton": "Å"}) self.assertEqual(output, "å") @setup( { "legacyi18n04": ( "{% load i18n %}" "{% blocktranslate with anton|lower as berta %}{{ berta }}" "{% endblocktranslate %}" ) } ) def test_legacyi18n04(self): """simple translation of a variable and filter""" output = self.engine.render_to_string("legacyi18n04", {"anton": "Å"}) self.assertEqual(output, "å") @setup( { "i18n05": ( "{% load i18n %}{% blocktranslate %}xxx{{ anton }}xxx" "{% endblocktranslate %}" ) } ) def test_i18n05(self): """simple translation of a string with interpolation""" output = self.engine.render_to_string("i18n05", {"anton": "yyy"}) self.assertEqual(output, "xxxyyyxxx") @setup( { "i18n07": "{% load i18n %}" "{% blocktranslate count counter=number %}singular{% plural %}" "{{ counter }} plural{% endblocktranslate %}" } ) def test_i18n07(self): """translation of singular form""" output = self.engine.render_to_string("i18n07", {"number": 1}) self.assertEqual(output, "singular") @setup( { "legacyi18n07": "{% load i18n %}" "{% blocktranslate count number as counter %}singular{% plural %}" "{{ counter }} plural{% endblocktranslate %}" } ) def test_legacyi18n07(self): """translation of singular form""" output = self.engine.render_to_string("legacyi18n07", {"number": 1}) self.assertEqual(output, "singular") @setup( { "i18n08": "{% load i18n %}" "{% blocktranslate count number as counter %}singular{% plural %}" "{{ counter }} plural{% endblocktranslate %}" } ) def test_i18n08(self): """translation of plural form""" output = self.engine.render_to_string("i18n08", {"number": 2}) self.assertEqual(output, "2 plural") @setup( { "legacyi18n08": "{% load i18n %}" "{% blocktranslate count counter=number %}singular{% plural %}" "{{ counter }} plural{% endblocktranslate %}" } ) def test_legacyi18n08(self): """translation of plural form""" output = self.engine.render_to_string("legacyi18n08", {"number": 2}) self.assertEqual(output, "2 plural") @setup( { "i18n17": ( "{% load i18n %}" "{% blocktranslate with berta=anton|escape %}{{ berta }}" "{% endblocktranslate %}" ) } ) def test_i18n17(self): """ Escaping inside blocktranslate and translate works as if it was directly in the template. """ output = self.engine.render_to_string("i18n17", {"anton": "α & β"}) self.assertEqual(output, "α &amp; β") @setup( { "i18n18": ( "{% load i18n %}" "{% blocktranslate with berta=anton|force_escape %}{{ berta }}" "{% endblocktranslate %}" ) } ) def test_i18n18(self): output = self.engine.render_to_string("i18n18", {"anton": "α & β"}) self.assertEqual(output, "α &amp; β") @setup( { "i18n19": ( "{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}" ) } ) def test_i18n19(self): output = self.engine.render_to_string("i18n19", {"andrew": "a & b"}) self.assertEqual(output, "a &amp; b") @setup( { "i18n21": ( "{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}" ) } ) def test_i18n21(self): output = self.engine.render_to_string("i18n21", {"andrew": mark_safe("a & b")}) self.assertEqual(output, "a & b") @setup( { "legacyi18n17": ( "{% load i18n %}" "{% blocktranslate with anton|escape as berta %}{{ berta }}" "{% endblocktranslate %}" ) } ) def test_legacyi18n17(self): output = self.engine.render_to_string("legacyi18n17", {"anton": "α & β"}) self.assertEqual(output, "α &amp; β") @setup( { "legacyi18n18": "{% load i18n %}" "{% blocktranslate with anton|force_escape as berta %}" "{{ berta }}{% endblocktranslate %}" } ) def test_legacyi18n18(self): output = self.engine.render_to_string("legacyi18n18", {"anton": "α & β"}) self.assertEqual(output, "α &amp; β") @setup( { "i18n26": "{% load i18n %}" "{% blocktranslate with extra_field=myextra_field count counter=number %}" "singular {{ extra_field }}{% plural %}plural{% endblocktranslate %}" } ) def test_i18n26(self): """ translation of plural form with extra field in singular form (#13568) """ output = self.engine.render_to_string( "i18n26", {"myextra_field": "test", "number": 1} ) self.assertEqual(output, "singular test") @setup( { "legacyi18n26": ( "{% load i18n %}" "{% blocktranslate with myextra_field as extra_field " "count number as counter %}singular {{ extra_field }}{% plural %}plural" "{% endblocktranslate %}" ) } ) def test_legacyi18n26(self): output = self.engine.render_to_string( "legacyi18n26", {"myextra_field": "test", "number": 1} ) self.assertEqual(output, "singular test") @setup( { "i18n27": "{% load i18n %}{% blocktranslate count counter=number %}" "{{ counter }} result{% plural %}{{ counter }} results" "{% endblocktranslate %}" } ) def test_i18n27(self): """translation of singular form in Russian (#14126)""" with translation.override("ru"): output = self.engine.render_to_string("i18n27", {"number": 1}) self.assertEqual( output, "1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442" ) @setup( { "legacyi18n27": "{% load i18n %}" "{% blocktranslate count number as counter %}{{ counter }} result" "{% plural %}{{ counter }} results{% endblocktranslate %}" } ) def test_legacyi18n27(self): with translation.override("ru"): output = self.engine.render_to_string("legacyi18n27", {"number": 1}) self.assertEqual( output, "1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442" ) @setup( { "i18n28": ( "{% load i18n %}" "{% blocktranslate with a=anton b=berta %}{{ a }} + {{ b }}" "{% endblocktranslate %}" ) } ) def test_i18n28(self): """simple translation of multiple variables""" output = self.engine.render_to_string("i18n28", {"anton": "α", "berta": "β"}) self.assertEqual(output, "α + β") @setup( { "legacyi18n28": "{% load i18n %}" "{% blocktranslate with anton as a and berta as b %}" "{{ a }} + {{ b }}{% endblocktranslate %}" } ) def test_legacyi18n28(self): output = self.engine.render_to_string( "legacyi18n28", {"anton": "α", "berta": "β"} ) self.assertEqual(output, "α + β") # blocktranslate handling of variables which are not in the context. # this should work as if blocktranslate was not there (#19915) @setup( { "i18n34": ( "{% load i18n %}{% blocktranslate %}{{ missing }}" "{% endblocktranslate %}" ) } ) def test_i18n34(self): output = self.engine.render_to_string("i18n34") if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") @setup( { "i18n34_2": ( "{% load i18n %}{% blocktranslate with a='α' %}{{ missing }}" "{% endblocktranslate %}" ) } ) def test_i18n34_2(self): output = self.engine.render_to_string("i18n34_2") if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") @setup( { "i18n34_3": ( "{% load i18n %}{% blocktranslate with a=anton %}{{ missing }}" "{% endblocktranslate %}" ) } ) def test_i18n34_3(self): output = self.engine.render_to_string("i18n34_3", {"anton": "\xce\xb1"}) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") @setup( { "i18n37": "{% load i18n %}" '{% translate "Page not found" as page_not_found %}' "{% blocktranslate %}Error: {{ page_not_found }}{% endblocktranslate %}" } ) def test_i18n37(self): with translation.override("de"): output = self.engine.render_to_string("i18n37") self.assertEqual(output, "Error: Seite nicht gefunden") # blocktranslate tag with asvar @setup( { "i18n39": ( "{% load i18n %}" "{% blocktranslate asvar page_not_found %}Page not found" "{% endblocktranslate %}>{{ page_not_found }}<" ) } ) def test_i18n39(self): with translation.override("de"): output = self.engine.render_to_string("i18n39") self.assertEqual(output, ">Seite nicht gefunden<") @setup( { "i18n40": "{% load i18n %}" '{% translate "Page not found" as pg_404 %}' "{% blocktranslate with page_not_found=pg_404 asvar output %}" "Error: {{ page_not_found }}" "{% endblocktranslate %}" } ) def test_i18n40(self): output = self.engine.render_to_string("i18n40") self.assertEqual(output, "") @setup( { "i18n41": "{% load i18n %}" '{% translate "Page not found" as pg_404 %}' "{% blocktranslate with page_not_found=pg_404 asvar output %}" "Error: {{ page_not_found }}" "{% endblocktranslate %}" ">{{ output }}<" } ) def test_i18n41(self): with translation.override("de"): output = self.engine.render_to_string("i18n41") self.assertEqual(output, ">Error: Seite nicht gefunden<") @setup( { "i18n_asvar_safestring": ( "{% load i18n %}" "{% blocktranslate asvar the_title %}" "{{title}}other text" "{% endblocktranslate %}" "{{ the_title }}" ) } ) def test_i18n_asvar_safestring(self): context = {"title": "<Main Title>"} output = self.engine.render_to_string("i18n_asvar_safestring", context=context) self.assertEqual(output, "&lt;Main Title&gt;other text") @setup( { "template": ( "{% load i18n %}{% blocktranslate asvar %}Yes{% endblocktranslate %}" ) } ) def test_blocktrans_syntax_error_missing_assignment(self, tag_name): msg = "No argument provided to the '{}' tag for the asvar option.".format( tag_name ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup({"template": "{% load i18n %}{% blocktranslate %}%s{% endblocktranslate %}"}) def test_blocktrans_tag_using_a_string_that_looks_like_str_fmt(self): output = self.engine.render_to_string("template") self.assertEqual(output, "%s") @setup( { "template": ( "{% load i18n %}{% blocktranslate %}{% block b %} {% endblock %}" "{% endblocktranslate %}" ) } ) def test_with_block(self, tag_name): msg = "'{}' doesn't allow other block tags (seen 'block b') inside it".format( tag_name ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup( { "template": ( "{% load i18n %}" "{% blocktranslate %}{% for b in [1, 2, 3] %} {% endfor %}" "{% endblocktranslate %}" ) } ) def test_with_for(self, tag_name): msg = ( f"'{tag_name}' doesn't allow other block tags (seen 'for b in [1, 2, 3]') " f"inside it" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup( { "template": ( "{% load i18n %}{% blocktranslate with foo=bar with %}{{ foo }}" "{% endblocktranslate %}" ) } ) def test_variable_twice(self): with self.assertRaisesMessage( TemplateSyntaxError, "The 'with' option was specified more than once" ): self.engine.render_to_string("template", {"foo": "bar"}) @setup( {"template": "{% load i18n %}{% blocktranslate with %}{% endblocktranslate %}"} ) def test_no_args_with(self, tag_name): msg = "\"with\" in '{}' tag needs at least one keyword argument.".format( tag_name ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup( { "template": ( "{% load i18n %}{% blocktranslate count a %}{% endblocktranslate %}" ) } ) def test_count(self, tag_name): msg = "\"count\" in '{}' tag expected exactly one keyword argument.".format( tag_name ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template", {"a": [1, 2, 3]}) @setup( { "template": ( "{% load i18n %}{% blocktranslate count counter=num %}{{ counter }}" "{% plural %}{{ counter }}{% endblocktranslate %}" ) } ) def test_count_not_number(self, tag_name): msg = "'counter' argument to '{}' tag must be a number.".format(tag_name) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template", {"num": "1"}) @setup( { "template": ( "{% load i18n %}{% blocktranslate count count=var|length %}" "There is {{ count }} object. {% block a %} {% endblock %}" "{% endblocktranslate %}" ) } ) def test_plural_bad_syntax(self, tag_name): msg = "'{}' doesn't allow other block tags inside it".format(tag_name) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template", {"var": [1, 2, 3]}) class TranslationBlockTranslateTagTests(SimpleTestCase): tag_name = "blocktranslate" def get_template(self, template_string): return Template( template_string.replace( "{{% blocktranslate ", "{{% {}".format(self.tag_name) ).replace( "{{% endblocktranslate %}}", "{{% end{} %}}".format(self.tag_name) ) ) @override_settings(LOCALE_PATHS=extended_locale_paths) def test_template_tags_pgettext(self): """ {% blocktranslate %} takes message contexts into account (#14806). """ trans_real._active = Local() trans_real._translations = {} with translation.override("de"): # Nonexistent context t = self.get_template( '{% load i18n %}{% blocktranslate context "nonexistent" %}May' "{% endblocktranslate %}" ) rendered = t.render(Context()) self.assertEqual(rendered, "May") # Existing context... using a literal t = self.get_template( "{% load i18n %}" '{% blocktranslate context "month name" %}May{% endblocktranslate %}' ) rendered = t.render(Context()) self.assertEqual(rendered, "Mai") t = self.get_template( "{% load i18n %}" '{% blocktranslate context "verb" %}May{% endblocktranslate %}' ) rendered = t.render(Context()) self.assertEqual(rendered, "Kann") # Using a variable t = self.get_template( "{% load i18n %}{% blocktranslate context message_context %}" "May{% endblocktranslate %}" ) rendered = t.render(Context({"message_context": "month name"})) self.assertEqual(rendered, "Mai") t = self.get_template( "{% load i18n %}{% blocktranslate context message_context %}" "May{% endblocktranslate %}" ) rendered = t.render(Context({"message_context": "verb"})) self.assertEqual(rendered, "Kann") # Using a filter t = self.get_template( "{% load i18n %}" "{% blocktranslate context message_context|lower %}May" "{% endblocktranslate %}" ) rendered = t.render(Context({"message_context": "MONTH NAME"})) self.assertEqual(rendered, "Mai") t = self.get_template( "{% load i18n %}" "{% blocktranslate context message_context|lower %}May" "{% endblocktranslate %}" ) rendered = t.render(Context({"message_context": "VERB"})) self.assertEqual(rendered, "Kann") # Using 'count' t = self.get_template( "{% load i18n %}" '{% blocktranslate count number=1 context "super search" %}{{ number }}' " super result{% plural %}{{ number }} super results" "{% endblocktranslate %}" ) rendered = t.render(Context()) self.assertEqual(rendered, "1 Super-Ergebnis") t = self.get_template( "{% load i18n %}" '{% blocktranslate count number=2 context "super search" %}{{ number }}' " super result{% plural %}{{ number }} super results" "{% endblocktranslate %}" ) rendered = t.render(Context()) self.assertEqual(rendered, "2 Super-Ergebnisse") t = self.get_template( "{% load i18n %}" '{% blocktranslate context "other super search" count number=1 %}' "{{ number }} super result{% plural %}{{ number }} super results" "{% endblocktranslate %}" ) rendered = t.render(Context()) self.assertEqual(rendered, "1 anderen Super-Ergebnis") t = self.get_template( "{% load i18n %}" '{% blocktranslate context "other super search" count number=2 %}' "{{ number }} super result{% plural %}{{ number }} super results" "{% endblocktranslate %}" ) rendered = t.render(Context()) self.assertEqual(rendered, "2 andere Super-Ergebnisse") # Using 'with' t = self.get_template( "{% load i18n %}" '{% blocktranslate with num_comments=5 context "comment count" %}' "There are {{ num_comments }} comments{% endblocktranslate %}" ) rendered = t.render(Context()) self.assertEqual(rendered, "Es gibt 5 Kommentare") t = self.get_template( "{% load i18n %}" '{% blocktranslate with num_comments=5 context "other comment count" %}' "There are {{ num_comments }} comments{% endblocktranslate %}" ) rendered = t.render(Context()) self.assertEqual(rendered, "Andere: Es gibt 5 Kommentare") # Using trimmed t = self.get_template( "{% load i18n %}{% blocktranslate trimmed %}\n\nThere\n\t are 5 " "\n\n comments\n{% endblocktranslate %}" ) rendered = t.render(Context()) self.assertEqual(rendered, "There are 5 comments") t = self.get_template( "{% load i18n %}" '{% blocktranslate with num_comments=5 context "comment count" trimmed ' "%}\n\n" "There are \t\n \t {{ num_comments }} comments\n\n" "{% endblocktranslate %}" ) rendered = t.render(Context()) self.assertEqual(rendered, "Es gibt 5 Kommentare") t = self.get_template( "{% load i18n %}" '{% blocktranslate context "other super search" count number=2 trimmed ' "%}\n{{ number }} super \n result{% plural %}{{ number }} super results" "{% endblocktranslate %}" ) rendered = t.render(Context()) self.assertEqual(rendered, "2 andere Super-Ergebnisse") # Misuses msg = "Unknown argument for 'blocktranslate' tag: %r." with self.assertRaisesMessage(TemplateSyntaxError, msg % 'month="May"'): self.get_template( '{% load i18n %}{% blocktranslate context with month="May" %}' "{{ month }}{% endblocktranslate %}" ) msg = ( '"context" in %r tag expected exactly one argument.' % "blocktranslate" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.get_template( "{% load i18n %}{% blocktranslate context %}{% endblocktranslate %}" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.get_template( "{% load i18n %}{% blocktranslate count number=2 context %}" "{{ number }} super result{% plural %}{{ number }}" " super results{% endblocktranslate %}" ) @override_settings(LOCALE_PATHS=[os.path.join(here, "other", "locale")]) def test_bad_placeholder_1(self): """ Error in translation file should not crash template rendering (#16516). (%(person)s is translated as %(personne)s in fr.po). """ with translation.override("fr"): t = Template( "{% load i18n %}{% blocktranslate %}My name is {{ person }}." "{% endblocktranslate %}" ) rendered = t.render(Context({"person": "James"})) self.assertEqual(rendered, "My name is James.") @override_settings(LOCALE_PATHS=[os.path.join(here, "other", "locale")]) def test_bad_placeholder_2(self): """ Error in translation file should not crash template rendering (#18393). (%(person) misses a 's' in fr.po, causing the string formatting to fail) . """ with translation.override("fr"): t = Template( "{% load i18n %}{% blocktranslate %}My other name is {{ person }}." "{% endblocktranslate %}" ) rendered = t.render(Context({"person": "James"})) self.assertEqual(rendered, "My other name is James.") class TranslationBlockTransnTagTests(TranslationBlockTranslateTagTests): tag_name = "blocktrans" class MultipleLocaleActivationBlockTranslateTests(MultipleLocaleActivationTestCase): tag_name = "blocktranslate" def get_template(self, template_string): return Template( template_string.replace( "{{% blocktranslate ", "{{% {}".format(self.tag_name) ).replace( "{{% endblocktranslate %}}", "{{% end{} %}}".format(self.tag_name) ) ) def test_single_locale_activation(self): """ Simple baseline behavior with one locale for all the supported i18n constructs. """ with translation.override("fr"): self.assertEqual( self.get_template( "{% load i18n %}{% blocktranslate %}Yes{% endblocktranslate %}" ).render(Context({})), "Oui", ) def test_multiple_locale_btrans(self): with translation.override("de"): t = self.get_template( "{% load i18n %}{% blocktranslate %}No{% endblocktranslate %}" ) with translation.override(self._old_language), translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_deactivate_btrans(self): with translation.override("de", deactivate=True): t = self.get_template( "{% load i18n %}{% blocktranslate %}No{% endblocktranslate %}" ) with translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_direct_switch_btrans(self): with translation.override("de"): t = self.get_template( "{% load i18n %}{% blocktranslate %}No{% endblocktranslate %}" ) with translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") class MultipleLocaleActivationBlockTransTests( MultipleLocaleActivationBlockTranslateTests ): tag_name = "blocktrans" class MiscTests(SimpleTestCase): tag_name = "blocktranslate" def get_template(self, template_string): return Template( template_string.replace( "{{% blocktranslate ", "{{% {}".format(self.tag_name) ).replace( "{{% endblocktranslate %}}", "{{% end{} %}}".format(self.tag_name) ) ) @override_settings(LOCALE_PATHS=extended_locale_paths) def test_percent_in_translatable_block(self): t_sing = self.get_template( "{% load i18n %}{% blocktranslate %}The result was {{ percent }}%" "{% endblocktranslate %}" ) t_plur = self.get_template( "{% load i18n %}{% blocktranslate count num as number %}" "{{ percent }}% represents {{ num }} object{% plural %}" "{{ percent }}% represents {{ num }} objects{% endblocktranslate %}" ) with translation.override("de"): self.assertEqual( t_sing.render(Context({"percent": 42})), "Das Ergebnis war 42%" ) self.assertEqual( t_plur.render(Context({"percent": 42, "num": 1})), "42% stellt 1 Objekt dar", ) self.assertEqual( t_plur.render(Context({"percent": 42, "num": 4})), "42% stellt 4 Objekte dar", ) @override_settings(LOCALE_PATHS=extended_locale_paths) def test_percent_formatting_in_blocktranslate(self): """ Python's %-formatting is properly escaped in blocktranslate, singular, or plural. """ t_sing = self.get_template( "{% load i18n %}{% blocktranslate %}There are %(num_comments)s comments" "{% endblocktranslate %}" ) t_plur = self.get_template( "{% load i18n %}{% blocktranslate count num as number %}" "%(percent)s% represents {{ num }} object{% plural %}" "%(percent)s% represents {{ num }} objects{% endblocktranslate %}" ) with translation.override("de"): # Strings won't get translated as they don't match after escaping % self.assertEqual( t_sing.render(Context({"num_comments": 42})), "There are %(num_comments)s comments", ) self.assertEqual( t_plur.render(Context({"percent": 42, "num": 1})), "%(percent)s% represents 1 object", ) self.assertEqual( t_plur.render(Context({"percent": 42, "num": 4})), "%(percent)s% represents 4 objects", ) class MiscBlockTranslationTests(MiscTests): tag_name = "blocktrans" class BlockTranslateNodeTests(SimpleTestCase): def test_repr(self): block_translate_node = BlockTranslateNode( extra_context={}, singular=[ Token(TokenType.TEXT, "content"), Token(TokenType.VAR, "variable"), ], ) self.assertEqual( repr(block_translate_node), "<BlockTranslateNode: extra_context={} " 'singular=[<Text token: "content...">, <Var token: "variable...">] ' "plural=None>", )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/i18n/__init__.py
tests/template_tests/syntax_tests/i18n/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/i18n/test_filters.py
tests/template_tests/syntax_tests/i18n/test_filters.py
from django.test import SimpleTestCase from django.utils import translation from ...utils import setup class I18nFiltersTests(SimpleTestCase): libraries = { "custom": "template_tests.templatetags.custom", "i18n": "django.templatetags.i18n", } @setup( { "i18n32": '{% load i18n %}{{ "hu"|language_name }} ' '{{ "hu"|language_name_local }} {{ "hu"|language_bidi }} ' '{{ "hu"|language_name_translated }}' } ) def test_i18n32(self): output = self.engine.render_to_string("i18n32") self.assertEqual(output, "Hungarian Magyar False Hungarian") with translation.override("cs"): output = self.engine.render_to_string("i18n32") self.assertEqual(output, "Hungarian Magyar False maďarsky") @setup( { "i18n33": "{% load i18n %}" "{{ langcode|language_name }} {{ langcode|language_name_local }} " "{{ langcode|language_bidi }} {{ langcode|language_name_translated }}" } ) def test_i18n33(self): output = self.engine.render_to_string("i18n33", {"langcode": "nl"}) self.assertEqual(output, "Dutch Nederlands False Dutch") with translation.override("cs"): output = self.engine.render_to_string("i18n33", {"langcode": "nl"}) self.assertEqual(output, "Dutch Nederlands False nizozemsky") @setup( { "i18n38_2": "{% load i18n custom %}" '{% get_language_info_list for langcodes|noop:"x y" as langs %}' "{% for l in langs %}{{ l.code }}: {{ l.name }}/" "{{ l.name_local }}/{{ l.name_translated }} " "bidi={{ l.bidi }}; {% endfor %}" } ) def test_i18n38_2(self): with translation.override("cs"): output = self.engine.render_to_string( "i18n38_2", {"langcodes": ["it", "fr"]} ) self.assertEqual( output, "it: Italian/italiano/italsky bidi=False; " "fr: French/français/francouzsky bidi=False; ", )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/i18n/base.py
tests/template_tests/syntax_tests/i18n/base.py
import os from django.conf import settings from django.test import SimpleTestCase from django.utils.translation import activate, get_language here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) pdir = os.path.split(os.path.split(os.path.abspath(here))[0])[0] extended_locale_paths = settings.LOCALE_PATHS + [ os.path.join(pdir, "i18n", "other", "locale"), ] class MultipleLocaleActivationTestCase(SimpleTestCase): """ Tests for template rendering when multiple locales are activated during the lifetime of the same process. """ def setUp(self): self._old_language = get_language() self.addCleanup(activate, self._old_language)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py
tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py
from django.template import TemplateSyntaxError from django.test import SimpleTestCase from django.utils import translation from ...utils import setup class GetLanguageInfoListTests(SimpleTestCase): libraries = { "custom": "template_tests.templatetags.custom", "i18n": "django.templatetags.i18n", } @setup( { "i18n30": "{% load i18n %}" "{% get_language_info_list for langcodes as langs %}" "{% for l in langs %}{{ l.code }}: {{ l.name }}/" "{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}" } ) def test_i18n30(self): output = self.engine.render_to_string("i18n30", {"langcodes": ["it", "no"]}) self.assertEqual( output, "it: Italian/italiano bidi=False; no: Norwegian/norsk bidi=False; " ) @setup( { "i18n31": "{% load i18n %}" "{% get_language_info_list for langcodes as langs %}" "{% for l in langs %}{{ l.code }}: {{ l.name }}/" "{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}" } ) def test_i18n31(self): output = self.engine.render_to_string( "i18n31", {"langcodes": (("sl", "Slovenian"), ("fa", "Persian"))} ) self.assertEqual( output, "sl: Slovenian/Sloven\u0161\u010dina bidi=False; " "fa: Persian/\u0641\u0627\u0631\u0633\u06cc bidi=True; ", ) @setup( { "i18n38_2": "{% load i18n custom %}" '{% get_language_info_list for langcodes|noop:"x y" as langs %}' "{% for l in langs %}{{ l.code }}: {{ l.name }}/" "{{ l.name_local }}/{{ l.name_translated }} " "bidi={{ l.bidi }}; {% endfor %}" } ) def test_i18n38_2(self): with translation.override("cs"): output = self.engine.render_to_string( "i18n38_2", {"langcodes": ["it", "fr"]} ) self.assertEqual( output, "it: Italian/italiano/italsky bidi=False; " "fr: French/français/francouzsky bidi=False; ", ) @setup({"i18n_syntax": "{% load i18n %} {% get_language_info_list error %}"}) def test_no_for_as(self): msg = ( "'get_language_info_list' requires 'for sequence as variable' (got " "['error'])" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("i18n_syntax")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/i18n/test_language.py
tests/template_tests/syntax_tests/i18n/test_language.py
from template_tests.utils import setup from django.template import TemplateSyntaxError from django.test import SimpleTestCase class I18nLanguageTagTests(SimpleTestCase): libraries = {"i18n": "django.templatetags.i18n"} @setup({"i18n_language": "{% load i18n %} {% language %} {% endlanguage %}"}) def test_no_arg(self): with self.assertRaisesMessage( TemplateSyntaxError, "'language' takes one argument (language)" ): self.engine.render_to_string("i18n_language")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/i18n/test_get_current_language.py
tests/template_tests/syntax_tests/i18n/test_get_current_language.py
from template_tests.utils import setup from django.template import TemplateSyntaxError from django.test import SimpleTestCase class I18nGetCurrentLanguageTagTests(SimpleTestCase): libraries = {"i18n": "django.templatetags.i18n"} @setup({"template": "{% load i18n %} {% get_current_language %}"}) def test_no_as_var(self): msg = ( "'get_current_language' requires 'as variable' (got " "['get_current_language'])" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py
tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py
from template_tests.utils import setup from django.template import TemplateSyntaxError from django.test import SimpleTestCase class I18nGetCurrentLanguageBidiTagTests(SimpleTestCase): libraries = {"i18n": "django.templatetags.i18n"} @setup({"template": "{% load i18n %} {% get_current_language_bidi %}"}) def test_no_as_var(self): msg = ( "'get_current_language_bidi' requires 'as variable' (got " "['get_current_language_bidi'])" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/template_tests/syntax_tests/i18n/test_get_language_info.py
tests/template_tests/syntax_tests/i18n/test_get_language_info.py
from django.template import TemplateSyntaxError from django.test import SimpleTestCase from django.utils import translation from ...utils import setup class I18nGetLanguageInfoTagTests(SimpleTestCase): libraries = { "custom": "template_tests.templatetags.custom", "i18n": "django.templatetags.i18n", } # retrieving language information @setup( { "i18n28_2": "{% load i18n %}" '{% get_language_info for "de" as l %}' "{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}" } ) def test_i18n28_2(self): output = self.engine.render_to_string("i18n28_2") self.assertEqual(output, "de: German/Deutsch bidi=False") @setup( { "i18n29": "{% load i18n %}" "{% get_language_info for LANGUAGE_CODE as l %}" "{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}" } ) def test_i18n29(self): output = self.engine.render_to_string("i18n29", {"LANGUAGE_CODE": "fi"}) self.assertEqual(output, "fi: Finnish/suomi bidi=False") # Test whitespace in filter arguments @setup( { "i18n38": "{% load i18n custom %}" '{% get_language_info for "de"|noop:"x y" as l %}' "{{ l.code }}: {{ l.name }}/{{ l.name_local }}/" "{{ l.name_translated }} bidi={{ l.bidi }}" } ) def test_i18n38(self): with translation.override("cs"): output = self.engine.render_to_string("i18n38") self.assertEqual(output, "de: German/Deutsch/německy bidi=False") @setup({"template": "{% load i18n %}{% get_language_info %}"}) def test_no_for_as(self): msg = "'get_language_info' requires 'for string as variable' (got [])" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_custom_urls/models.py
tests/admin_custom_urls/models.py
from functools import update_wrapper from django.contrib import admin from django.db import models from django.http import HttpResponseRedirect from django.urls import reverse class Action(models.Model): name = models.CharField(max_length=50, primary_key=True) description = models.CharField(max_length=70) def __str__(self): return self.name class ActionAdmin(admin.ModelAdmin): """ A ModelAdmin for the Action model that changes the URL of the add_view to '<app name>/<model name>/!add/' The Action model has a CharField PK. """ list_display = ("name", "description") def remove_url(self, name): """ Remove all entries named 'name' from the ModelAdmin instance URL patterns list """ return [url for url in super().get_urls() if url.name != name] def get_urls(self): # Add the URL of our custom 'add_view' view to the front of the URLs # list. Remove the existing one(s) first from django.urls import re_path def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = self.opts.app_label, self.opts.model_name view_name = "%s_%s_add" % info return [ re_path("^!add/$", wrap(self.add_view), name=view_name), ] + self.remove_url(view_name) class Person(models.Model): name = models.CharField(max_length=20) class PersonAdmin(admin.ModelAdmin): def response_post_save_add(self, request, obj): return HttpResponseRedirect( reverse("admin:admin_custom_urls_person_history", args=[obj.pk]) ) def response_post_save_change(self, request, obj): return HttpResponseRedirect( reverse("admin:admin_custom_urls_person_delete", args=[obj.pk]) ) class Car(models.Model): name = models.CharField(max_length=20) class CarAdmin(admin.ModelAdmin): def response_add(self, request, obj, post_url_continue=None): return super().response_add( request, obj, post_url_continue=reverse( "admin:admin_custom_urls_car_history", args=[obj.pk] ), ) site = admin.AdminSite(name="admin_custom_urls") site.register(Action, ActionAdmin) site.register(Person, PersonAdmin) site.register(Car, CarAdmin)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_custom_urls/__init__.py
tests/admin_custom_urls/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_custom_urls/tests.py
tests/admin_custom_urls/tests.py
from django.contrib.admin.utils import quote from django.contrib.admin.views.main import IS_POPUP_VAR from django.contrib.auth.models import User from django.template.response import TemplateResponse from django.test import TestCase, override_settings from django.urls import reverse from .models import Action, Car, Person @override_settings( ROOT_URLCONF="admin_custom_urls.urls", ) class AdminCustomUrlsTest(TestCase): """ Remember that: * The Action model has a CharField PK. * The ModelAdmin for Action customizes the add_view URL, it's '<app name>/<model name>/!add/' """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) Action.objects.create(name="delete", description="Remove things.") Action.objects.create(name="rename", description="Gives things other names.") Action.objects.create(name="add", description="Add things.") Action.objects.create( name="path/to/file/", description="An action with '/' in its name." ) Action.objects.create( name="path/to/html/document.html", description="An action with a name similar to a HTML doc path.", ) Action.objects.create( name="javascript:alert('Hello world');\">Click here</a>", description="An action with a name suspected of being a XSS attempt", ) def setUp(self): self.client.force_login(self.superuser) def test_basic_add_GET(self): """ Ensure GET on the add_view works. """ add_url = reverse("admin_custom_urls:admin_custom_urls_action_add") self.assertTrue(add_url.endswith("/!add/")) response = self.client.get(add_url) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_add_with_GET_args(self): """ Ensure GET on the add_view plus specifying a field value in the query string works. """ response = self.client.get( reverse("admin_custom_urls:admin_custom_urls_action_add"), {"name": "My Action"}, ) self.assertContains(response, 'value="My Action"') def test_basic_add_POST(self): """ Ensure POST on add_view works. """ post_data = { IS_POPUP_VAR: "1", "name": "Action added through a popup", "description": "Description of added action", } response = self.client.post( reverse("admin_custom_urls:admin_custom_urls_action_add"), post_data ) self.assertContains(response, "Action added through a popup") def test_admin_URLs_no_clash(self): # Should get the change_view for model instance with PK 'add', not show # the add_view url = reverse( "admin_custom_urls:%s_action_change" % Action._meta.app_label, args=(quote("add"),), ) response = self.client.get(url) self.assertContains(response, "Change action") # Should correctly get the change_view for the model instance with the # funny-looking PK (the one with a 'path/to/html/document.html' value) url = reverse( "admin_custom_urls:%s_action_change" % Action._meta.app_label, args=(quote("path/to/html/document.html"),), ) response = self.client.get(url) self.assertContains(response, "Change action") self.assertContains(response, 'value="path/to/html/document.html"') def test_post_save_add_redirect(self): """ ModelAdmin.response_post_save_add() controls the redirection after the 'Save' button has been pressed when adding a new object. """ post_data = {"name": "John Doe"} self.assertEqual(Person.objects.count(), 0) response = self.client.post( reverse("admin_custom_urls:admin_custom_urls_person_add"), post_data ) persons = Person.objects.all() self.assertEqual(len(persons), 1) redirect_url = reverse( "admin_custom_urls:admin_custom_urls_person_history", args=[persons[0].pk] ) self.assertRedirects(response, redirect_url) def test_post_save_change_redirect(self): """ ModelAdmin.response_post_save_change() controls the redirection after the 'Save' button has been pressed when editing an existing object. """ Person.objects.create(name="John Doe") self.assertEqual(Person.objects.count(), 1) person = Person.objects.all()[0] post_url = reverse( "admin_custom_urls:admin_custom_urls_person_change", args=[person.pk] ) response = self.client.post(post_url, {"name": "Jack Doe"}) self.assertRedirects( response, reverse( "admin_custom_urls:admin_custom_urls_person_delete", args=[person.pk] ), ) def test_post_url_continue(self): """ The ModelAdmin.response_add()'s parameter `post_url_continue` controls the redirection after an object has been created. """ post_data = {"name": "SuperFast", "_continue": "1"} self.assertEqual(Car.objects.count(), 0) response = self.client.post( reverse("admin_custom_urls:admin_custom_urls_car_add"), post_data ) cars = Car.objects.all() self.assertEqual(len(cars), 1) self.assertRedirects( response, reverse( "admin_custom_urls:admin_custom_urls_car_history", args=[cars[0].pk] ), )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_custom_urls/urls.py
tests/admin_custom_urls/urls.py
from django.urls import path from .models import site urlpatterns = [ path("admin/", site.urls), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/select_related_onetoone/models.py
tests/select_related_onetoone/models.py
from django.db import models class User(models.Model): username = models.CharField(max_length=100) email = models.EmailField() class UserProfile(models.Model): user = models.OneToOneField(User, models.CASCADE) city = models.CharField(max_length=100) state = models.CharField(max_length=2) class UserStatResult(models.Model): results = models.CharField(max_length=50) class UserStat(models.Model): user = models.OneToOneField(User, models.CASCADE, primary_key=True) posts = models.IntegerField() results = models.ForeignKey(UserStatResult, models.CASCADE) class StatDetails(models.Model): base_stats = models.OneToOneField(UserStat, models.CASCADE) comments = models.IntegerField() class AdvancedUserStat(UserStat): karma = models.IntegerField() class Image(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=100) image = models.OneToOneField(Image, models.SET_NULL, null=True) class Parent1(models.Model): name1 = models.CharField(max_length=50) class Parent2(models.Model): # Avoid having two "id" fields in the Child1 subclass id2 = models.AutoField(primary_key=True) name2 = models.CharField(max_length=50) class Child1(Parent1, Parent2): value = models.IntegerField() class Child2(Parent1): parent2 = models.OneToOneField(Parent2, models.CASCADE) value = models.IntegerField() class Child3(Child2): value3 = models.IntegerField() class Child4(Child1): value4 = models.IntegerField() class LinkedList(models.Model): name = models.CharField(max_length=50) previous_item = models.OneToOneField( "self", models.CASCADE, related_name="next_item", blank=True, null=True, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/select_related_onetoone/__init__.py
tests/select_related_onetoone/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/select_related_onetoone/tests.py
tests/select_related_onetoone/tests.py
from django.core.exceptions import FieldError from django.db.models import FilteredRelation from django.test import SimpleTestCase, TestCase from .models import ( AdvancedUserStat, Child1, Child2, Child3, Child4, Image, LinkedList, Parent1, Parent2, Product, StatDetails, User, UserProfile, UserStat, UserStatResult, ) class ReverseSelectRelatedTestCase(TestCase): @classmethod def setUpTestData(cls): user = User.objects.create(username="test") UserProfile.objects.create(user=user, state="KS", city="Lawrence") results = UserStatResult.objects.create(results="first results") userstat = UserStat.objects.create(user=user, posts=150, results=results) StatDetails.objects.create(base_stats=userstat, comments=259) user2 = User.objects.create(username="bob") results2 = UserStatResult.objects.create(results="moar results") advstat = AdvancedUserStat.objects.create( user=user2, posts=200, karma=5, results=results2 ) StatDetails.objects.create(base_stats=advstat, comments=250) p1 = Parent1(name1="Only Parent1") p1.save() c1 = Child1(name1="Child1 Parent1", name2="Child1 Parent2", value=1) c1.save() p2 = Parent2(name2="Child2 Parent2") p2.save() c2 = Child2(name1="Child2 Parent1", parent2=p2, value=2) c2.save() def test_basic(self): with self.assertNumQueries(1): u = User.objects.select_related("userprofile").get(username="test") self.assertEqual(u.userprofile.state, "KS") def test_follow_next_level(self): with self.assertNumQueries(1): u = User.objects.select_related("userstat__results").get(username="test") self.assertEqual(u.userstat.posts, 150) self.assertEqual(u.userstat.results.results, "first results") def test_follow_two(self): with self.assertNumQueries(1): u = User.objects.select_related("userprofile", "userstat").get( username="test" ) self.assertEqual(u.userprofile.state, "KS") self.assertEqual(u.userstat.posts, 150) def test_follow_two_next_level(self): with self.assertNumQueries(1): u = User.objects.select_related( "userstat__results", "userstat__statdetails" ).get(username="test") self.assertEqual(u.userstat.results.results, "first results") self.assertEqual(u.userstat.statdetails.comments, 259) def test_forward_and_back(self): with self.assertNumQueries(1): stat = UserStat.objects.select_related("user__userprofile").get( user__username="test" ) self.assertEqual(stat.user.userprofile.state, "KS") self.assertEqual(stat.user.userstat.posts, 150) def test_back_and_forward(self): with self.assertNumQueries(1): u = User.objects.select_related("userstat").get(username="test") self.assertEqual(u.userstat.user.username, "test") def test_not_followed_by_default(self): with self.assertNumQueries(2): u = User.objects.select_related().get(username="test") self.assertEqual(u.userstat.posts, 150) def test_follow_from_child_class(self): with self.assertNumQueries(1): stat = AdvancedUserStat.objects.select_related("user", "statdetails").get( posts=200 ) self.assertEqual(stat.statdetails.comments, 250) self.assertEqual(stat.user.username, "bob") def test_follow_inheritance(self): with self.assertNumQueries(1): stat = UserStat.objects.select_related("user", "advanceduserstat").get( posts=200 ) self.assertEqual(stat.advanceduserstat.posts, 200) self.assertEqual(stat.user.username, "bob") with self.assertNumQueries(0): self.assertEqual(stat.advanceduserstat.user.username, "bob") def test_nullable_relation(self): im = Image.objects.create(name="imag1") p1 = Product.objects.create(name="Django Plushie", image=im) p2 = Product.objects.create(name="Talking Django Plushie") with self.assertNumQueries(1): result = sorted( Product.objects.select_related("image"), key=lambda x: x.name ) self.assertEqual( [p.name for p in result], ["Django Plushie", "Talking Django Plushie"] ) self.assertEqual(p1.image, im) # Check for ticket #13839 self.assertIsNone(p2.image) def test_missing_reverse(self): """ Ticket #13839: select_related() should NOT cache None for missing objects on a reverse 1-1 relation. """ with self.assertNumQueries(1): user = User.objects.select_related("userprofile").get(username="bob") with self.assertRaises(UserProfile.DoesNotExist): user.userprofile def test_nullable_missing_reverse(self): """ Ticket #13839: select_related() should NOT cache None for missing objects on a reverse 0-1 relation. """ Image.objects.create(name="imag1") with self.assertNumQueries(1): image = Image.objects.select_related("product").get() with self.assertRaises(Product.DoesNotExist): image.product def test_parent_only(self): with self.assertNumQueries(1): p = Parent1.objects.select_related("child1").get(name1="Only Parent1") with self.assertNumQueries(0): with self.assertRaises(Child1.DoesNotExist): p.child1 def test_multiple_subclass(self): with self.assertNumQueries(1): p = Parent1.objects.select_related("child1").get(name1="Child1 Parent1") self.assertEqual(p.child1.name2, "Child1 Parent2") def test_onetoone_with_subclass(self): with self.assertNumQueries(1): p = Parent2.objects.select_related("child2").get(name2="Child2 Parent2") self.assertEqual(p.child2.name1, "Child2 Parent1") def test_onetoone_with_two_subclasses(self): with self.assertNumQueries(1): p = Parent2.objects.select_related("child2", "child2__child3").get( name2="Child2 Parent2" ) self.assertEqual(p.child2.name1, "Child2 Parent1") with self.assertRaises(Child3.DoesNotExist): p.child2.child3 p3 = Parent2(name2="Child3 Parent2") p3.save() c2 = Child3(name1="Child3 Parent1", parent2=p3, value=2, value3=3) c2.save() with self.assertNumQueries(1): p = Parent2.objects.select_related("child2", "child2__child3").get( name2="Child3 Parent2" ) self.assertEqual(p.child2.name1, "Child3 Parent1") self.assertEqual(p.child2.child3.value3, 3) self.assertEqual(p.child2.child3.value, p.child2.value) self.assertEqual(p.child2.name1, p.child2.child3.name1) def test_multiinheritance_two_subclasses(self): with self.assertNumQueries(1): p = Parent1.objects.select_related("child1", "child1__child4").get( name1="Child1 Parent1" ) self.assertEqual(p.child1.name2, "Child1 Parent2") self.assertEqual(p.child1.name1, p.name1) with self.assertRaises(Child4.DoesNotExist): p.child1.child4 Child4(name1="n1", name2="n2", value=1, value4=4).save() with self.assertNumQueries(1): p = Parent2.objects.select_related("child1", "child1__child4").get( name2="n2" ) self.assertEqual(p.name2, "n2") self.assertEqual(p.child1.name1, "n1") self.assertEqual(p.child1.name2, p.name2) self.assertEqual(p.child1.value, 1) self.assertEqual(p.child1.child4.name1, p.child1.name1) self.assertEqual(p.child1.child4.name2, p.child1.name2) self.assertEqual(p.child1.child4.value, p.child1.value) self.assertEqual(p.child1.child4.value4, 4) def test_inheritance_deferred(self): c = Child4.objects.create(name1="n1", name2="n2", value=1, value4=4) with self.assertNumQueries(1): p = ( Parent2.objects.select_related("child1") .only("id2", "child1__value") .get(name2="n2") ) self.assertEqual(p.id2, c.id2) self.assertEqual(p.child1.value, 1) p = ( Parent2.objects.select_related("child1") .only("id2", "child1__value") .get(name2="n2") ) with self.assertNumQueries(1): self.assertEqual(p.name2, "n2") p = ( Parent2.objects.select_related("child1") .only("id2", "child1__value") .get(name2="n2") ) with self.assertNumQueries(1): self.assertEqual(p.child1.name2, "n2") def test_inheritance_deferred2(self): c = Child4.objects.create(name1="n1", name2="n2", value=1, value4=4) qs = Parent2.objects.select_related("child1", "child1__child4").only( "id2", "child1__value", "child1__child4__value4" ) with self.assertNumQueries(1): p = qs.get(name2="n2") self.assertEqual(p.id2, c.id2) self.assertEqual(p.child1.value, 1) self.assertEqual(p.child1.child4.value4, 4) self.assertEqual(p.child1.child4.id2, c.id2) p = qs.get(name2="n2") with self.assertNumQueries(1): self.assertEqual(p.child1.name2, "n2") p = qs.get(name2="n2") with self.assertNumQueries(0): self.assertEqual(p.child1.value, 1) self.assertEqual(p.child1.child4.value4, 4) with self.assertNumQueries(2): self.assertEqual(p.child1.name1, "n1") self.assertEqual(p.child1.child4.name1, "n1") def test_self_relation(self): item1 = LinkedList.objects.create(name="item1") LinkedList.objects.create(name="item2", previous_item=item1) with self.assertNumQueries(1): item1_db = LinkedList.objects.select_related("next_item").get(name="item1") self.assertEqual(item1_db.next_item.name, "item2") class ReverseSelectRelatedValidationTests(SimpleTestCase): """ Rverse related fields should be listed in the validation message when an invalid field is given in select_related(). """ non_relational_error = ( "Non-relational field given in select_related: '%s'. Choices are: %s" ) invalid_error = ( "Invalid field name(s) given in select_related: '%s'. Choices are: %s" ) def test_reverse_related_validation(self): fields = "userprofile, userstat" with self.assertRaisesMessage( FieldError, self.invalid_error % ("foobar", fields) ): list(User.objects.select_related("foobar")) with self.assertRaisesMessage( FieldError, self.non_relational_error % ("username", fields) ): list(User.objects.select_related("username")) def test_reverse_related_validation_with_filtered_relation(self): fields = "userprofile, userstat, relation" with self.assertRaisesMessage( FieldError, self.invalid_error % ("foobar", fields) ): list( User.objects.annotate( relation=FilteredRelation("userprofile") ).select_related("foobar") )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_utils/__init__.py
tests/db_utils/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/db_utils/tests.py
tests/db_utils/tests.py
"""Tests for django.db.utils.""" import unittest from django.core.exceptions import ImproperlyConfigured from django.db import DEFAULT_DB_ALIAS, ProgrammingError, connection from django.db.utils import ConnectionHandler, load_backend from django.test import SimpleTestCase, TestCase from django.utils.connection import ConnectionDoesNotExist class ConnectionHandlerTests(SimpleTestCase): def test_connection_handler_no_databases(self): """ Empty DATABASES and empty 'default' settings default to the dummy backend. """ for DATABASES in ( {}, # Empty DATABASES setting. {"default": {}}, # Empty 'default' database. ): with self.subTest(DATABASES=DATABASES): self.assertImproperlyConfigured(DATABASES) def assertImproperlyConfigured(self, DATABASES): conns = ConnectionHandler(DATABASES) self.assertEqual( conns[DEFAULT_DB_ALIAS].settings_dict["ENGINE"], "django.db.backends.dummy" ) msg = ( "settings.DATABASES is improperly configured. Please supply the " "ENGINE value. Check settings documentation for more details." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): conns[DEFAULT_DB_ALIAS].ensure_connection() def test_no_default_database(self): DATABASES = {"other": {}} conns = ConnectionHandler(DATABASES) msg = "You must define a 'default' database." with self.assertRaisesMessage(ImproperlyConfigured, msg): conns["other"].ensure_connection() def test_databases_property(self): # The "databases" property is maintained for backwards compatibility # with 3rd party packages. It should be an alias of the "settings" # property. conn = ConnectionHandler({}) self.assertNotEqual(conn.settings, {}) self.assertEqual(conn.settings, conn.databases) def test_nonexistent_alias(self): msg = "The connection 'nonexistent' doesn't exist." conns = ConnectionHandler( { DEFAULT_DB_ALIAS: {"ENGINE": "django.db.backends.dummy"}, } ) with self.assertRaisesMessage(ConnectionDoesNotExist, msg): conns["nonexistent"] class DatabaseErrorWrapperTests(TestCase): @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL test") def test_reraising_backend_specific_database_exception(self): from django.db.backends.postgresql.psycopg_any import is_psycopg3 with connection.cursor() as cursor: msg = 'table "X" does not exist' with self.assertRaisesMessage(ProgrammingError, msg) as cm: cursor.execute('DROP TABLE "X"') self.assertNotEqual(type(cm.exception), type(cm.exception.__cause__)) self.assertIsNotNone(cm.exception.__cause__) if is_psycopg3: self.assertIsNotNone(cm.exception.__cause__.diag.sqlstate) self.assertIsNotNone(cm.exception.__cause__.diag.message_primary) else: self.assertIsNotNone(cm.exception.__cause__.pgcode) self.assertIsNotNone(cm.exception.__cause__.pgerror) class LoadBackendTests(SimpleTestCase): def test_load_backend_invalid_name(self): msg = ( "'foo' isn't an available database backend or couldn't be " "imported. Check the above exception. To use one of the built-in " "backends, use 'django.db.backends.XXX', where XXX is one of:\n" " 'mysql', 'oracle', 'postgresql', 'sqlite3'" ) with self.assertRaisesMessage(ImproperlyConfigured, msg) as cm: load_backend("foo") self.assertEqual(str(cm.exception.__cause__), "No module named 'foo'")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/file_storage/test_generate_filename.py
tests/file_storage/test_generate_filename.py
import os from django.core.exceptions import SuspiciousFileOperation from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage, Storage from django.db.models import FileField from django.test import SimpleTestCase class AWSS3Storage(Storage): """ Simulate an AWS S3 storage which uses Unix-like paths and allows any characters in file names but where there aren't actual folders but just keys. """ prefix = "mys3folder/" def _save(self, name, content): """ This method is important to test that Storage.save() doesn't replace '\' with '/' (rather FileSystemStorage.save() does). """ return name def get_valid_name(self, name): return name def get_available_name(self, name, max_length=None): return name def generate_filename(self, filename): """ This is the method that's important to override when using S3 so that os.path() isn't called, which would break S3 keys. """ return self.prefix + self.get_valid_name(filename) class StorageGenerateFilenameTests(SimpleTestCase): """Tests for base Storage's generate_filename method.""" storage_class = Storage def test_valid_names(self): storage = self.storage_class() name = "UnTRIVíAL @fil$ena#me!" valid_name = storage.get_valid_name(name) candidates = [ (name, valid_name), (f"././././././{name}", valid_name), (f"some/path/{name}", f"some/path/{valid_name}"), (f"some/./path/./{name}", f"some/path/{valid_name}"), (f"././some/././path/./{name}", f"some/path/{valid_name}"), (f".\\.\\.\\.\\.\\.\\{name}", valid_name), (f"some\\path\\{name}", f"some/path/{valid_name}"), (f"some\\.\\path\\.\\{name}", f"some/path/{valid_name}"), (f".\\.\\some\\.\\.\\path\\.\\{name}", f"some/path/{valid_name}"), ] for name, expected in candidates: with self.subTest(name=name): result = storage.generate_filename(name) self.assertEqual(result, os.path.normpath(expected)) class FileSystemStorageGenerateFilenameTests(StorageGenerateFilenameTests): storage_class = FileSystemStorage class GenerateFilenameStorageTests(SimpleTestCase): def test_storage_dangerous_paths(self): candidates = [ ("/tmp/..", ".."), ("\\tmp\\..", ".."), ("/tmp/.", "."), ("\\tmp\\.", "."), ("..", ".."), (".", "."), ("", ""), ] s = FileSystemStorage() s_overwrite = FileSystemStorage(allow_overwrite=True) msg = "Could not derive file name from '%s'" for file_name, base_name in candidates: with self.subTest(file_name=file_name): with self.assertRaisesMessage(SuspiciousFileOperation, msg % base_name): s.get_available_name(file_name) with self.assertRaisesMessage(SuspiciousFileOperation, msg % base_name): s_overwrite.get_available_name(file_name) with self.assertRaisesMessage(SuspiciousFileOperation, msg % base_name): s.generate_filename(file_name) def test_storage_dangerous_paths_dir_name(self): candidates = [ ("../path", ".."), ("..\\path", ".."), ("tmp/../path", "tmp/.."), ("tmp\\..\\path", "tmp/.."), ("/tmp/../path", "/tmp/.."), ("\\tmp\\..\\path", "/tmp/.."), ] s = FileSystemStorage() s_overwrite = FileSystemStorage(allow_overwrite=True) for file_name, path in candidates: msg = "Detected path traversal attempt in '%s'" % path with self.subTest(file_name=file_name): with self.assertRaisesMessage(SuspiciousFileOperation, msg): s.get_available_name(file_name) with self.assertRaisesMessage(SuspiciousFileOperation, msg): s_overwrite.get_available_name(file_name) with self.assertRaisesMessage(SuspiciousFileOperation, msg): s.generate_filename(file_name) def test_filefield_dangerous_filename(self): candidates = [ ("..", "some/folder/.."), (".", "some/folder/."), ("", "some/folder/"), ("???", "???"), ("$.$.$", "$.$.$"), ] f = FileField(upload_to="some/folder/") for file_name, msg_file_name in candidates: msg = f"Could not derive file name from '{msg_file_name}'" with self.subTest(file_name=file_name): with self.assertRaisesMessage(SuspiciousFileOperation, msg): f.generate_filename(None, file_name) def test_filefield_dangerous_filename_dot_segments(self): f = FileField(upload_to="some/folder/") msg = "Detected path traversal attempt in 'some/folder/../path'" with self.assertRaisesMessage(SuspiciousFileOperation, msg): f.generate_filename(None, "../path") def test_filefield_generate_filename_absolute_path(self): f = FileField(upload_to="some/folder/") candidates = [ "/tmp/path", "/tmp/../path", ] for file_name in candidates: msg = f"Detected path traversal attempt in '{file_name}'" with self.subTest(file_name=file_name): with self.assertRaisesMessage(SuspiciousFileOperation, msg): f.generate_filename(None, file_name) def test_filefield_generate_filename(self): f = FileField(upload_to="some/folder/") self.assertEqual( f.generate_filename(None, "test with space.txt"), os.path.normpath("some/folder/test_with_space.txt"), ) def test_filefield_generate_filename_with_upload_to(self): def upload_to(instance, filename): return "some/folder/" + filename f = FileField(upload_to=upload_to) self.assertEqual( f.generate_filename(None, "test with space.txt"), os.path.normpath("some/folder/test_with_space.txt"), ) def test_filefield_generate_filename_upload_to_overrides_dangerous_filename(self): def upload_to(instance, filename): return "test.txt" f = FileField(upload_to=upload_to) candidates = [ "/tmp/.", "/tmp/..", "/tmp/../path", "/tmp/path", "some/folder/", "some/folder/.", "some/folder/..", "some/folder/???", "some/folder/$.$.$", "some/../test.txt", "", ] for file_name in candidates: with self.subTest(file_name=file_name): self.assertEqual(f.generate_filename(None, file_name), "test.txt") def test_filefield_generate_filename_upload_to_absolute_path(self): def upload_to(instance, filename): return "/tmp/" + filename f = FileField(upload_to=upload_to) candidates = [ "path", "../path", "???", "$.$.$", ] for file_name in candidates: msg = f"Detected path traversal attempt in '/tmp/{file_name}'" with self.subTest(file_name=file_name): with self.assertRaisesMessage(SuspiciousFileOperation, msg): f.generate_filename(None, file_name) def test_filefield_generate_filename_upload_to_dangerous_filename(self): def upload_to(instance, filename): return "/tmp/" + filename f = FileField(upload_to=upload_to) candidates = ["..", ".", ""] for file_name in candidates: msg = f"Could not derive file name from '/tmp/{file_name}'" with self.subTest(file_name=file_name): with self.assertRaisesMessage(SuspiciousFileOperation, msg): f.generate_filename(None, file_name) def test_filefield_awss3_storage(self): """ Simulate a FileField with an S3 storage which uses keys rather than folders and names. FileField and Storage shouldn't have any os.path() calls that break the key. """ storage = AWSS3Storage() folder = "not/a/folder/" f = FileField(upload_to=folder, storage=storage) key = "my-file-key\\with odd characters" data = ContentFile("test") expected_key = AWSS3Storage.prefix + folder + key # Simulate call to f.save() result_key = f.generate_filename(None, key) self.assertEqual(result_key, expected_key) result_key = storage.save(result_key, data) self.assertEqual(result_key, expected_key) # Repeat test with a callable. def upload_to(instance, filename): # Return a non-normalized path on purpose. return folder + filename f = FileField(upload_to=upload_to, storage=storage) # Simulate call to f.save() result_key = f.generate_filename(None, key) self.assertEqual(result_key, expected_key) result_key = storage.save(result_key, data) self.assertEqual(result_key, expected_key)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/file_storage/test_base.py
tests/file_storage/test_base.py
import os from unittest import mock from django.core.exceptions import SuspiciousFileOperation from django.core.files.storage import Storage from django.test import SimpleTestCase class CustomStorage(Storage): """Simple Storage subclass implementing the bare minimum for testing.""" def exists(self, name): return False def _save(self, name): return name class StorageValidateFileNameTests(SimpleTestCase): invalid_file_names = [ os.path.join("path", "to", os.pardir, "test.file"), os.path.join(os.path.sep, "path", "to", "test.file"), ] error_msg = "Detected path traversal attempt in '%s'" def test_validate_before_get_available_name(self): s = CustomStorage() # The initial name passed to `save` is not valid nor safe, fail early. for name in self.invalid_file_names: with ( self.subTest(name=name), mock.patch.object(s, "get_available_name") as mock_get_available_name, mock.patch.object(s, "_save") as mock_internal_save, ): with self.assertRaisesMessage( SuspiciousFileOperation, self.error_msg % name ): s.save(name, content="irrelevant") self.assertEqual(mock_get_available_name.mock_calls, []) self.assertEqual(mock_internal_save.mock_calls, []) def test_validate_after_get_available_name(self): s = CustomStorage() # The initial name passed to `save` is valid and safe, but the returned # name from `get_available_name` is not. for name in self.invalid_file_names: with ( self.subTest(name=name), mock.patch.object(s, "get_available_name", return_value=name), mock.patch.object(s, "_save") as mock_internal_save, ): with self.assertRaisesMessage( SuspiciousFileOperation, self.error_msg % name ): s.save("valid-file-name.txt", content="irrelevant") self.assertEqual(mock_internal_save.mock_calls, []) def test_validate_after_internal_save(self): s = CustomStorage() # The initial name passed to `save` is valid and safe, but the result # from `_save` is not (this is achieved by monkeypatching _save). for name in self.invalid_file_names: with ( self.subTest(name=name), mock.patch.object(s, "_save", return_value=name), ): with self.assertRaisesMessage( SuspiciousFileOperation, self.error_msg % name ): s.save("valid-file-name.txt", content="irrelevant")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/file_storage/models.py
tests/file_storage/models.py
""" Storing files according to a custom storage system ``FileField`` and its variations can take a ``storage`` argument to specify how and where files should be stored. """ import random import tempfile from pathlib import Path from django.core.files.storage import FileSystemStorage, default_storage from django.db import models from django.utils.functional import LazyObject class CustomValidNameStorage(FileSystemStorage): def get_valid_name(self, name): # mark the name to show that this was called return name + "_valid" temp_storage_location = tempfile.mkdtemp() temp_storage = FileSystemStorage(location=temp_storage_location) def callable_storage(): return temp_storage def callable_default_storage(): return default_storage class CallableStorage(FileSystemStorage): def __call__(self): # no-op implementation. return self class LazyTempStorage(LazyObject): def _setup(self): self._wrapped = temp_storage class Storage(models.Model): def custom_upload_to(self, filename): return "foo" def random_upload_to(self, filename): # This returns a different result each time, # to make sure it only gets called once. return "%s/%s" % (random.randint(100, 999), filename) def pathlib_upload_to(self, filename): return Path("bar") / filename normal = models.FileField(storage=temp_storage, upload_to="tests") custom = models.FileField(storage=temp_storage, upload_to=custom_upload_to) pathlib_callable = models.FileField( storage=temp_storage, upload_to=pathlib_upload_to ) pathlib_direct = models.FileField(storage=temp_storage, upload_to=Path("bar")) random = models.FileField(storage=temp_storage, upload_to=random_upload_to) custom_valid_name = models.FileField( storage=CustomValidNameStorage(location=temp_storage_location), upload_to=random_upload_to, ) storage_callable = models.FileField( storage=callable_storage, upload_to="storage_callable" ) storage_callable_class = models.FileField( storage=CallableStorage, upload_to="storage_callable_class" ) storage_callable_default = models.FileField( storage=callable_default_storage, upload_to="storage_callable_default" ) default = models.FileField( storage=temp_storage, upload_to="tests", default="tests/default.txt" ) db_default = models.FileField( storage=temp_storage, upload_to="tests", db_default="tests/db_default.txt" ) empty = models.FileField(storage=temp_storage) limited_length = models.FileField( storage=temp_storage, upload_to="tests", max_length=20 ) extended_length = models.FileField( storage=temp_storage, upload_to="tests", max_length=1024 ) lazy_storage = models.FileField(storage=LazyTempStorage(), upload_to="tests")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/file_storage/test_inmemory_storage.py
tests/file_storage/test_inmemory_storage.py
import os import sys import time import unittest from django.core.files.base import ContentFile from django.core.files.storage import InMemoryStorage from django.core.files.uploadedfile import TemporaryUploadedFile from django.test import SimpleTestCase, override_settings class MemoryStorageIOTests(unittest.TestCase): def setUp(self): self.storage = InMemoryStorage() def test_write_string(self): with self.storage.open("file.txt", "w") as fd: fd.write("hello") with self.storage.open("file.txt", "r") as fd: self.assertEqual(fd.read(), "hello") with self.storage.open("file.dat", "wb") as fd: fd.write(b"hello") with self.storage.open("file.dat", "rb") as fd: self.assertEqual(fd.read(), b"hello") def test_convert_str_to_bytes_and_back(self): """InMemoryStorage handles conversion from str to bytes and back.""" with self.storage.open("file.txt", "w") as fd: fd.write("hello") with self.storage.open("file.txt", "rb") as fd: self.assertEqual(fd.read(), b"hello") with self.storage.open("file.dat", "wb") as fd: fd.write(b"hello") with self.storage.open("file.dat", "r") as fd: self.assertEqual(fd.read(), "hello") def test_open_missing_file(self): self.assertRaises(FileNotFoundError, self.storage.open, "missing.txt") def test_open_dir_as_file(self): with self.storage.open("a/b/file.txt", "w") as fd: fd.write("hello") self.assertRaises(IsADirectoryError, self.storage.open, "a/b") def test_file_saving(self): self.storage.save("file.txt", ContentFile("test")) self.assertEqual(self.storage.open("file.txt", "r").read(), "test") self.storage.save("file.dat", ContentFile(b"test")) self.assertEqual(self.storage.open("file.dat", "rb").read(), b"test") @unittest.skipIf( sys.platform == "win32", "Windows doesn't support moving open files." ) def test_removing_temporary_file_after_save(self): """A temporary file is removed when saved into storage.""" with TemporaryUploadedFile("test", "text/plain", 1, "utf8") as file: self.storage.save("test.txt", file) self.assertFalse(os.path.exists(file.temporary_file_path())) def test_large_file_saving(self): large_file = ContentFile("A" * ContentFile.DEFAULT_CHUNK_SIZE * 3) self.storage.save("file.txt", large_file) def test_file_size(self): """ File size is equal to the size of bytes-encoded version of the saved data. """ self.storage.save("file.txt", ContentFile("test")) self.assertEqual(self.storage.size("file.txt"), 4) # A unicode char encoded to UTF-8 takes 2 bytes. self.storage.save("unicode_file.txt", ContentFile("è")) self.assertEqual(self.storage.size("unicode_file.txt"), 2) self.storage.save("file.dat", ContentFile(b"\xf1\xf1")) self.assertEqual(self.storage.size("file.dat"), 2) def test_listdir(self): self.assertEqual(self.storage.listdir(""), ([], [])) self.storage.save("file_a.txt", ContentFile("test")) self.storage.save("file_b.txt", ContentFile("test")) self.storage.save("dir/file_c.txt", ContentFile("test")) dirs, files = self.storage.listdir("") self.assertEqual(sorted(files), ["file_a.txt", "file_b.txt"]) self.assertEqual(dirs, ["dir"]) def test_list_relative_path(self): self.storage.save("a/file.txt", ContentFile("test")) _dirs, files = self.storage.listdir("./a/./.") self.assertEqual(files, ["file.txt"]) def test_exists(self): self.storage.save("dir/subdir/file.txt", ContentFile("test")) self.assertTrue(self.storage.exists("dir")) self.assertTrue(self.storage.exists("dir/subdir")) self.assertTrue(self.storage.exists("dir/subdir/file.txt")) def test_delete(self): """Deletion handles both files and directory trees.""" self.storage.save("dir/subdir/file.txt", ContentFile("test")) self.storage.save("dir/subdir/other_file.txt", ContentFile("test")) self.assertTrue(self.storage.exists("dir/subdir/file.txt")) self.assertTrue(self.storage.exists("dir/subdir/other_file.txt")) self.storage.delete("dir/subdir/other_file.txt") self.assertFalse(self.storage.exists("dir/subdir/other_file.txt")) self.storage.delete("dir/subdir") self.assertFalse(self.storage.exists("dir/subdir/file.txt")) self.assertFalse(self.storage.exists("dir/subdir")) def test_delete_missing_file(self): self.storage.delete("missing_file.txt") self.storage.delete("missing_dir/missing_file.txt") def test_file_node_cannot_have_children(self): """Navigate to children of a file node raises FileExistsError.""" self.storage.save("file.txt", ContentFile("test")) self.assertRaises(FileExistsError, self.storage.listdir, "file.txt/child_dir") self.assertRaises( FileExistsError, self.storage.save, "file.txt/child_file.txt", ContentFile("test"), ) @override_settings(MEDIA_URL=None) def test_url(self): self.assertRaises(ValueError, self.storage.url, ("file.txt",)) storage = InMemoryStorage(base_url="http://www.example.com") self.assertEqual(storage.url("file.txt"), "http://www.example.com/file.txt") def test_url_with_none_filename(self): storage = InMemoryStorage(base_url="/test_media_url/") self.assertEqual(storage.url(None), "/test_media_url/") class MemoryStorageTimesTests(unittest.TestCase): def setUp(self): self.storage = InMemoryStorage() def test_file_modified_time(self): """ File modified time should change after file changing """ self.storage.save("file.txt", ContentFile("test")) modified_time = self.storage.get_modified_time("file.txt") time.sleep(0.1) with self.storage.open("file.txt", "w") as fd: fd.write("new content") new_modified_time = self.storage.get_modified_time("file.txt") self.assertTrue(new_modified_time > modified_time) def test_file_accessed_time(self): """File accessed time should change after consecutive opening.""" self.storage.save("file.txt", ContentFile("test")) accessed_time = self.storage.get_accessed_time("file.txt") time.sleep(0.1) self.storage.open("file.txt", "r") new_accessed_time = self.storage.get_accessed_time("file.txt") self.assertGreater(new_accessed_time, accessed_time) def test_file_created_time(self): """File creation time should not change after I/O operations.""" self.storage.save("file.txt", ContentFile("test")) created_time = self.storage.get_created_time("file.txt") time.sleep(0.1) # File opening doesn't change creation time. file = self.storage.open("file.txt", "r") after_open_created_time = self.storage.get_created_time("file.txt") self.assertEqual(after_open_created_time, created_time) # Writing to a file doesn't change its creation time. file.write("New test") self.storage.save("file.txt", file) after_write_created_time = self.storage.get_created_time("file.txt") self.assertEqual(after_write_created_time, created_time) def test_directory_times_changing_after_file_creation(self): """ Directory modified and accessed time should change when a new file is created inside. """ self.storage.save("dir/file1.txt", ContentFile("test")) created_time = self.storage.get_created_time("dir") modified_time = self.storage.get_modified_time("dir") accessed_time = self.storage.get_accessed_time("dir") time.sleep(0.1) self.storage.save("dir/file2.txt", ContentFile("test")) new_modified_time = self.storage.get_modified_time("dir") new_accessed_time = self.storage.get_accessed_time("dir") after_file_creation_created_time = self.storage.get_created_time("dir") self.assertGreater(new_modified_time, modified_time) self.assertGreater(new_accessed_time, accessed_time) self.assertEqual(created_time, after_file_creation_created_time) def test_directory_times_changing_after_file_deletion(self): """ Directory modified and accessed time should change when a new file is deleted inside. """ self.storage.save("dir/file.txt", ContentFile("test")) created_time = self.storage.get_created_time("dir") modified_time = self.storage.get_modified_time("dir") accessed_time = self.storage.get_accessed_time("dir") time.sleep(0.1) self.storage.delete("dir/file.txt") new_modified_time = self.storage.get_modified_time("dir") new_accessed_time = self.storage.get_accessed_time("dir") after_file_deletion_created_time = self.storage.get_created_time("dir") self.assertGreater(new_modified_time, modified_time) self.assertGreater(new_accessed_time, accessed_time) self.assertEqual(created_time, after_file_deletion_created_time) class InMemoryStorageTests(SimpleTestCase): def test_deconstruction(self): storage = InMemoryStorage() path, args, kwargs = storage.deconstruct() self.assertEqual(path, "django.core.files.storage.InMemoryStorage") self.assertEqual(args, ()) self.assertEqual(kwargs, {}) kwargs_orig = { "location": "/custom_path", "base_url": "http://myfiles.example.com/", "file_permissions_mode": "0o755", "directory_permissions_mode": "0o600", } storage = InMemoryStorage(**kwargs_orig) path, args, kwargs = storage.deconstruct() self.assertEqual(kwargs, kwargs_orig) @override_settings( MEDIA_ROOT="media_root", MEDIA_URL="media_url/", FILE_UPLOAD_PERMISSIONS=0o777, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o777, ) def test_setting_changed(self): """ Properties using settings values as defaults should be updated on referenced settings change while specified values should be unchanged. """ storage = InMemoryStorage( location="explicit_location", base_url="explicit_base_url/", file_permissions_mode=0o666, directory_permissions_mode=0o666, ) defaults_storage = InMemoryStorage() settings = { "MEDIA_ROOT": "overridden_media_root", "MEDIA_URL": "/overridden_media_url/", "FILE_UPLOAD_PERMISSIONS": 0o333, "FILE_UPLOAD_DIRECTORY_PERMISSIONS": 0o333, } with self.settings(**settings): self.assertEqual(storage.base_location, "explicit_location") self.assertIn("explicit_location", storage.location) self.assertEqual(storage.base_url, "explicit_base_url/") self.assertEqual(storage.file_permissions_mode, 0o666) self.assertEqual(storage.directory_permissions_mode, 0o666) self.assertEqual(defaults_storage.base_location, settings["MEDIA_ROOT"]) self.assertIn(settings["MEDIA_ROOT"], defaults_storage.location) self.assertEqual(defaults_storage.base_url, settings["MEDIA_URL"]) self.assertEqual( defaults_storage.file_permissions_mode, settings["FILE_UPLOAD_PERMISSIONS"], ) self.assertEqual( defaults_storage.directory_permissions_mode, settings["FILE_UPLOAD_DIRECTORY_PERMISSIONS"], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/file_storage/__init__.py
tests/file_storage/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/file_storage/tests.py
tests/file_storage/tests.py
import datetime import os import shutil import sys import tempfile import threading import time import unittest from io import StringIO from pathlib import Path from urllib.request import urlopen from django.conf import DEFAULT_STORAGE_ALIAS, STATICFILES_STORAGE_ALIAS from django.core.cache import cache from django.core.exceptions import SuspiciousFileOperation from django.core.files.base import ContentFile, File from django.core.files.storage import FileSystemStorage, InvalidStorageError from django.core.files.storage import Storage as BaseStorage from django.core.files.storage import StorageHandler, default_storage, storages from django.core.files.uploadedfile import ( InMemoryUploadedFile, SimpleUploadedFile, TemporaryUploadedFile, ) from django.db.models import FileField from django.db.models.fields.files import FileDescriptor from django.test import LiveServerTestCase, SimpleTestCase, TestCase, override_settings from django.test.utils import requires_tz_support from django.urls import NoReverseMatch, reverse_lazy from django.utils import timezone from django.utils._os import symlinks_supported from django.utils.functional import empty from .models import ( Storage, callable_default_storage, callable_storage, temp_storage, temp_storage_location, ) FILE_SUFFIX_REGEX = "[A-Za-z0-9]{7}" class FileSystemStorageTests(unittest.TestCase): def test_deconstruction(self): path, args, kwargs = temp_storage.deconstruct() self.assertEqual(path, "django.core.files.storage.FileSystemStorage") self.assertEqual(args, ()) self.assertEqual(kwargs, {"location": temp_storage_location}) kwargs_orig = { "location": temp_storage_location, "base_url": "http://myfiles.example.com/", } storage = FileSystemStorage(**kwargs_orig) path, args, kwargs = storage.deconstruct() self.assertEqual(kwargs, kwargs_orig) def test_lazy_base_url_init(self): """ FileSystemStorage.__init__() shouldn't evaluate base_url. """ storage = FileSystemStorage(base_url=reverse_lazy("app:url")) with self.assertRaises(NoReverseMatch): storage.url(storage.base_url) class FileStorageTests(SimpleTestCase): storage_class = FileSystemStorage def setUp(self): self.temp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.temp_dir) self.storage = self.storage_class( location=self.temp_dir, base_url="/test_media_url/" ) def test_empty_location(self): """ Makes sure an exception is raised if the location is empty """ storage = self.storage_class(location="") self.assertEqual(storage.base_location, "") self.assertEqual(storage.location, os.getcwd()) def test_file_access_options(self): """ Standard file access options are available, and work as expected. """ self.assertFalse(self.storage.exists("storage_test")) f = self.storage.open("storage_test", "w") f.write("storage contents") f.close() self.assertTrue(self.storage.exists("storage_test")) f = self.storage.open("storage_test", "r") self.assertEqual(f.read(), "storage contents") f.close() self.storage.delete("storage_test") self.assertFalse(self.storage.exists("storage_test")) def _test_file_time_getter(self, getter): # Check for correct behavior under both USE_TZ=True and USE_TZ=False. # The tests are similar since they both set up a situation where the # system time zone, Django's TIME_ZONE, and UTC are distinct. self._test_file_time_getter_tz_handling_on(getter) self._test_file_time_getter_tz_handling_off(getter) @override_settings(USE_TZ=True, TIME_ZONE="Africa/Algiers") def _test_file_time_getter_tz_handling_on(self, getter): # Django's TZ (and hence the system TZ) is set to Africa/Algiers which # is UTC+1 and has no DST change. We can set the Django TZ to something # else so that UTC, Django's TIME_ZONE, and the system timezone are all # different. now_in_algiers = timezone.make_aware(datetime.datetime.now()) with timezone.override(timezone.get_fixed_timezone(-300)): # At this point the system TZ is +1 and the Django TZ # is -5. The following will be aware in UTC. now = timezone.now() self.assertFalse(self.storage.exists("test.file.tz.on")) f = ContentFile("custom contents") f_name = self.storage.save("test.file.tz.on", f) self.addCleanup(self.storage.delete, f_name) dt = getter(f_name) # dt should be aware, in UTC self.assertTrue(timezone.is_aware(dt)) self.assertEqual(now.tzname(), dt.tzname()) # The three timezones are indeed distinct. naive_now = datetime.datetime.now() algiers_offset = now_in_algiers.tzinfo.utcoffset(naive_now) django_offset = timezone.get_current_timezone().utcoffset(naive_now) utc_offset = datetime.UTC.utcoffset(naive_now) self.assertGreater(algiers_offset, utc_offset) self.assertLess(django_offset, utc_offset) # dt and now should be the same effective time. self.assertLess(abs(dt - now), datetime.timedelta(seconds=2)) @override_settings(USE_TZ=False, TIME_ZONE="Africa/Algiers") def _test_file_time_getter_tz_handling_off(self, getter): # Django's TZ (and hence the system TZ) is set to Africa/Algiers which # is UTC+1 and has no DST change. We can set the Django TZ to something # else so that UTC, Django's TIME_ZONE, and the system timezone are all # different. now_in_algiers = timezone.make_aware(datetime.datetime.now()) with timezone.override(timezone.get_fixed_timezone(-300)): # At this point the system TZ is +1 and the Django TZ # is -5. self.assertFalse(self.storage.exists("test.file.tz.off")) f = ContentFile("custom contents") f_name = self.storage.save("test.file.tz.off", f) self.addCleanup(self.storage.delete, f_name) dt = getter(f_name) # dt should be naive, in system (+1) TZ self.assertTrue(timezone.is_naive(dt)) # The three timezones are indeed distinct. naive_now = datetime.datetime.now() algiers_offset = now_in_algiers.tzinfo.utcoffset(naive_now) django_offset = timezone.get_current_timezone().utcoffset(naive_now) utc_offset = datetime.UTC.utcoffset(naive_now) self.assertGreater(algiers_offset, utc_offset) self.assertLess(django_offset, utc_offset) # dt and naive_now should be the same effective time. self.assertLess(abs(dt - naive_now), datetime.timedelta(seconds=2)) # If we convert dt to an aware object using the Algiers # timezone then it should be the same effective time to # now_in_algiers. _dt = timezone.make_aware(dt, now_in_algiers.tzinfo) self.assertLess(abs(_dt - now_in_algiers), datetime.timedelta(seconds=2)) def test_file_get_accessed_time(self): """ File storage returns a Datetime object for the last accessed time of a file. """ self.assertFalse(self.storage.exists("test.file")) f = ContentFile("custom contents") f_name = self.storage.save("test.file", f) self.addCleanup(self.storage.delete, f_name) path = self.storage.path(f_name) atime = self.storage.get_accessed_time(f_name) self.assertAlmostEqual( atime, datetime.datetime.fromtimestamp(os.path.getatime(path)), delta=datetime.timedelta(seconds=1), ) self.assertAlmostEqual( atime, timezone.now(), delta=datetime.timedelta(seconds=1), ) @requires_tz_support def test_file_get_accessed_time_timezone(self): self._test_file_time_getter(self.storage.get_accessed_time) def test_file_get_created_time(self): """ File storage returns a datetime for the creation time of a file. """ self.assertFalse(self.storage.exists("test.file")) f = ContentFile("custom contents") f_name = self.storage.save("test.file", f) self.addCleanup(self.storage.delete, f_name) path = self.storage.path(f_name) ctime = self.storage.get_created_time(f_name) self.assertAlmostEqual( ctime, datetime.datetime.fromtimestamp(os.path.getctime(path)), delta=datetime.timedelta(seconds=1), ) self.assertAlmostEqual( ctime, timezone.now(), delta=datetime.timedelta(seconds=1), ) @requires_tz_support def test_file_get_created_time_timezone(self): self._test_file_time_getter(self.storage.get_created_time) def test_file_get_modified_time(self): """ File storage returns a datetime for the last modified time of a file. """ self.assertFalse(self.storage.exists("test.file")) f = ContentFile("custom contents") f_name = self.storage.save("test.file", f) self.addCleanup(self.storage.delete, f_name) path = self.storage.path(f_name) mtime = self.storage.get_modified_time(f_name) self.assertAlmostEqual( mtime, datetime.datetime.fromtimestamp(os.path.getmtime(path)), delta=datetime.timedelta(seconds=1), ) self.assertAlmostEqual( mtime, timezone.now(), delta=datetime.timedelta(seconds=1), ) @requires_tz_support def test_file_get_modified_time_timezone(self): self._test_file_time_getter(self.storage.get_modified_time) def test_file_save_without_name(self): """ File storage extracts the filename from the content object if no name is given explicitly. """ self.assertFalse(self.storage.exists("test.file")) f = ContentFile("custom contents") f.name = "test.file" storage_f_name = self.storage.save(None, f) self.assertEqual(storage_f_name, f.name) self.assertTrue(os.path.exists(os.path.join(self.temp_dir, f.name))) self.storage.delete(storage_f_name) def test_file_save_with_path(self): """ Saving a pathname should create intermediate directories as necessary. """ self.assertFalse(self.storage.exists("path/to")) self.storage.save("path/to/test.file", ContentFile("file saved with path")) self.assertTrue(self.storage.exists("path/to")) with self.storage.open("path/to/test.file") as f: self.assertEqual(f.read(), b"file saved with path") self.assertTrue( os.path.exists(os.path.join(self.temp_dir, "path", "to", "test.file")) ) self.storage.delete("path/to/test.file") @unittest.skipUnless( symlinks_supported(), "Must be able to symlink to run this test." ) def test_file_save_broken_symlink(self): """A new path is created on save when a broken symlink is supplied.""" nonexistent_file_path = os.path.join(self.temp_dir, "nonexistent.txt") broken_symlink_file_name = "symlink.txt" broken_symlink_path = os.path.join(self.temp_dir, broken_symlink_file_name) os.symlink(nonexistent_file_path, broken_symlink_path) f = ContentFile("some content") f_name = self.storage.save(broken_symlink_file_name, f) self.assertIs(os.path.exists(os.path.join(self.temp_dir, f_name)), True) def test_save_doesnt_close(self): with TemporaryUploadedFile("test", "text/plain", 1, "utf8") as file: file.write(b"1") file.seek(0) self.assertFalse(file.closed) self.storage.save("path/to/test.file", file) self.assertFalse(file.closed) self.assertFalse(file.file.closed) file = InMemoryUploadedFile(StringIO("1"), "", "test", "text/plain", 1, "utf8") with file: self.assertFalse(file.closed) self.storage.save("path/to/test.file", file) self.assertFalse(file.closed) self.assertFalse(file.file.closed) def test_file_path(self): """ File storage returns the full path of a file """ self.assertFalse(self.storage.exists("test.file")) f = ContentFile("custom contents") f_name = self.storage.save("test.file", f) self.assertEqual(self.storage.path(f_name), os.path.join(self.temp_dir, f_name)) self.storage.delete(f_name) def test_file_url(self): """ File storage returns a url to access a given file from the web. """ self.assertEqual( self.storage.url("test.file"), self.storage.base_url + "test.file" ) # should encode special chars except ~!*()' # like encodeURIComponent() JavaScript function do self.assertEqual( self.storage.url(r"~!*()'@#$%^&*abc`+ =.file"), "/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%20%3D.file", ) self.assertEqual(self.storage.url("ab\0c"), "/test_media_url/ab%00c") # should translate os path separator(s) to the url path separator self.assertEqual( self.storage.url("""a/b\\c.file"""), "/test_media_url/a/b/c.file" ) # #25905: remove leading slashes from file names to prevent unsafe url # output self.assertEqual(self.storage.url("/evil.com"), "/test_media_url/evil.com") self.assertEqual(self.storage.url(r"\evil.com"), "/test_media_url/evil.com") self.assertEqual(self.storage.url("///evil.com"), "/test_media_url/evil.com") self.assertEqual(self.storage.url(r"\\\evil.com"), "/test_media_url/evil.com") self.assertEqual(self.storage.url(None), "/test_media_url/") def test_base_url(self): """ File storage returns a url even when its base_url is unset or modified. """ self.storage.base_url = None with self.assertRaises(ValueError): self.storage.url("test.file") # #22717: missing ending slash in base_url should be auto-corrected storage = self.storage_class( location=self.temp_dir, base_url="/no_ending_slash" ) self.assertEqual( storage.url("test.file"), "%s%s" % (storage.base_url, "test.file") ) def test_listdir(self): """ File storage returns a tuple containing directories and files. """ self.assertFalse(self.storage.exists("storage_test_1")) self.assertFalse(self.storage.exists("storage_test_2")) self.assertFalse(self.storage.exists("storage_dir_1")) self.storage.save("storage_test_1", ContentFile("custom content")) self.storage.save("storage_test_2", ContentFile("custom content")) os.mkdir(os.path.join(self.temp_dir, "storage_dir_1")) self.addCleanup(self.storage.delete, "storage_test_1") self.addCleanup(self.storage.delete, "storage_test_2") for directory in ("", Path("")): with self.subTest(directory=directory): dirs, files = self.storage.listdir(directory) self.assertEqual(set(dirs), {"storage_dir_1"}) self.assertEqual(set(files), {"storage_test_1", "storage_test_2"}) def test_file_storage_prevents_directory_traversal(self): """ File storage prevents directory traversal (files can only be accessed if they're below the storage location). """ with self.assertRaises(SuspiciousFileOperation): self.storage.exists("..") with self.assertRaises(SuspiciousFileOperation): self.storage.exists("/etc/passwd") def test_file_storage_preserves_filename_case(self): """The storage backend should preserve case of filenames.""" # Create a storage backend associated with the mixed case name # directory. temp_dir2 = tempfile.mkdtemp(suffix="aBc") self.addCleanup(shutil.rmtree, temp_dir2) other_temp_storage = self.storage_class(location=temp_dir2) # Ask that storage backend to store a file with a mixed case filename. mixed_case = "CaSe_SeNsItIvE" file = other_temp_storage.open(mixed_case, "w") file.write("storage contents") file.close() self.assertEqual( os.path.join(temp_dir2, mixed_case), other_temp_storage.path(mixed_case), ) other_temp_storage.delete(mixed_case) def test_makedirs_race_handling(self): """ File storage should be robust against directory creation race conditions. """ real_makedirs = os.makedirs # Monkey-patch os.makedirs, to simulate a normal call, a raced call, # and an error. def fake_makedirs(path, mode=0o777, exist_ok=False): if path == os.path.join(self.temp_dir, "normal"): real_makedirs(path, mode, exist_ok) elif path == os.path.join(self.temp_dir, "raced"): real_makedirs(path, mode, exist_ok) if not exist_ok: raise FileExistsError() elif path == os.path.join(self.temp_dir, "error"): raise PermissionError() else: self.fail("unexpected argument %r" % path) try: os.makedirs = fake_makedirs self.storage.save("normal/test.file", ContentFile("saved normally")) with self.storage.open("normal/test.file") as f: self.assertEqual(f.read(), b"saved normally") self.storage.save("raced/test.file", ContentFile("saved with race")) with self.storage.open("raced/test.file") as f: self.assertEqual(f.read(), b"saved with race") # Exceptions aside from FileExistsError are raised. with self.assertRaises(PermissionError): self.storage.save("error/test.file", ContentFile("not saved")) finally: os.makedirs = real_makedirs def test_remove_race_handling(self): """ File storage should be robust against file removal race conditions. """ real_remove = os.remove # Monkey-patch os.remove, to simulate a normal call, a raced call, # and an error. def fake_remove(path): if path == os.path.join(self.temp_dir, "normal.file"): real_remove(path) elif path == os.path.join(self.temp_dir, "raced.file"): real_remove(path) raise FileNotFoundError() elif path == os.path.join(self.temp_dir, "error.file"): raise PermissionError() else: self.fail("unexpected argument %r" % path) try: os.remove = fake_remove self.storage.save("normal.file", ContentFile("delete normally")) self.storage.delete("normal.file") self.assertFalse(self.storage.exists("normal.file")) self.storage.save("raced.file", ContentFile("delete with race")) self.storage.delete("raced.file") self.assertFalse(self.storage.exists("normal.file")) # Exceptions aside from FileNotFoundError are raised. self.storage.save("error.file", ContentFile("delete with error")) with self.assertRaises(PermissionError): self.storage.delete("error.file") finally: os.remove = real_remove def test_file_chunks_error(self): """ Test behavior when file.chunks() is raising an error """ f1 = ContentFile("chunks fails") def failing_chunks(): raise OSError f1.chunks = failing_chunks with self.assertRaises(OSError): self.storage.save("error.file", f1) def test_delete_no_name(self): """ Calling delete with an empty name should not try to remove the base storage directory, but fail loudly (#20660). """ msg = "The name must be given to delete()." with self.assertRaisesMessage(ValueError, msg): self.storage.delete(None) with self.assertRaisesMessage(ValueError, msg): self.storage.delete("") def test_delete_deletes_directories(self): tmp_dir = tempfile.mkdtemp(dir=self.storage.location) self.storage.delete(tmp_dir) self.assertFalse(os.path.exists(tmp_dir)) @override_settings( MEDIA_ROOT="media_root", MEDIA_URL="media_url/", FILE_UPLOAD_PERMISSIONS=0o777, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o777, ) def test_setting_changed(self): """ Properties using settings values as defaults should be updated on referenced settings change while specified values should be unchanged. """ storage = self.storage_class( location="explicit_location", base_url="explicit_base_url/", file_permissions_mode=0o666, directory_permissions_mode=0o666, ) defaults_storage = self.storage_class() settings = { "MEDIA_ROOT": "overridden_media_root", "MEDIA_URL": "/overridden_media_url/", "FILE_UPLOAD_PERMISSIONS": 0o333, "FILE_UPLOAD_DIRECTORY_PERMISSIONS": 0o333, } with self.settings(**settings): self.assertEqual(storage.base_location, "explicit_location") self.assertIn("explicit_location", storage.location) self.assertEqual(storage.base_url, "explicit_base_url/") self.assertEqual(storage.file_permissions_mode, 0o666) self.assertEqual(storage.directory_permissions_mode, 0o666) self.assertEqual(defaults_storage.base_location, settings["MEDIA_ROOT"]) self.assertIn(settings["MEDIA_ROOT"], defaults_storage.location) self.assertEqual(defaults_storage.base_url, settings["MEDIA_URL"]) self.assertEqual( defaults_storage.file_permissions_mode, settings["FILE_UPLOAD_PERMISSIONS"], ) self.assertEqual( defaults_storage.directory_permissions_mode, settings["FILE_UPLOAD_DIRECTORY_PERMISSIONS"], ) def test_file_methods_pathlib_path(self): p = Path("test.file") self.assertFalse(self.storage.exists(p)) f = ContentFile("custom contents") f_name = self.storage.save(p, f) # Storage basic methods. self.assertEqual(self.storage.path(p), os.path.join(self.temp_dir, p)) self.assertEqual(self.storage.size(p), 15) self.assertEqual(self.storage.url(p), self.storage.base_url + f_name) with self.storage.open(p) as f: self.assertEqual(f.read(), b"custom contents") self.addCleanup(self.storage.delete, p) class CustomStorage(FileSystemStorage): def get_available_name(self, name, max_length=None): """ Append numbers to duplicate files rather than underscores, like Trac. """ basename, *ext = os.path.splitext(name) number = 2 while self.exists(name): name = "".join([basename, ".", str(number)] + ext) number += 1 return name class CustomStorageTests(FileStorageTests): storage_class = CustomStorage def test_custom_get_available_name(self): first = self.storage.save("custom_storage", ContentFile("custom contents")) self.assertEqual(first, "custom_storage") second = self.storage.save("custom_storage", ContentFile("more contents")) self.assertEqual(second, "custom_storage.2") self.storage.delete(first) self.storage.delete(second) class OverwritingStorageTests(FileStorageTests): storage_class = FileSystemStorage def setUp(self): self.temp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.temp_dir) self.storage = self.storage_class( location=self.temp_dir, base_url="/test_media_url/", allow_overwrite=True ) def test_save_overwrite_behavior(self): """Saving to same file name twice overwrites the first file.""" name = "test.file" self.assertFalse(self.storage.exists(name)) content_1 = b"content one" content_2 = b"second content" f_1 = ContentFile(content_1) f_2 = ContentFile(content_2) stored_name_1 = self.storage.save(name, f_1) try: self.assertEqual(stored_name_1, name) self.assertTrue(self.storage.exists(name)) with self.storage.open(name) as fp: self.assertEqual(fp.read(), content_1) stored_name_2 = self.storage.save(name, f_2) self.assertEqual(stored_name_2, name) self.assertTrue(self.storage.exists(name)) with self.storage.open(name) as fp: self.assertEqual(fp.read(), content_2) finally: self.storage.delete(name) def test_save_overwrite_behavior_truncate(self): name = "test.file" original_content = b"content extra extra extra" new_smaller_content = b"content" self.storage.save(name, ContentFile(original_content)) try: self.storage.save(name, ContentFile(new_smaller_content)) with self.storage.open(name) as fp: self.assertEqual(fp.read(), new_smaller_content) finally: self.storage.delete(name) def test_save_overwrite_behavior_temp_file(self): """Saving to same file name twice overwrites the first file.""" name = "test.file" self.assertFalse(self.storage.exists(name)) content_1 = b"content one" content_2 = b"second content" f_1 = TemporaryUploadedFile("tmp1", "text/plain", 11, "utf8") self.addCleanup(f_1.close) f_1.write(content_1) f_1.seek(0) f_2 = TemporaryUploadedFile("tmp2", "text/plain", 14, "utf8") self.addCleanup(f_2.close) f_2.write(content_2) f_2.seek(0) stored_name_1 = self.storage.save(name, f_1) try: self.assertEqual(stored_name_1, name) self.assertTrue(os.path.exists(os.path.join(self.temp_dir, name))) with self.storage.open(name) as fp: self.assertEqual(fp.read(), content_1) stored_name_2 = self.storage.save(name, f_2) self.assertEqual(stored_name_2, name) self.assertTrue(os.path.exists(os.path.join(self.temp_dir, name))) with self.storage.open(name) as fp: self.assertEqual(fp.read(), content_2) finally: self.storage.delete(name) def test_file_name_truncation(self): name = "test_long_file_name.txt" file = ContentFile(b"content") stored_name = self.storage.save(name, file, max_length=10) self.addCleanup(self.storage.delete, stored_name) self.assertEqual(stored_name, "test_l.txt") self.assertEqual(len(stored_name), 10) def test_file_name_truncation_extension_too_long(self): name = "file_name.longext" file = ContentFile(b"content") with self.assertRaisesMessage( SuspiciousFileOperation, "Storage can not find an available filename" ): self.storage.save(name, file, max_length=5) class DiscardingFalseContentStorage(FileSystemStorage): def _save(self, name, content): if content: return super()._save(name, content) return "" class DiscardingFalseContentStorageTests(FileStorageTests): storage_class = DiscardingFalseContentStorage def test_custom_storage_discarding_empty_content(self): """ When Storage.save() wraps a file-like object in File, it should include the name argument so that bool(file) evaluates to True (#26495). """ output = StringIO("content") self.storage.save("tests/stringio", output) self.assertTrue(self.storage.exists("tests/stringio")) with self.storage.open("tests/stringio") as f: self.assertEqual(f.read(), b"content") class FileFieldStorageTests(TestCase): def tearDown(self): if os.path.exists(temp_storage_location): shutil.rmtree(temp_storage_location) def _storage_max_filename_length(self, storage): """ Query filesystem for maximum filename length (e.g. AUFS has 242). """ dir_to_test = storage.location while not os.path.exists(dir_to_test): dir_to_test = os.path.dirname(dir_to_test) try: return os.pathconf(dir_to_test, "PC_NAME_MAX") except Exception: return 255 # Should be safe on most backends def test_files(self): self.assertIsInstance(Storage.normal, FileDescriptor) # An object without a file has limited functionality. obj1 = Storage() self.assertEqual(obj1.normal.name, "") with self.assertRaises(ValueError): obj1.normal.size # Saving a file enables full functionality. obj1.normal.save("django_test.txt", ContentFile("content")) self.assertEqual(obj1.normal.name, "tests/django_test.txt") self.assertEqual(obj1.normal.size, 7) self.assertEqual(obj1.normal.read(), b"content") obj1.normal.close() # File objects can be assigned to FileField attributes, but shouldn't # get committed until the model it's attached to is saved. obj1.normal = SimpleUploadedFile("assignment.txt", b"content") dirs, files = temp_storage.listdir("tests") self.assertEqual(dirs, []) self.assertNotIn("assignment.txt", files) obj1.save() dirs, files = temp_storage.listdir("tests") self.assertEqual(sorted(files), ["assignment.txt", "django_test.txt"]) # Save another file with the same name. obj2 = Storage() obj2.normal.save("django_test.txt", ContentFile("more content")) obj2_name = obj2.normal.name self.assertRegex(obj2_name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX) self.assertEqual(obj2.normal.size, 12) obj2.normal.close() # Deleting an object does not delete the file it uses. obj2.delete() obj2.normal.save("django_test.txt", ContentFile("more content")) self.assertNotEqual(obj2_name, obj2.normal.name) self.assertRegex( obj2.normal.name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX ) obj2.normal.close() def test_filefield_read(self): # Files can be read in a little at a time, if necessary. obj = Storage.objects.create( normal=SimpleUploadedFile("assignment.txt", b"content") ) obj.normal.open() self.assertEqual(obj.normal.read(3), b"con") self.assertEqual(obj.normal.read(), b"tent") self.assertEqual( list(obj.normal.chunks(chunk_size=2)), [b"co", b"nt", b"en", b"t"] ) obj.normal.close() def test_filefield_write(self): # Files can be written to. obj = Storage.objects.create( normal=SimpleUploadedFile("rewritten.txt", b"content") ) with obj.normal as normal: normal.open("wb") normal.write(b"updated") obj.refresh_from_db() self.assertEqual(obj.normal.read(), b"updated") obj.normal.close() def test_filefield_reopen(self): obj = Storage.objects.create( normal=SimpleUploadedFile("reopen.txt", b"content") ) with obj.normal as normal: normal.open() obj.normal.open() obj.normal.file.seek(0) obj.normal.close() def test_duplicate_filename(self): # Multiple files with the same name get _(7 random chars) appended to # them. tests = [ ("multiple_files", "txt"), ("multiple_files_many_extensions", "tar.gz"), ] for filename, extension in tests:
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/file_storage/urls.py
tests/file_storage/urls.py
from django.http import HttpResponse from django.urls import path urlpatterns = [ path("", lambda req: HttpResponse("example view")), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/update_only_fields/models.py
tests/update_only_fields/models.py
from django.db import models class Account(models.Model): num = models.IntegerField() class Person(models.Model): GENDER_CHOICES = ( ("M", "Male"), ("F", "Female"), ) name = models.CharField(max_length=20) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) pid = models.IntegerField(null=True, default=None) class Employee(Person): employee_num = models.IntegerField(default=0) profile = models.ForeignKey( "Profile", models.SET_NULL, related_name="profiles", null=True ) accounts = models.ManyToManyField("Account", related_name="employees", blank=True) class NonConcreteField(models.IntegerField): def db_type(self, connection): return None def get_attname_column(self): attname, _ = super().get_attname_column() return attname, None class Profile(models.Model): name = models.CharField(max_length=200) salary = models.FloatField(default=1000.0) non_concrete = NonConcreteField() class ProxyEmployee(Employee): class Meta: proxy = True
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/update_only_fields/__init__.py
tests/update_only_fields/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/update_only_fields/tests.py
tests/update_only_fields/tests.py
from django.core.exceptions import ObjectNotUpdated from django.db import DatabaseError, connection, transaction from django.db.models import F from django.db.models.signals import post_save, pre_save from django.test import TestCase from .models import Account, Employee, Person, Profile, ProxyEmployee class UpdateOnlyFieldsTests(TestCase): msg = ( "The following fields do not exist in this model, are m2m " "fields, primary keys, or are non-concrete fields: %s" ) def test_update_fields_basic(self): s = Person.objects.create(name="Sara", gender="F") self.assertEqual(s.gender, "F") s.gender = "M" s.name = "Ian" s.save(update_fields=["name"]) s = Person.objects.get(pk=s.pk) self.assertEqual(s.gender, "F") self.assertEqual(s.name, "Ian") def test_update_fields_deferred(self): s = Person.objects.create(name="Sara", gender="F", pid=22) self.assertEqual(s.gender, "F") s1 = Person.objects.defer("gender", "pid").get(pk=s.pk) s1.name = "Emily" s1.gender = "M" with self.assertNumQueries(1): s1.save() s2 = Person.objects.get(pk=s1.pk) self.assertEqual(s2.name, "Emily") self.assertEqual(s2.gender, "M") def test_update_fields_only_1(self): s = Person.objects.create(name="Sara", gender="F") self.assertEqual(s.gender, "F") s1 = Person.objects.only("name").get(pk=s.pk) s1.name = "Emily" s1.gender = "M" with self.assertNumQueries(1): s1.save() s2 = Person.objects.get(pk=s1.pk) self.assertEqual(s2.name, "Emily") self.assertEqual(s2.gender, "M") def test_update_fields_only_2(self): s = Person.objects.create(name="Sara", gender="F", pid=22) self.assertEqual(s.gender, "F") s1 = Person.objects.only("name").get(pk=s.pk) s1.name = "Emily" s1.gender = "M" with self.assertNumQueries(2): s1.save(update_fields=["pid"]) s2 = Person.objects.get(pk=s1.pk) self.assertEqual(s2.name, "Sara") self.assertEqual(s2.gender, "F") def test_update_fields_only_repeated(self): s = Person.objects.create(name="Sara", gender="F") self.assertEqual(s.gender, "F") s1 = Person.objects.only("name").get(pk=s.pk) s1.gender = "M" with self.assertNumQueries(1): s1.save() # save() should not fetch deferred fields s1 = Person.objects.only("name").get(pk=s.pk) with self.assertNumQueries(1): s1.save() def test_update_fields_inheritance_defer(self): profile_boss = Profile.objects.create(name="Boss", salary=3000) e1 = Employee.objects.create( name="Sara", gender="F", employee_num=1, profile=profile_boss ) e1 = Employee.objects.only("name").get(pk=e1.pk) e1.name = "Linda" with self.assertNumQueries(1): e1.save() self.assertEqual(Employee.objects.get(pk=e1.pk).name, "Linda") def test_update_fields_fk_defer(self): profile_boss = Profile.objects.create(name="Boss", salary=3000) profile_receptionist = Profile.objects.create(name="Receptionist", salary=1000) e1 = Employee.objects.create( name="Sara", gender="F", employee_num=1, profile=profile_boss ) e1 = Employee.objects.only("profile").get(pk=e1.pk) e1.profile = profile_receptionist with self.assertNumQueries(1): e1.save() self.assertEqual(Employee.objects.get(pk=e1.pk).profile, profile_receptionist) e1.profile_id = profile_boss.pk with self.assertNumQueries(1): e1.save() self.assertEqual(Employee.objects.get(pk=e1.pk).profile, profile_boss) def test_select_related_only_interaction(self): profile_boss = Profile.objects.create(name="Boss", salary=3000) e1 = Employee.objects.create( name="Sara", gender="F", employee_num=1, profile=profile_boss ) e1 = ( Employee.objects.only("profile__salary") .select_related("profile") .get(pk=e1.pk) ) profile_boss.name = "Clerk" profile_boss.salary = 1000 profile_boss.save() # The loaded salary of 3000 gets saved, the name of 'Clerk' isn't # overwritten. with self.assertNumQueries(1): e1.profile.save() reloaded_profile = Profile.objects.get(pk=profile_boss.pk) self.assertEqual(reloaded_profile.name, profile_boss.name) self.assertEqual(reloaded_profile.salary, 3000) def test_update_fields_m2m(self): profile_boss = Profile.objects.create(name="Boss", salary=3000) e1 = Employee.objects.create( name="Sara", gender="F", employee_num=1, profile=profile_boss ) a1 = Account.objects.create(num=1) a2 = Account.objects.create(num=2) e1.accounts.set([a1, a2]) with self.assertRaisesMessage(ValueError, self.msg % "accounts"): e1.save(update_fields=["accounts"]) def test_update_fields_inheritance(self): profile_boss = Profile.objects.create(name="Boss", salary=3000) profile_receptionist = Profile.objects.create(name="Receptionist", salary=1000) e1 = Employee.objects.create( name="Sara", gender="F", employee_num=1, profile=profile_boss ) e1.name = "Ian" e1.gender = "M" e1.save(update_fields=["name"]) e2 = Employee.objects.get(pk=e1.pk) self.assertEqual(e2.name, "Ian") self.assertEqual(e2.gender, "F") self.assertEqual(e2.profile, profile_boss) e2.profile = profile_receptionist e2.name = "Sara" e2.save(update_fields=["profile"]) e3 = Employee.objects.get(pk=e1.pk) self.assertEqual(e3.name, "Ian") self.assertEqual(e3.profile, profile_receptionist) with self.assertNumQueries(1): e3.profile = profile_boss e3.save(update_fields=["profile_id"]) e4 = Employee.objects.get(pk=e3.pk) self.assertEqual(e4.profile, profile_boss) self.assertEqual(e4.profile_id, profile_boss.pk) def test_update_fields_inheritance_with_proxy_model(self): profile_boss = Profile.objects.create(name="Boss", salary=3000) profile_receptionist = Profile.objects.create(name="Receptionist", salary=1000) e1 = ProxyEmployee.objects.create( name="Sara", gender="F", employee_num=1, profile=profile_boss ) e1.name = "Ian" e1.gender = "M" e1.save(update_fields=["name"]) e2 = ProxyEmployee.objects.get(pk=e1.pk) self.assertEqual(e2.name, "Ian") self.assertEqual(e2.gender, "F") self.assertEqual(e2.profile, profile_boss) e2.profile = profile_receptionist e2.name = "Sara" e2.save(update_fields=["profile"]) e3 = ProxyEmployee.objects.get(pk=e1.pk) self.assertEqual(e3.name, "Ian") self.assertEqual(e3.profile, profile_receptionist) def test_update_fields_signals(self): p = Person.objects.create(name="Sara", gender="F") pre_save_data = [] def pre_save_receiver(**kwargs): pre_save_data.append(kwargs["update_fields"]) pre_save.connect(pre_save_receiver) post_save_data = [] def post_save_receiver(**kwargs): post_save_data.append(kwargs["update_fields"]) post_save.connect(post_save_receiver) p.save(update_fields=["name"]) self.assertEqual(len(pre_save_data), 1) self.assertEqual(len(pre_save_data[0]), 1) self.assertIn("name", pre_save_data[0]) self.assertEqual(len(post_save_data), 1) self.assertEqual(len(post_save_data[0]), 1) self.assertIn("name", post_save_data[0]) pre_save.disconnect(pre_save_receiver) post_save.disconnect(post_save_receiver) def test_update_fields_incorrect_params(self): s = Person.objects.create(name="Sara", gender="F") with self.assertRaisesMessage(ValueError, self.msg % "first_name"): s.save(update_fields=["first_name"]) # "name" is treated as an iterable so the output is something like # "n, a, m, e" but the order isn't deterministic. with self.assertRaisesMessage(ValueError, self.msg % ""): s.save(update_fields="name") def test_empty_update_fields(self): s = Person.objects.create(name="Sara", gender="F") pre_save_data = [] def pre_save_receiver(**kwargs): pre_save_data.append(kwargs["update_fields"]) pre_save.connect(pre_save_receiver) post_save_data = [] def post_save_receiver(**kwargs): post_save_data.append(kwargs["update_fields"]) post_save.connect(post_save_receiver) # Save is skipped. with self.assertNumQueries(0): s.save(update_fields=[]) # Signals were skipped, too... self.assertEqual(len(pre_save_data), 0) self.assertEqual(len(post_save_data), 0) pre_save.disconnect(pre_save_receiver) post_save.disconnect(post_save_receiver) def test_num_queries_inheritance(self): s = Employee.objects.create(name="Sara", gender="F") s.employee_num = 1 s.name = "Emily" with self.assertNumQueries(1): s.save(update_fields=["employee_num"]) s = Employee.objects.get(pk=s.pk) self.assertEqual(s.employee_num, 1) self.assertEqual(s.name, "Sara") s.employee_num = 2 s.name = "Emily" with self.assertNumQueries(1): s.save(update_fields=["name"]) s = Employee.objects.get(pk=s.pk) self.assertEqual(s.name, "Emily") self.assertEqual(s.employee_num, 1) # A little sanity check that we actually did updates... self.assertEqual(Employee.objects.count(), 1) self.assertEqual(Person.objects.count(), 1) with self.assertNumQueries(2): s.save(update_fields=["name", "employee_num"]) def test_update_non_concrete_field(self): profile_boss = Profile.objects.create(name="Boss", salary=3000) with self.assertRaisesMessage(ValueError, self.msg % "non_concrete"): profile_boss.save(update_fields=["non_concrete"]) def test_update_pk_field(self): person_boss = Person.objects.create(name="Boss", gender="F") with self.assertRaisesMessage(ValueError, self.msg % "id"): person_boss.save(update_fields=["id"]) def test_update_inherited_pk_field(self): employee_boss = Employee.objects.create(name="Boss", gender="F") with self.assertRaisesMessage(ValueError, self.msg % "id"): employee_boss.save(update_fields=["id"]) def test_update_fields_not_updated(self): obj = Person.objects.create(name="Sara", gender="F") Person.objects.filter(pk=obj.pk).delete() msg = "Save with update_fields did not affect any rows." # Make sure backward compatibility with DatabaseError is preserved. exceptions = [DatabaseError, ObjectNotUpdated, Person.NotUpdated] for exception in exceptions: with ( self.subTest(exception), self.assertRaisesMessage(DatabaseError, msg), transaction.atomic(), ): obj.save(update_fields=["name"]) def test_update_fields_expression(self): obj = Person.objects.create(name="Valerie", gender="F", pid=42) updated_pid = F("pid") + 1 obj.pid = updated_pid obj.save(update_fields={"gender"}) self.assertIs(obj.pid, updated_pid) obj.save(update_fields={"pid"}) expected_num_queries = ( 0 if connection.features.can_return_rows_from_update else 1 ) with self.assertNumQueries(expected_num_queries): self.assertEqual(obj.pid, 43)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/test_data.py
tests/gis_tests/test_data.py
""" This module has the mock object definitions used to hold reference geometry for the GEOS and GDAL tests. """ import json import os from django.utils.functional import cached_property # Path where reference test data is located. TEST_DATA = os.path.join(os.path.dirname(__file__), "data") def tuplize(seq): "Turn all nested sequences to tuples in given sequence." if isinstance(seq, (list, tuple)): return tuple(tuplize(i) for i in seq) return seq def strconvert(d): "Converts all keys in dictionary to str type." return {str(k): v for k, v in d.items()} def get_ds_file(name, ext): return os.path.join(TEST_DATA, name, name + ".%s" % ext) class TestObj: """ Base testing object, turns keyword args into attributes. """ def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) class TestDS(TestObj): """ Object for testing GDAL data sources. """ def __init__(self, name, *, ext="shp", **kwargs): # Shapefile is default extension, unless specified otherwise. self.name = name self.ds = get_ds_file(name, ext) super().__init__(**kwargs) class TestGeom(TestObj): """ Testing object used for wrapping reference geometry data in GEOS/GDAL tests. """ def __init__(self, *, coords=None, centroid=None, ext_ring_cs=None, **kwargs): # Converting lists to tuples of certain keyword args # so coordinate test cases will match (JSON has no # concept of tuple). if coords: self.coords = tuplize(coords) if centroid: self.centroid = tuple(centroid) self.ext_ring_cs = ext_ring_cs and tuplize(ext_ring_cs) super().__init__(**kwargs) class TestGeomSet: """ Each attribute of this object is a list of `TestGeom` instances. """ def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, [TestGeom(**strconvert(kw)) for kw in value]) class TestDataMixin: """ Mixin used for GEOS/GDAL test cases that defines a `geometries` property, which returns and/or loads the reference geometry data. """ @cached_property def geometries(self): # Load up the test geometry data from fixture into global. with open(os.path.join(TEST_DATA, "geometries.json")) as f: geometries = json.load(f) return TestGeomSet(**strconvert(geometries))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/test_geoip2.py
tests/gis_tests/test_geoip2.py
import ipaddress import itertools import pathlib from unittest import mock, skipUnless from django.conf import settings from django.contrib.gis.geoip2 import HAS_GEOIP2 from django.contrib.gis.geos import GEOSGeometry from django.test import SimpleTestCase, override_settings if HAS_GEOIP2: import geoip2 from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception def build_geoip_path(*parts): return pathlib.Path(__file__).parent.joinpath("data/geoip2", *parts).resolve() @skipUnless(HAS_GEOIP2, "GeoIP2 is required.") @override_settings( GEOIP_CITY="GeoLite2-City-Test.mmdb", GEOIP_COUNTRY="GeoLite2-Country-Test.mmdb", ) class GeoLite2Test(SimpleTestCase): fqdn = "sky.uk" ipv4_str = "2.125.160.216" ipv6_str = "::ffff:027d:a0d8" ipv4_addr = ipaddress.ip_address(ipv4_str) ipv6_addr = ipaddress.ip_address(ipv6_str) query_values = (fqdn, ipv4_str, ipv6_str, ipv4_addr, ipv6_addr) expected_city = { "accuracy_radius": 100, "city": "Boxford", "continent_code": "EU", "continent_name": "Europe", "country_code": "GB", "country_name": "United Kingdom", "is_in_european_union": False, "latitude": 51.75, "longitude": -1.25, "metro_code": None, "postal_code": "OX1", "region_code": "ENG", "region_name": "England", "time_zone": "Europe/London", # Kept for backward compatibility. "dma_code": None, "region": "ENG", } expected_country = { "continent_code": "EU", "continent_name": "Europe", "country_code": "GB", "country_name": "United Kingdom", "is_in_european_union": False, } @classmethod def setUpClass(cls): # Avoid referencing __file__ at module level. cls.enterClassContext(override_settings(GEOIP_PATH=build_geoip_path())) # Always mock host lookup to avoid test breakage if DNS changes. cls.enterClassContext( mock.patch("socket.gethostbyname", return_value=cls.ipv4_str) ) super().setUpClass() def test_init(self): # Everything inferred from GeoIP path. g1 = GeoIP2() # Path passed explicitly. g2 = GeoIP2(settings.GEOIP_PATH, GeoIP2.MODE_AUTO) # Path provided as a string. g3 = GeoIP2(str(settings.GEOIP_PATH)) # Only passing in the location of one database. g4 = GeoIP2(settings.GEOIP_PATH / settings.GEOIP_CITY, country="") g5 = GeoIP2(settings.GEOIP_PATH / settings.GEOIP_COUNTRY, city="") for g in (g1, g2, g3, g4, g5): self.assertTrue(g._reader) # Improper parameters. bad_params = (23, "foo", 15.23) for bad in bad_params: with self.assertRaises(GeoIP2Exception): GeoIP2(cache=bad) if isinstance(bad, str): e = GeoIP2Exception else: e = TypeError with self.assertRaises(e): GeoIP2(bad, GeoIP2.MODE_AUTO) def test_no_database_file(self): invalid_path = pathlib.Path(__file__).parent.joinpath("data/invalid").resolve() msg = "Path must be a valid database or directory containing databases." with self.assertRaisesMessage(GeoIP2Exception, msg): GeoIP2(invalid_path) def test_bad_query(self): g = GeoIP2(city="<invalid>") functions = (g.city, g.geos, g.lat_lon, g.lon_lat) msg = "Invalid GeoIP city data file: " for function in functions: with self.subTest(function=function.__qualname__): with self.assertRaisesMessage(GeoIP2Exception, msg): function("example.com") functions += (g.country, g.country_code, g.country_name) values = (123, 123.45, b"", (), [], {}, set(), frozenset(), GeoIP2) msg = ( "GeoIP query must be a string or instance of IPv4Address or IPv6Address, " "not type" ) for function, value in itertools.product(functions, values): with self.subTest(function=function.__qualname__, type=type(value)): with self.assertRaisesMessage(TypeError, msg): function(value) def test_country(self): g = GeoIP2(city="<invalid>") self.assertIs(g.is_city, False) self.assertIs(g.is_country, True) for query in self.query_values: with self.subTest(query=query): self.assertEqual(g.country(query), self.expected_country) self.assertEqual( g.country_code(query), self.expected_country["country_code"] ) self.assertEqual( g.country_name(query), self.expected_country["country_name"] ) def test_country_using_city_database(self): g = GeoIP2(country="<invalid>") self.assertIs(g.is_city, True) self.assertIs(g.is_country, False) for query in self.query_values: with self.subTest(query=query): self.assertEqual(g.country(query), self.expected_country) self.assertEqual( g.country_code(query), self.expected_country["country_code"] ) self.assertEqual( g.country_name(query), self.expected_country["country_name"] ) def test_city(self): g = GeoIP2(country="<invalid>") self.assertIs(g.is_city, True) self.assertIs(g.is_country, False) for query in self.query_values: with self.subTest(query=query): self.assertEqual(g.city(query), self.expected_city) geom = g.geos(query) self.assertIsInstance(geom, GEOSGeometry) self.assertEqual(geom.srid, 4326) expected_lat = self.expected_city["latitude"] expected_lon = self.expected_city["longitude"] self.assertEqual(geom.tuple, (expected_lon, expected_lat)) self.assertEqual(g.lat_lon(query), (expected_lat, expected_lon)) self.assertEqual(g.lon_lat(query), (expected_lon, expected_lat)) # Country queries should still work. self.assertEqual(g.country(query), self.expected_country) self.assertEqual( g.country_code(query), self.expected_country["country_code"] ) self.assertEqual( g.country_name(query), self.expected_country["country_name"] ) def test_not_found(self): g1 = GeoIP2(city="<invalid>") g2 = GeoIP2(country="<invalid>") for function, query in itertools.product( (g1.country, g2.city), ("127.0.0.1", "::1") ): with self.subTest(function=function.__qualname__, query=query): msg = f"The address {query} is not in the database." with self.assertRaisesMessage(geoip2.errors.AddressNotFoundError, msg): function(query) def test_del(self): g = GeoIP2() reader = g._reader self.assertIs(reader._db_reader.closed, False) del g self.assertIs(reader._db_reader.closed, True) def test_repr(self): g = GeoIP2() m = g._metadata version = f"{m.binary_format_major_version}.{m.binary_format_minor_version}" self.assertEqual(repr(g), f"<GeoIP2 [v{version}] _path='{g._path}'>") @skipUnless(HAS_GEOIP2, "GeoIP2 is required.") @override_settings( GEOIP_CITY="GeoIP2-City-Test.mmdb", GEOIP_COUNTRY="GeoIP2-Country-Test.mmdb", ) class GeoIP2Test(GeoLite2Test): """Non-free GeoIP2 databases are supported.""" @skipUnless(HAS_GEOIP2, "GeoIP2 is required.") @override_settings( GEOIP_CITY="dbip-city-lite-test.mmdb", GEOIP_COUNTRY="dbip-country-lite-test.mmdb", ) class DBIPLiteTest(GeoLite2Test): """DB-IP Lite databases are supported.""" expected_city = GeoLite2Test.expected_city | { "accuracy_radius": None, "city": "London (Shadwell)", "latitude": 51.5181, "longitude": -0.0714189, "postal_code": None, "region_code": None, "time_zone": None, # Kept for backward compatibility. "region": None, } @skipUnless(HAS_GEOIP2, "GeoIP2 is required.") class ErrorTest(SimpleTestCase): def test_missing_path(self): msg = "GeoIP path must be provided via parameter or the GEOIP_PATH setting." with self.settings(GEOIP_PATH=None): with self.assertRaisesMessage(GeoIP2Exception, msg): GeoIP2() def test_unsupported_database(self): msg = "Unable to handle database edition: GeoLite2-ASN" with self.settings(GEOIP_PATH=build_geoip_path("GeoLite2-ASN-Test.mmdb")): with self.assertRaisesMessage(GeoIP2Exception, msg): GeoIP2()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/admin.py
tests/gis_tests/admin.py
try: from django.contrib.gis import admin except ImportError: from django.contrib import admin admin.GISModelAdmin = admin.ModelAdmin
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/test_spatialrefsys.py
tests/gis_tests/test_spatialrefsys.py
import re from django.contrib.gis.db.backends.base.models import SpatialRefSysMixin from django.db import connection from django.test import TestCase, skipUnlessDBFeature from django.utils.functional import cached_property test_srs = ( { "srid": 4326, "auth_name": ("EPSG", True), "auth_srid": 4326, # Only the beginning, because there are differences depending on # installed libs "srtext": 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84"', "proj_re": ( r"\+proj=longlat (\+datum=WGS84 |\+towgs84=0,0,0,0,0,0,0 )\+no_defs ?" ), "spheroid": "WGS 84", "name": "WGS 84", "geographic": True, "projected": False, "spatialite": True, # From proj's "cs2cs -le" and Wikipedia (semi-minor only) "ellipsoid": (6378137.0, 6356752.3, 298.257223563), "eprec": (1, 1, 9), "wkt": re.sub( r"[\s+]", "", """ GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0.01745329251994328, AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","4326"]] """, ), }, { "srid": 32140, "auth_name": ("EPSG", False), "auth_srid": 32140, "srtext": ( 'PROJCS["NAD83 / Texas South Central",GEOGCS["NAD83",' 'DATUM["North_American_Datum_1983",SPHEROID["GRS 1980"' ), "proj_re": ( r"\+proj=lcc (\+lat_1=30.28333333333333? |\+lat_2=28.38333333333333? " r"|\+lat_0=27.83333333333333? |" r"\+lon_0=-99 ){4}\+x_0=600000 \+y_0=4000000 (\+ellps=GRS80 )?" r"(\+datum=NAD83 |\+towgs84=0,0,0,0,0,0,0 )?\+units=m \+no_defs ?" ), "spheroid": "GRS 1980", "name": "NAD83 / Texas South Central", "geographic": False, "projected": True, "spatialite": False, # From proj's "cs2cs -le" and Wikipedia (semi-minor only) "ellipsoid": (6378137.0, 6356752.31414, 298.257222101), "eprec": (1, 5, 10), }, ) @skipUnlessDBFeature("has_spatialrefsys_table") class SpatialRefSysTest(TestCase): @cached_property def SpatialRefSys(self): return connection.ops.connection.ops.spatial_ref_sys() def test_get_units(self): epsg_4326 = next(f for f in test_srs if f["srid"] == 4326) unit, unit_name = self.SpatialRefSys().get_units(epsg_4326["wkt"]) self.assertEqual(unit_name, "degree") self.assertAlmostEqual(unit, 0.01745329251994328) def test_retrieve(self): """ Test retrieval of SpatialRefSys model objects. """ for sd in test_srs: srs = self.SpatialRefSys.objects.get(srid=sd["srid"]) self.assertEqual(sd["srid"], srs.srid) # Some of the authority names are borked on Oracle, e.g., # SRID=32140. Also, Oracle Spatial seems to add extraneous info to # fields, hence the testing with the 'startswith' flag. auth_name, oracle_flag = sd["auth_name"] # Compare case-insensitively because srs.auth_name is lowercase # ("epsg") on Spatialite. if not connection.ops.oracle or oracle_flag: self.assertIs(srs.auth_name.upper().startswith(auth_name), True) self.assertEqual(sd["auth_srid"], srs.auth_srid) # No PROJ and different srtext on Oracle. if not connection.ops.oracle: self.assertTrue(srs.wkt.startswith(sd["srtext"])) self.assertRegex(srs.proj4text, sd["proj_re"]) def test_osr(self): """ Test getting OSR objects from SpatialRefSys model objects. """ for sd in test_srs: sr = self.SpatialRefSys.objects.get(srid=sd["srid"]) self.assertTrue(sr.spheroid.startswith(sd["spheroid"])) self.assertEqual(sd["geographic"], sr.geographic) self.assertEqual(sd["projected"], sr.projected) self.assertIs(sr.name.startswith(sd["name"]), True) # Testing the SpatialReference object directly. if not connection.ops.oracle: srs = sr.srs self.assertRegex(srs.proj, sd["proj_re"]) self.assertTrue(srs.wkt.startswith(sd["srtext"])) def test_ellipsoid(self): """ Test the ellipsoid property. """ for sd in test_srs: # Getting the ellipsoid and precision parameters. ellps1 = sd["ellipsoid"] prec = sd["eprec"] # Getting our spatial reference and its ellipsoid srs = self.SpatialRefSys.objects.get(srid=sd["srid"]) ellps2 = srs.ellipsoid for i in range(3): self.assertAlmostEqual(ellps1[i], ellps2[i], prec[i]) @skipUnlessDBFeature("supports_add_srs_entry") def test_add_entry(self): """ Test adding a new entry in the SpatialRefSys model using the add_srs_entry utility. """ from django.contrib.gis.utils import add_srs_entry add_srs_entry(3857) self.assertTrue(self.SpatialRefSys.objects.filter(srid=3857).exists()) srs = self.SpatialRefSys.objects.get(srid=3857) self.assertTrue( self.SpatialRefSys.get_spheroid(srs.wkt).startswith("SPHEROID[") ) def test_srs_with_invalid_wkt_and_proj4(self): class MockSpatialRefSys(SpatialRefSysMixin): def __init__(self, wkt=None, proj4text=None): self.wkt = wkt self.proj4text = proj4text with self.assertRaisesMessage( Exception, "Could not get OSR SpatialReference.\n" "Error for WKT 'INVALID_WKT': Corrupt data.\n" "Error for PROJ.4 '+proj=invalid': Corrupt data.", ): MockSpatialRefSys(wkt="INVALID_WKT", proj4text="+proj=invalid").srs
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/test_measure.py
tests/gis_tests/test_measure.py
""" Distance and Area objects to allow for sensible and convenient calculation and conversions. Here are some tests. """ import unittest from django.contrib.gis.measure import A, Area, D, Distance from django.test import SimpleTestCase class DistanceTest(SimpleTestCase): "Testing the Distance object" def test_init(self): "Testing initialization from valid units" d = Distance(m=100) self.assertEqual(d.m, 100) d1, d2, d3 = D(m=100), D(meter=100), D(metre=100) for d in (d1, d2, d3): self.assertEqual(d.m, 100) d = D(nm=100) self.assertEqual(d.m, 185200) y1, y2, y3 = D(yd=100), D(yard=100), D(Yard=100) for d in (y1, y2, y3): self.assertEqual(d.yd, 100) mm1, mm2 = D(millimeter=1000), D(MiLLiMeTeR=1000) for d in (mm1, mm2): self.assertEqual(d.m, 1.0) self.assertEqual(d.mm, 1000.0) def test_init_invalid(self): "Testing initialization from invalid units" with self.assertRaises(AttributeError): D(banana=100) def test_init_invalid_area_only_units(self): with self.assertRaises(AttributeError): D(ha=100) def test_access(self): "Testing access in different units" d = D(m=100) self.assertEqual(d.km, 0.1) self.assertAlmostEqual(d.ft, 328.084, 3) def test_access_invalid(self): "Testing access in invalid units" d = D(m=100) self.assertFalse(hasattr(d, "banana")) def test_addition(self): "Test addition & subtraction" d1 = D(m=100) d2 = D(m=200) d3 = d1 + d2 self.assertEqual(d3.m, 300) d3 += d1 self.assertEqual(d3.m, 400) d4 = d1 - d2 self.assertEqual(d4.m, -100) d4 -= d1 self.assertEqual(d4.m, -200) with self.assertRaises(TypeError): d1 + 1 with self.assertRaises(TypeError): d1 - 1 with self.assertRaises(TypeError): d1 += 1 with self.assertRaises(TypeError): d1 -= 1 def test_multiplication(self): "Test multiplication & division" d1 = D(m=100) d3 = d1 * 2 self.assertEqual(d3.m, 200) d3 = 2 * d1 self.assertEqual(d3.m, 200) d3 *= 5 self.assertEqual(d3.m, 1000) d4 = d1 / 2 self.assertEqual(d4.m, 50) d4 /= 5 self.assertEqual(d4.m, 10) d5 = d1 / D(m=2) self.assertEqual(d5, 50) a5 = d1 * D(m=10) self.assertIsInstance(a5, Area) self.assertEqual(a5.sq_m, 100 * 10) with self.assertRaises(TypeError): d1 *= D(m=1) with self.assertRaises(TypeError): d1 /= D(m=1) def test_unit_conversions(self): "Testing default units during maths" d1 = D(m=100) d2 = D(km=1) d3 = d1 + d2 self.assertEqual(d3._default_unit, "m") d4 = d2 + d1 self.assertEqual(d4._default_unit, "km") d5 = d1 * 2 self.assertEqual(d5._default_unit, "m") d6 = d1 / 2 self.assertEqual(d6._default_unit, "m") def test_comparisons(self): "Testing comparisons" d1 = D(m=100) d2 = D(km=1) d3 = D(km=0) self.assertGreater(d2, d1) self.assertEqual(d1, d1) self.assertLess(d1, d2) self.assertFalse(d3) def test_units_str(self): "Testing conversion to strings" d1 = D(m=100) d2 = D(km=3.5) self.assertEqual(str(d1), "100.0 m") self.assertEqual(str(d2), "3.5 km") self.assertEqual(repr(d1), "Distance(m=100.0)") self.assertEqual(repr(d2), "Distance(km=3.5)") def test_furlong(self): d = D(m=201.168) self.assertEqual(d.furlong, 1) def test_unit_att_name(self): "Testing the `unit_attname` class method" unit_tuple = [ ("Yard", "yd"), ("Nautical Mile", "nm"), ("German legal metre", "german_m"), ("Indian yard", "indian_yd"), ("Chain (Sears)", "chain_sears"), ("Chain", "chain"), ("Furrow Long", "furlong"), ] for nm, att in unit_tuple: with self.subTest(nm=nm): self.assertEqual(att, D.unit_attname(nm)) def test_unit_att_name_invalid(self): msg = "Unknown unit type: invalid-unit-name" with self.assertRaisesMessage(AttributeError, msg): D.unit_attname("invalid-unit-name") with self.assertRaisesMessage(AttributeError, msg): A.unit_attname("invalid-unit-name") def test_hash(self): d1 = D(m=99) d2 = D(m=100) d3 = D(km=0.1) self.assertEqual(hash(d2), hash(d3)) self.assertNotEqual(hash(d1), hash(d2)) self.assertNotEqual(hash(d1), hash(d3)) class AreaTest(unittest.TestCase): "Testing the Area object" def test_init(self): "Testing initialization from valid units" a = Area(sq_m=100) self.assertEqual(a.sq_m, 100) a = A(sq_m=100) self.assertEqual(a.sq_m, 100) a = A(sq_mi=100) self.assertEqual(a.sq_m, 258998811.0336) def test_init_invalid_a(self): "Testing initialization from invalid units" with self.assertRaises(AttributeError): A(banana=100) def test_access(self): "Testing access in different units" a = A(sq_m=100) self.assertEqual(a.sq_km, 0.0001) self.assertAlmostEqual(a.sq_ft, 1076.391, 3) def test_access_invalid_a(self): "Testing access in invalid units" a = A(sq_m=100) self.assertFalse(hasattr(a, "banana")) def test_addition(self): "Test addition & subtraction" a1 = A(sq_m=100) a2 = A(sq_m=200) a3 = a1 + a2 self.assertEqual(a3.sq_m, 300) a3 += a1 self.assertEqual(a3.sq_m, 400) a4 = a1 - a2 self.assertEqual(a4.sq_m, -100) a4 -= a1 self.assertEqual(a4.sq_m, -200) with self.assertRaises(TypeError): a1 + 1 with self.assertRaises(TypeError): a1 - 1 with self.assertRaises(TypeError): a1 += 1 with self.assertRaises(TypeError): a1 -= 1 def test_multiplication(self): "Test multiplication & division" a1 = A(sq_m=100) a3 = a1 * 2 self.assertEqual(a3.sq_m, 200) a3 = 2 * a1 self.assertEqual(a3.sq_m, 200) a3 *= 5 self.assertEqual(a3.sq_m, 1000) a4 = a1 / 2 self.assertEqual(a4.sq_m, 50) a4 /= 5 self.assertEqual(a4.sq_m, 10) with self.assertRaises(TypeError): a1 * A(sq_m=1) with self.assertRaises(TypeError): a1 *= A(sq_m=1) with self.assertRaises(TypeError): a1 / A(sq_m=1) with self.assertRaises(TypeError): a1 /= A(sq_m=1) def test_unit_conversions(self): "Testing default units during maths" a1 = A(sq_m=100) a2 = A(sq_km=1) a3 = a1 + a2 self.assertEqual(a3._default_unit, "sq_m") a4 = a2 + a1 self.assertEqual(a4._default_unit, "sq_km") a5 = a1 * 2 self.assertEqual(a5._default_unit, "sq_m") a6 = a1 / 2 self.assertEqual(a6._default_unit, "sq_m") def test_comparisons(self): "Testing comparisons" a1 = A(sq_m=100) a2 = A(sq_km=1) a3 = A(sq_km=0) self.assertGreater(a2, a1) self.assertEqual(a1, a1) self.assertLess(a1, a2) self.assertFalse(a3) def test_units_str(self): "Testing conversion to strings" a1 = A(sq_m=100) a2 = A(sq_km=3.5) self.assertEqual(str(a1), "100.0 sq_m") self.assertEqual(str(a2), "3.5 sq_km") self.assertEqual(repr(a1), "Area(sq_m=100.0)") self.assertEqual(repr(a2), "Area(sq_km=3.5)") def test_hectare(self): a = A(sq_m=10000) self.assertEqual(a.ha, 1) def test_hectare_unit_att_name(self): self.assertEqual(A.unit_attname("Hectare"), "ha") def test_hash(self): a1 = A(sq_m=100) a2 = A(sq_m=1000000) a3 = A(sq_km=1) self.assertEqual(hash(a2), hash(a3)) self.assertNotEqual(hash(a1), hash(a2)) self.assertNotEqual(hash(a1), hash(a3))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/models.py
tests/gis_tests/models.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/test_ptr.py
tests/gis_tests/test_ptr.py
import ctypes from unittest import mock from django.contrib.gis.ptr import CPointerBase from django.test import SimpleTestCase class CPointerBaseTests(SimpleTestCase): def test(self): destructor_mock = mock.Mock() class NullPointerException(Exception): pass class FakeGeom1(CPointerBase): null_ptr_exception_class = NullPointerException class FakeGeom2(FakeGeom1): ptr_type = ctypes.POINTER(ctypes.c_float) destructor = destructor_mock fg1 = FakeGeom1() fg2 = FakeGeom2() # These assignments are OK. None is allowed because it's equivalent # to the NULL pointer. fg1.ptr = fg1.ptr_type() fg1.ptr = None fg2.ptr = fg2.ptr_type(ctypes.c_float(5.23)) fg2.ptr = None # Because pointers have been set to NULL, an exception is raised on # access. Raising an exception is preferable to a segmentation fault # that commonly occurs when a C method is given a NULL reference. for fg in (fg1, fg2): with self.assertRaises(NullPointerException): fg.ptr # Anything that's either not None or the acceptable pointer type # results in a TypeError when trying to assign it to the `ptr` # property. Thus, memory addresses (integers) and pointers of the # incorrect type (in `bad_ptrs`) aren't allowed. bad_ptrs = (5, ctypes.c_char_p(b"foobar")) for bad_ptr in bad_ptrs: for fg in (fg1, fg2): with self.assertRaisesMessage(TypeError, "Incompatible pointer type"): fg.ptr = bad_ptr # Object can be deleted without a destructor set. fg = FakeGeom1() fg.ptr = fg.ptr_type(1) del fg # A NULL pointer isn't passed to the destructor. fg = FakeGeom2() fg.ptr = None del fg self.assertFalse(destructor_mock.called) # The destructor is called if set. fg = FakeGeom2() ptr = fg.ptr_type(ctypes.c_float(1.0)) fg.ptr = ptr del fg destructor_mock.assert_called_with(ptr) def test_destructor_catches_importerror(self): class FakeGeom(CPointerBase): destructor = mock.Mock(side_effect=ImportError) fg = FakeGeom() fg.ptr = fg.ptr_type(1) del fg
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/utils.py
tests/gis_tests/utils.py
import copy import unittest from functools import wraps from unittest import mock from django.conf import settings from django.contrib.gis.geos.libgeos import geos_version_tuple from django.db import DEFAULT_DB_ALIAS, connection from django.db.models import Func def skipUnlessGISLookup(*gis_lookups): """ Skip a test unless a database supports all of gis_lookups. """ def decorator(test_func): @wraps(test_func) def skip_wrapper(*args, **kwargs): if any(key not in connection.ops.gis_operators for key in gis_lookups): raise unittest.SkipTest( "Database doesn't support all the lookups: %s" % ", ".join(gis_lookups) ) return test_func(*args, **kwargs) return skip_wrapper return decorator _default_db = settings.DATABASES[DEFAULT_DB_ALIAS]["ENGINE"].rsplit(".")[-1] # MySQL spatial indices can't handle NULL geometries. gisfield_may_be_null = _default_db != "mysql" # GEOSWKTWriter_write() behavior was changed in GEOS 3.12+ to include # parentheses for sub-members. MariaDB doesn't accept WKT representations with # additional parentheses for MultiPoint. This is an accepted bug (MDEV-36166) # in MariaDB that should be fixed in the future. cannot_save_multipoint = connection.ops.mariadb and geos_version_tuple() >= (3, 12) can_save_multipoint = not cannot_save_multipoint class FuncTestMixin: """Assert that Func expressions aren't mutated during their as_sql().""" def setUp(self): def as_sql_wrapper(original_as_sql): def inner(*args, **kwargs): func = original_as_sql.__self__ # Resolve output_field before as_sql() so touching it in # as_sql() won't change __dict__. func.output_field __dict__original = copy.deepcopy(func.__dict__) result = original_as_sql(*args, **kwargs) msg = ( "%s Func was mutated during compilation." % func.__class__.__name__ ) self.assertEqual(func.__dict__, __dict__original, msg) return result return inner def __getattribute__(self, name): if name != vendor_impl: return __getattribute__original(self, name) try: as_sql = __getattribute__original(self, vendor_impl) except AttributeError: as_sql = __getattribute__original(self, "as_sql") return as_sql_wrapper(as_sql) vendor_impl = "as_" + connection.vendor __getattribute__original = Func.__getattribute__ func_patcher = mock.patch.object(Func, "__getattribute__", __getattribute__) func_patcher.start() self.addCleanup(func_patcher.stop) super().setUp()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/test_geoforms.py
tests/gis_tests/test_geoforms.py
import re from django.contrib.gis import forms from django.contrib.gis.forms import BaseGeometryWidget, OpenLayersWidget from django.contrib.gis.geos import GEOSGeometry from django.core.exceptions import ValidationError from django.template.defaultfilters import json_script from django.test import SimpleTestCase, override_settings from django.utils.html import escape class GeometryFieldTest(SimpleTestCase): def test_init(self): "Testing GeometryField initialization with defaults." fld = forms.GeometryField() for bad_default in ("blah", 3, "FoO", None, 0): with self.subTest(bad_default=bad_default): with self.assertRaises(ValidationError): fld.clean(bad_default) def test_srid(self): "Testing GeometryField with a SRID set." # Input that doesn't specify the SRID is assumed to be in the SRID # of the input field. fld = forms.GeometryField(srid=4326) geom = fld.clean("POINT(5 23)") self.assertEqual(4326, geom.srid) # Making the field in a different SRID from that of the geometry, and # asserting it transforms. fld = forms.GeometryField(srid=32140) # Different PROJ versions use different transformations, all are # correct as having a 1 meter accuracy. tol = 1 xform_geom = GEOSGeometry( "POINT (951640.547328465 4219369.26171664)", srid=32140 ) # The cleaned geometry is transformed to 32140 (the widget map_srid is # 3857). cleaned_geom = fld.clean( "SRID=3857;POINT (-10615777.40976205 3473169.895707852)" ) self.assertEqual(cleaned_geom.srid, 32140) self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol)) def test_null(self): "Testing GeometryField's handling of null (None) geometries." # Form fields, by default, are required (`required=True`) fld = forms.GeometryField() with self.assertRaisesMessage(ValidationError, "No geometry value provided."): fld.clean(None) # This will clean None as a geometry (See #10660). fld = forms.GeometryField(required=False) self.assertIsNone(fld.clean(None)) def test_geom_type(self): "Testing GeometryField's handling of different geometry types." # By default, all geometry types are allowed. fld = forms.GeometryField() for wkt in ( "POINT(5 23)", "MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))", "LINESTRING(0 0, 1 1)", ): with self.subTest(wkt=wkt): # to_python() uses the SRID of OpenLayersWidget if the # converted value doesn't have an SRID. self.assertEqual( GEOSGeometry(wkt, srid=fld.widget.map_srid), fld.clean(wkt) ) pnt_fld = forms.GeometryField(geom_type="POINT") self.assertEqual( GEOSGeometry("POINT(5 23)", srid=pnt_fld.widget.map_srid), pnt_fld.clean("POINT(5 23)"), ) # a WKT for any other geom_type will be properly transformed by # `to_python` self.assertEqual( GEOSGeometry("LINESTRING(0 0, 1 1)", srid=pnt_fld.widget.map_srid), pnt_fld.to_python("LINESTRING(0 0, 1 1)"), ) # but rejected by `clean` with self.assertRaises(ValidationError): pnt_fld.clean("LINESTRING(0 0, 1 1)") def test_to_python(self): """ to_python() either returns a correct GEOSGeometry object or a ValidationError. """ good_inputs = [ "POINT(5 23)", "MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))", "LINESTRING(0 0, 1 1)", ] bad_inputs = [ "POINT(5)", "MULTI POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))", "BLAH(0 0, 1 1)", '{"type": "FeatureCollection", "features": [' '{"geometry": {"type": "Point", "coordinates": [508375, 148905]}, ' '"type": "Feature"}]}', ] fld = forms.GeometryField() # to_python returns the same GEOSGeometry for a WKT for geo_input in good_inputs: with self.subTest(geo_input=geo_input): self.assertEqual( GEOSGeometry(geo_input, srid=fld.widget.map_srid), fld.to_python(geo_input), ) # but raises a ValidationError for any other string for geo_input in bad_inputs: with self.subTest(geo_input=geo_input): with self.assertRaises(ValidationError): fld.to_python(geo_input) def test_to_python_different_map_srid(self): f = forms.GeometryField(widget=OpenLayersWidget) json = '{ "type": "Point", "coordinates": [ 5.0, 23.0 ] }' self.assertEqual( GEOSGeometry("POINT(5 23)", srid=f.widget.map_srid), f.to_python(json) ) def test_field_with_text_widget(self): class PointForm(forms.Form): pt = forms.PointField(srid=4326, widget=forms.TextInput) form = PointForm() cleaned_pt = form.fields["pt"].clean("POINT(5 23)") self.assertEqual(cleaned_pt, GEOSGeometry("POINT(5 23)", srid=4326)) self.assertEqual(4326, cleaned_pt.srid) with self.assertRaisesMessage(ValidationError, "Invalid geometry value."): form.fields["pt"].clean("POINT(5)") point = GEOSGeometry("SRID=4326;POINT(5 23)") form = PointForm(data={"pt": "POINT(5 23)"}, initial={"pt": point}) self.assertFalse(form.has_changed()) def test_field_string_value(self): """ Initialization of a geometry field with a valid/empty/invalid string. Only the invalid string should trigger an error log entry. """ class PointForm(forms.Form): pt1 = forms.PointField(srid=4326) pt2 = forms.PointField(srid=4326) pt3 = forms.PointField(srid=4326) form = PointForm( { "pt1": "SRID=4326;POINT(7.3 44)", # valid "pt2": "", # empty "pt3": "PNT(0)", # invalid } ) with self.assertLogs("django.contrib.gis", "ERROR") as logger_calls: output = str(form) # The first point can't use assertInHTML() due to non-deterministic # ordering of the rendered dictionary. pt1_serialized = re.search(r"<textarea [^>]*>({[^<]+})<", output)[1] pt1_json = pt1_serialized.replace("&quot;", '"') pt1_expected = GEOSGeometry(form.data["pt1"]).transform(3857, clone=True) self.assertJSONEqual(pt1_json, pt1_expected.json) self.assertInHTML( '<textarea id="id_pt2" class="vSerializedField required" cols="150"' ' rows="10" name="pt2" hidden></textarea>', output, ) self.assertInHTML( '<textarea id="id_pt3" class="vSerializedField required" cols="150"' ' rows="10" name="pt3" hidden></textarea>', output, ) # Only the invalid PNT(0) triggers an error log entry. # Deserialization is called in form clean and in widget rendering. self.assertEqual(len(logger_calls.records), 2) self.assertEqual( logger_calls.records[0].getMessage(), "Error creating geometry from value 'PNT(0)' (String input " "unrecognized as WKT EWKT, and HEXEWKB.)", ) def test_override_attrs(self): self.assertIsNone(forms.BaseGeometryWidget.base_layer) self.assertEqual(forms.BaseGeometryWidget.geom_type, "GEOMETRY") self.assertEqual(forms.BaseGeometryWidget.map_srid, 4326) self.assertIs(forms.BaseGeometryWidget.display_raw, False) class PointForm(forms.Form): p = forms.PointField( widget=forms.OpenLayersWidget( attrs={ "base_layer": "some-test-file", "map_srid": 1234, } ), ) form = PointForm() rendered = form.as_p() attrs = { "base_layer": "some-test-file", "geom_type": "POINT", "map_srid": 1234, "display_raw": False, "required": True, "id": "id_p", "geom_name": "Point", } expected = json_script(attrs, "id_p_mapwidget_options") self.assertInHTML(expected, rendered) class SpecializedFieldTest(SimpleTestCase): def setUp(self): self.geometries = { "point": GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)"), "multipoint": GEOSGeometry( "SRID=4326;MULTIPOINT(" "(13.18634033203125 14.504356384277344)," "(13.207969665527 14.490966796875)," "(13.177070617675 14.454917907714))" ), "linestring": GEOSGeometry( "SRID=4326;LINESTRING(" "-8.26171875 -0.52734375," "-7.734375 4.21875," "6.85546875 3.779296875," "5.44921875 -3.515625)" ), "multilinestring": GEOSGeometry( "SRID=4326;MULTILINESTRING(" "(-16.435546875 -2.98828125," "-17.2265625 2.98828125," "-0.703125 3.515625," "-1.494140625 -3.33984375)," "(-8.0859375 -5.9765625," "8.525390625 -8.7890625," "12.392578125 -0.87890625," "10.01953125 7.646484375))" ), "polygon": GEOSGeometry( "SRID=4326;POLYGON(" "(-1.669921875 6.240234375," "-3.8671875 -0.615234375," "5.9765625 -3.955078125," "18.193359375 3.955078125," "9.84375 9.4921875," "-1.669921875 6.240234375))" ), "multipolygon": GEOSGeometry( "SRID=4326;MULTIPOLYGON(" "((-17.578125 13.095703125," "-17.2265625 10.8984375," "-13.974609375 10.1953125," "-13.359375 12.744140625," "-15.732421875 13.7109375," "-17.578125 13.095703125))," "((-8.525390625 5.537109375," "-8.876953125 2.548828125," "-5.888671875 1.93359375," "-5.09765625 4.21875," "-6.064453125 6.240234375," "-8.525390625 5.537109375)))" ), "geometrycollection": GEOSGeometry( "SRID=4326;GEOMETRYCOLLECTION(" "POINT(5.625 -0.263671875)," "POINT(6.767578125 -3.603515625)," "POINT(8.525390625 0.087890625)," "POINT(8.0859375 -2.13134765625)," "LINESTRING(" "6.273193359375 -1.175537109375," "5.77880859375 -1.812744140625," "7.27294921875 -2.230224609375," "7.657470703125 -1.25244140625))" ), } def assertMapWidget(self, form_instance, geom_name): """ Make sure the MapWidget js is passed in the form media and a MapWidget is actually created """ self.assertTrue(form_instance.is_valid()) rendered = form_instance.as_p() map_fields = [ f for f in form_instance if isinstance(f.field, forms.GeometryField) ] for map_field in map_fields: attrs = { "base_layer": "nasaWorldview", "geom_type": map_field.field.geom_type, "map_srid": 3857, "display_raw": False, "required": True, "id": map_field.id_for_label, "geom_name": geom_name, } expected = json_script(attrs, f"{map_field.id_for_label}_mapwidget_options") self.assertInHTML(expected, rendered) self.assertIn("gis/js/OLMapWidget.js", str(form_instance.media)) def assertTextarea(self, geom, rendered): """Makes sure the wkt and a textarea are in the content""" self.assertIn("<textarea ", rendered) self.assertIn("required", rendered) ogr = geom.ogr ogr.transform(3857) self.assertIn(escape(ogr.json), rendered) # map_srid in openlayers.html template must not be localized. @override_settings(USE_THOUSAND_SEPARATOR=True) def test_pointfield(self): class PointForm(forms.Form): p = forms.PointField() geom = self.geometries["point"] form = PointForm(data={"p": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "Point") self.assertFalse(PointForm().is_valid()) invalid = PointForm(data={"p": "some invalid geom"}) self.assertFalse(invalid.is_valid()) self.assertIn("Invalid geometry value", str(invalid.errors)) for invalid in [geo for key, geo in self.geometries.items() if key != "point"]: self.assertFalse(PointForm(data={"p": invalid.wkt}).is_valid()) def test_multipointfield(self): class PointForm(forms.Form): p = forms.MultiPointField() geom = self.geometries["multipoint"] form = PointForm(data={"p": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "MultiPoint") self.assertFalse(PointForm().is_valid()) for invalid in [ geo for key, geo in self.geometries.items() if key != "multipoint" ]: self.assertFalse(PointForm(data={"p": invalid.wkt}).is_valid()) def test_linestringfield(self): class LineStringForm(forms.Form): f = forms.LineStringField() geom = self.geometries["linestring"] form = LineStringForm(data={"f": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "LineString") self.assertFalse(LineStringForm().is_valid()) for invalid in [ geo for key, geo in self.geometries.items() if key != "linestring" ]: self.assertFalse(LineStringForm(data={"p": invalid.wkt}).is_valid()) def test_multilinestringfield(self): class LineStringForm(forms.Form): f = forms.MultiLineStringField() geom = self.geometries["multilinestring"] form = LineStringForm(data={"f": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "MultiLineString") self.assertFalse(LineStringForm().is_valid()) for invalid in [ geo for key, geo in self.geometries.items() if key != "multilinestring" ]: self.assertFalse(LineStringForm(data={"p": invalid.wkt}).is_valid()) def test_polygonfield(self): class PolygonForm(forms.Form): p = forms.PolygonField() geom = self.geometries["polygon"] form = PolygonForm(data={"p": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "Polygon") self.assertFalse(PolygonForm().is_valid()) for invalid in [ geo for key, geo in self.geometries.items() if key != "polygon" ]: self.assertFalse(PolygonForm(data={"p": invalid.wkt}).is_valid()) def test_multipolygonfield(self): class PolygonForm(forms.Form): p = forms.MultiPolygonField() geom = self.geometries["multipolygon"] form = PolygonForm(data={"p": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "MultiPolygon") self.assertFalse(PolygonForm().is_valid()) for invalid in [ geo for key, geo in self.geometries.items() if key != "multipolygon" ]: self.assertFalse(PolygonForm(data={"p": invalid.wkt}).is_valid()) def test_geometrycollectionfield(self): class GeometryForm(forms.Form): g = forms.GeometryCollectionField() geom = self.geometries["geometrycollection"] form = GeometryForm(data={"g": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "GeometryCollection") self.assertFalse(GeometryForm().is_valid()) for invalid in [ geo for key, geo in self.geometries.items() if key != "geometrycollection" ]: self.assertFalse(GeometryForm(data={"g": invalid.wkt}).is_valid()) class OSMWidgetTest(SimpleTestCase): def setUp(self): self.geometries = { "point": GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)"), } def test_osm_widget(self): class PointForm(forms.Form): p = forms.PointField(widget=forms.OSMWidget) geom = self.geometries["point"] form = PointForm(data={"p": geom}) rendered = form.as_p() self.assertIn('"base_layer": "osm"', rendered) self.assertIn('<textarea id="id_p"', rendered) def test_default_lat_lon(self): self.assertEqual(forms.OSMWidget.default_lon, 5) self.assertEqual(forms.OSMWidget.default_lat, 47) self.assertEqual(forms.OSMWidget.default_zoom, 12) class PointForm(forms.Form): p = forms.PointField( widget=forms.OSMWidget( attrs={ "default_lon": 20, "default_lat": 30, "default_zoom": 17, } ), ) form = PointForm() rendered = form.as_p() attrs = { "base_layer": "osm", "geom_type": "POINT", "map_srid": 3857, "display_raw": False, "default_lon": 20, "default_lat": 30, "default_zoom": 17, "required": True, "id": "id_p", "geom_name": "Point", } expected = json_script(attrs, "id_p_mapwidget_options") self.assertInHTML(expected, rendered) class GeometryWidgetTests(SimpleTestCase): def test_get_context_attrs(self): # The Widget.get_context() attrs argument overrides self.attrs. widget = BaseGeometryWidget(attrs={"geom_type": "POINT"}) context = widget.get_context("point", None, attrs={"geom_type": "POINT2"}) self.assertEqual(context["widget"]["attrs"]["geom_type"], "POINT2") # Widget.get_context() returns expected name for geom_type. widget = BaseGeometryWidget(attrs={"geom_type": "POLYGON"}) context = widget.get_context("polygon", None, None) self.assertEqual(context["widget"]["attrs"]["geom_name"], "Polygon") # Widget.get_context() returns 'Geometry' instead of 'Unknown'. widget = BaseGeometryWidget(attrs={"geom_type": "GEOMETRY"}) context = widget.get_context("geometry", None, None) self.assertEqual(context["widget"]["attrs"]["geom_name"], "Geometry") def test_subwidgets(self): widget = forms.BaseGeometryWidget() self.assertEqual( list(widget.subwidgets("name", "value")), [ { "is_hidden": False, "attrs": { "base_layer": None, "display_raw": False, "map_srid": 4326, "geom_name": "Geometry", "geom_type": "GEOMETRY", }, "name": "name", "template_name": "", "value": "value", "required": False, } ], ) def test_custom_serialization_widget(self): class CustomGeometryWidget(forms.BaseGeometryWidget): template_name = "gis/openlayers.html" deserialize_called = 0 def serialize(self, value): return value.json if value else "" def deserialize(self, value): self.deserialize_called += 1 return GEOSGeometry(value) class PointForm(forms.Form): p = forms.PointField(widget=CustomGeometryWidget) point = GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)") form = PointForm(data={"p": point}) self.assertIn(escape(point.json), form.as_p()) CustomGeometryWidget.called = 0 widget = form.fields["p"].widget # Force deserialize use due to a string value self.assertIn(escape(point.json), widget.render("p", point.json)) self.assertEqual(widget.deserialize_called, 1) form = PointForm(data={"p": point.json}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data["p"].srid, 4326)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/test_gis_tests_utils.py
tests/gis_tests/test_gis_tests_utils.py
from django.db import connection, models from django.test import SimpleTestCase from .utils import FuncTestMixin def test_mutation(raises=True): def wrapper(mutation_func): def test(test_case_instance, *args, **kwargs): class TestFunc(models.Func): output_field = models.IntegerField() def __init__(self): self.attribute = "initial" super().__init__("initial", ["initial"]) def as_sql(self, *args, **kwargs): mutation_func(self) return "", () if raises: msg = "TestFunc Func was mutated during compilation." with test_case_instance.assertRaisesMessage(AssertionError, msg): getattr(TestFunc(), "as_" + connection.vendor)(None, None) else: getattr(TestFunc(), "as_" + connection.vendor)(None, None) return test return wrapper class FuncTestMixinTests(FuncTestMixin, SimpleTestCase): @test_mutation() def test_mutated_attribute(func): func.attribute = "mutated" @test_mutation() def test_mutated_expressions(func): func.source_expressions.clear() @test_mutation() def test_mutated_expression(func): func.source_expressions[0].name = "mutated" @test_mutation() def test_mutated_expression_deep(func): func.source_expressions[1].value[0] = "mutated" @test_mutation(raises=False) def test_not_mutated(func): pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/test_fields.py
tests/gis_tests/test_fields.py
import copy from django.contrib.gis.db.models import GeometryField from django.contrib.gis.db.models.sql import AreaField, DistanceField from django.test import SimpleTestCase class FieldsTests(SimpleTestCase): def test_area_field_deepcopy(self): field = AreaField(None) self.assertEqual(copy.deepcopy(field), field) def test_distance_field_deepcopy(self): field = DistanceField(None) self.assertEqual(copy.deepcopy(field), field) class GeometryFieldTests(SimpleTestCase): def test_deconstruct_empty(self): field = GeometryField() *_, kwargs = field.deconstruct() self.assertEqual(kwargs, {"srid": 4326}) def test_deconstruct_values(self): field = GeometryField( srid=4067, dim=3, geography=True, extent=( 50199.4814, 6582464.0358, -50000.0, 761274.6247, 7799839.8902, 50000.0, ), tolerance=0.01, ) *_, kwargs = field.deconstruct() self.assertEqual( kwargs, { "srid": 4067, "dim": 3, "geography": True, "extent": ( 50199.4814, 6582464.0358, -50000.0, 761274.6247, 7799839.8902, 50000.0, ), "tolerance": 0.01, }, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/__init__.py
tests/gis_tests/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/tests.py
tests/gis_tests/tests.py
import unittest from django.core.exceptions import ImproperlyConfigured from django.db import ProgrammingError, connection from django.db.backends.base.base import NO_DB_ALIAS from django.test import TestCase try: from django.contrib.gis.db.backends.postgis.operations import PostGISOperations HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False class BaseSpatialFeaturesTests(TestCase): def test_invalid_has_func_function(self): msg = ( 'DatabaseFeatures.has_Invalid_function isn\'t valid. Is "Invalid" ' "missing from BaseSpatialOperations.unsupported_functions?" ) with self.assertRaisesMessage(ValueError, msg): connection.features.has_Invalid_function if HAS_POSTGRES: class FakeConnection: def __init__(self): self.settings_dict = { "NAME": "test", } class FakePostGISOperations(PostGISOperations): def __init__(self, version=None): self.version = version self.connection = FakeConnection() def _get_postgis_func(self, func): if func == "postgis_lib_version": if self.version is None: raise ProgrammingError else: return self.version elif func == "version": pass else: raise NotImplementedError("This function was not expected to be called") @unittest.skipUnless(HAS_POSTGRES, "The psycopg driver is needed for these tests") class TestPostGISVersionCheck(unittest.TestCase): """ The PostGIS version check parses correctly the version numbers """ def test_get_version(self): expect = "1.0.0" ops = FakePostGISOperations(expect) actual = ops.postgis_lib_version() self.assertEqual(expect, actual) def test_version_classic_tuple(self): expect = ("1.2.3", 1, 2, 3) ops = FakePostGISOperations(expect[0]) actual = ops.postgis_version_tuple() self.assertEqual(expect, actual) def test_version_dev_tuple(self): expect = ("1.2.3dev", 1, 2, 3) ops = FakePostGISOperations(expect[0]) actual = ops.postgis_version_tuple() self.assertEqual(expect, actual) def test_version_loose_tuple(self): expect = ("1.2.3b1.dev0", 1, 2, 3) ops = FakePostGISOperations(expect[0]) actual = ops.postgis_version_tuple() self.assertEqual(expect, actual) def test_valid_version_numbers(self): versions = [ ("1.3.0", 1, 3, 0), ("2.1.1", 2, 1, 1), ("2.2.0dev", 2, 2, 0), ] for version in versions: with self.subTest(version=version): ops = FakePostGISOperations(version[0]) actual = ops.spatial_version self.assertEqual(version[1:], actual) def test_no_version_number(self): ops = FakePostGISOperations() with self.assertRaises(ImproperlyConfigured): ops.spatial_version @unittest.skipUnless(HAS_POSTGRES, "PostGIS-specific tests.") class TestPostGISBackend(unittest.TestCase): def test_non_db_connection_classes(self): from django.contrib.gis.db.backends.postgis.base import DatabaseWrapper from django.db.backends.postgresql.features import DatabaseFeatures from django.db.backends.postgresql.introspection import DatabaseIntrospection from django.db.backends.postgresql.operations import DatabaseOperations wrapper = DatabaseWrapper(settings_dict={}, alias=NO_DB_ALIAS) # PostGIS-specific stuff is not initialized for non-db connections. self.assertIs(wrapper.features_class, DatabaseFeatures) self.assertIs(wrapper.ops_class, DatabaseOperations) self.assertIs(wrapper.introspection_class, DatabaseIntrospection)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geo3d/views.py
tests/gis_tests/geo3d/views.py
# Create your views here.
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geo3d/models.py
tests/gis_tests/geo3d/models.py
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 City3D(NamedModel): point = models.PointField(dim=3) pointg = models.PointField(dim=3, geography=True) class Meta: required_db_features = {"supports_3d_storage"} class Interstate2D(NamedModel): line = models.LineStringField(srid=4269) class Interstate3D(NamedModel): line = models.LineStringField(dim=3, srid=4269) class Meta: required_db_features = {"supports_3d_storage"} class InterstateProj2D(NamedModel): line = models.LineStringField(srid=32140) class InterstateProj3D(NamedModel): line = models.LineStringField(dim=3, srid=32140) class Meta: required_db_features = {"supports_3d_storage"} class Polygon2D(NamedModel): poly = models.PolygonField(srid=32140) class Polygon3D(NamedModel): poly = models.PolygonField(dim=3, srid=32140) class Meta: required_db_features = {"supports_3d_storage"} class SimpleModel(models.Model): class Meta: abstract = True class Point2D(SimpleModel): point = models.PointField(null=True) class Point3D(SimpleModel): point = models.PointField(dim=3) class Meta: required_db_features = {"supports_3d_storage"} class MultiPoint3D(SimpleModel): mpoint = models.MultiPointField(dim=3) class Meta: required_db_features = {"supports_3d_storage"}
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geo3d/__init__.py
tests/gis_tests/geo3d/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geo3d/tests.py
tests/gis_tests/geo3d/tests.py
import os import re from django.contrib.gis.db.models import Extent3D, Q, Union from django.contrib.gis.db.models.functions import ( AsGeoJSON, AsKML, Length, Perimeter, Scale, Translate, ) from django.contrib.gis.geos import GEOSGeometry, LineString, Point, Polygon from django.test import TestCase, skipUnlessDBFeature from ..utils import FuncTestMixin from .models import ( City3D, Interstate2D, Interstate3D, InterstateProj2D, InterstateProj3D, MultiPoint3D, Point2D, Point3D, Polygon2D, Polygon3D, ) data_path = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "data")) city_file = os.path.join(data_path, "cities", "cities.shp") vrt_file = os.path.join(data_path, "test_vrt", "test_vrt.vrt") # The coordinates of each city, with Z values corresponding to their # altitude in meters. city_data = ( ("Houston", (-95.363151, 29.763374, 18)), ("Dallas", (-96.801611, 32.782057, 147)), ("Oklahoma City", (-97.521157, 34.464642, 380)), ("Wellington", (174.783117, -41.315268, 14)), ("Pueblo", (-104.609252, 38.255001, 1433)), ("Lawrence", (-95.235060, 38.971823, 251)), ("Chicago", (-87.650175, 41.850385, 181)), ("Victoria", (-123.305196, 48.462611, 15)), ) # Reference mapping of city name to its altitude (Z value). city_dict = {name: coords for name, coords in city_data} # 3D freeway data derived from the National Elevation Dataset: # http://seamless.usgs.gov/products/9arc.php interstate_data = ( ( "I-45", "LINESTRING(-95.3708481 29.7765870 11.339,-95.3694580 29.7787980 4.536," "-95.3690305 29.7797359 9.762,-95.3691886 29.7812450 12.448," "-95.3696447 29.7850144 10.457,-95.3702511 29.7868518 9.418," "-95.3706724 29.7881286 14.858,-95.3711632 29.7896157 15.386," "-95.3714525 29.7936267 13.168,-95.3717848 29.7955007 15.104," "-95.3717719 29.7969804 16.516,-95.3717305 29.7982117 13.923," "-95.3717254 29.8000778 14.385,-95.3719875 29.8013539 15.160," "-95.3720575 29.8026785 15.544,-95.3721321 29.8040912 14.975," "-95.3722074 29.8050998 15.688,-95.3722779 29.8060430 16.099," "-95.3733818 29.8076750 15.197,-95.3741563 29.8103686 17.268," "-95.3749458 29.8129927 19.857,-95.3763564 29.8144557 15.435)", ( 11.339, 4.536, 9.762, 12.448, 10.457, 9.418, 14.858, 15.386, 13.168, 15.104, 16.516, 13.923, 14.385, 15.16, 15.544, 14.975, 15.688, 16.099, 15.197, 17.268, 19.857, 15.435, ), ), ) # Bounding box polygon for inner-loop of Houston (in projected coordinate # system 32140), with elevation values from the National Elevation Dataset # (see above). bbox_data = ( "POLYGON((941527.97 4225693.20,962596.48 4226349.75,963152.57 4209023.95," "942051.75 4208366.38,941527.97 4225693.20))", (21.71, 13.21, 9.12, 16.40, 21.71), ) class Geo3DLoadingHelper: def _load_interstate_data(self): # Interstate (2D / 3D and Geographic/Projected variants) for name, line, exp_z in interstate_data: line_3d = GEOSGeometry(line, srid=4269) line_2d = LineString([coord[:2] for coord in line_3d.coords], srid=4269) # Creating a geographic and projected version of the # interstate in both 2D and 3D. Interstate3D.objects.create(name=name, line=line_3d) InterstateProj3D.objects.create(name=name, line=line_3d) Interstate2D.objects.create(name=name, line=line_2d) InterstateProj2D.objects.create(name=name, line=line_2d) def _load_city_data(self): for name, pnt_data in city_data: City3D.objects.create( name=name, point=Point(*pnt_data, srid=4326), pointg=Point(*pnt_data, srid=4326), ) def _load_polygon_data(self): bbox_wkt, bbox_z = bbox_data bbox_2d = GEOSGeometry(bbox_wkt, srid=32140) bbox_3d = Polygon( tuple((x, y, z) for (x, y), z in zip(bbox_2d[0].coords, bbox_z)), srid=32140 ) Polygon2D.objects.create(name="2D BBox", poly=bbox_2d) Polygon3D.objects.create(name="3D BBox", poly=bbox_3d) @skipUnlessDBFeature("supports_3d_storage") class Geo3DTest(Geo3DLoadingHelper, TestCase): """ Only a subset of the PostGIS routines are 3D-enabled, and this TestCase tries to test the features that can handle 3D and that are also available within GeoDjango. For more information, see the PostGIS docs on the routines that support 3D: https://postgis.net/docs/PostGIS_Special_Functions_Index.html#PostGIS_3D_Functions """ def test_3d_hasz(self): """ Make sure data is 3D and has expected Z values -- shouldn't change because of coordinate system. """ self._load_interstate_data() for name, line, exp_z in interstate_data: interstate = Interstate3D.objects.get(name=name) interstate_proj = InterstateProj3D.objects.get(name=name) for i in [interstate, interstate_proj]: self.assertTrue(i.line.hasz) self.assertEqual(exp_z, tuple(i.line.z)) self._load_city_data() for name, pnt_data in city_data: city = City3D.objects.get(name=name) # Testing both geometry and geography fields self.assertTrue(city.point.hasz) self.assertTrue(city.pointg.hasz) self.assertEqual(city.point.z, pnt_data[2]) self.assertEqual(city.pointg.z, pnt_data[2]) def test_3d_polygons(self): """ Test the creation of polygon 3D models. """ self._load_polygon_data() p3d = Polygon3D.objects.get(name="3D BBox") self.assertTrue(p3d.poly.hasz) self.assertIsInstance(p3d.poly, Polygon) self.assertEqual(p3d.poly.srid, 32140) def test_3d_layermapping(self): """ Testing LayerMapping on 3D models. """ # Import here as GDAL is required for those imports from django.contrib.gis.utils import LayerMapError, LayerMapping point_mapping = {"point": "POINT"} mpoint_mapping = {"mpoint": "MULTIPOINT"} # The VRT is 3D, but should still be able to map sans the Z. lm = LayerMapping(Point2D, vrt_file, point_mapping, transform=False) lm.save() self.assertEqual(3, Point2D.objects.count()) # The city shapefile is 2D, and won't be able to fill the coordinates # in the 3D model -- thus, a LayerMapError is raised. with self.assertRaises(LayerMapError): LayerMapping(Point3D, city_file, point_mapping, transform=False) # 3D model should take 3D data just fine. lm = LayerMapping(Point3D, vrt_file, point_mapping, transform=False) lm.save() self.assertEqual(3, Point3D.objects.count()) # Making sure LayerMapping.make_multi works right, by converting # a Point25D into a MultiPoint25D. lm = LayerMapping(MultiPoint3D, vrt_file, mpoint_mapping, transform=False) lm.save() self.assertEqual(3, MultiPoint3D.objects.count()) def test_bulk_create_point_field(self): objs = Point2D.objects.bulk_create([Point2D(), Point2D()]) self.assertEqual(len(objs), 2) @skipUnlessDBFeature("supports_3d_functions") def test_union(self): """ Testing the Union aggregate of 3D models. """ # PostGIS query that returned the reference EWKT for this test: # `SELECT ST_AsText(ST_Union(point)) FROM geo3d_city3d;` self._load_city_data() ref_ewkt = ( "SRID=4326;MULTIPOINT(-123.305196 48.462611 15,-104.609252 38.255001 1433," "-97.521157 34.464642 380,-96.801611 32.782057 147,-95.363151 29.763374 18," "-95.23506 38.971823 251,-87.650175 41.850385 181,174.783117 -41.315268 14)" ) ref_union = GEOSGeometry(ref_ewkt) union = City3D.objects.aggregate(Union("point"))["point__union"] self.assertTrue(union.hasz) # Ordering of points in the resulting geometry may vary between # implementations self.assertEqual({p.ewkt for p in ref_union}, {p.ewkt for p in union}) @skipUnlessDBFeature("supports_3d_functions") def test_extent(self): """ Testing the Extent3D aggregate for 3D models. """ self._load_city_data() # `SELECT ST_Extent3D(point) FROM geo3d_city3d;` ref_extent3d = (-123.305196, -41.315268, 14, 174.783117, 48.462611, 1433) extent = City3D.objects.aggregate(Extent3D("point"))["point__extent3d"] def check_extent3d(extent3d, tol=6): for ref_val, ext_val in zip(ref_extent3d, extent3d): self.assertAlmostEqual(ref_val, ext_val, tol) check_extent3d(extent) self.assertIsNone( City3D.objects.none().aggregate(Extent3D("point"))["point__extent3d"] ) @skipUnlessDBFeature("supports_3d_functions") def test_extent3d_filter(self): self._load_city_data() extent3d = City3D.objects.aggregate( ll_cities=Extent3D("point", filter=Q(name__contains="ll")) )["ll_cities"] ref_extent3d = (-96.801611, -41.315268, 14.0, 174.783117, 32.782057, 147.0) for ref_val, ext_val in zip(ref_extent3d, extent3d): self.assertAlmostEqual(ref_val, ext_val, 6) @skipUnlessDBFeature("supports_3d_functions") class Geo3DFunctionsTests(FuncTestMixin, Geo3DLoadingHelper, TestCase): def test_kml(self): """ Test KML() function with Z values. """ self._load_city_data() h = City3D.objects.annotate(kml=AsKML("point", precision=6)).get(name="Houston") # KML should be 3D. # `SELECT ST_AsKML(point, 6) FROM geo3d_city3d WHERE name = 'Houston';` ref_kml_regex = re.compile( r"^<Point><coordinates>-95.363\d+,29.763\d+,18</coordinates></Point>$" ) self.assertTrue(ref_kml_regex.match(h.kml)) def test_geojson(self): """ Test GeoJSON() function with Z values. """ self._load_city_data() h = City3D.objects.annotate(geojson=AsGeoJSON("point", precision=6)).get( name="Houston" ) # GeoJSON should be 3D # `SELECT ST_AsGeoJSON(point, 6) FROM geo3d_city3d # WHERE name='Houston';` ref_json_regex = re.compile( r'^{"type":"Point","coordinates":\[-95.363151,29.763374,18(\.0+)?\]}$' ) self.assertTrue(ref_json_regex.match(h.geojson)) def test_perimeter(self): """ Testing Perimeter() function on 3D fields. """ self._load_polygon_data() # Reference query for values below: # `SELECT ST_Perimeter3D(poly), ST_Perimeter2D(poly) # FROM geo3d_polygon3d;` ref_perim_3d = 76859.2620451 ref_perim_2d = 76859.2577803 tol = 6 poly2d = Polygon2D.objects.annotate(perimeter=Perimeter("poly")).get( name="2D BBox" ) self.assertAlmostEqual(ref_perim_2d, poly2d.perimeter.m, tol) poly3d = Polygon3D.objects.annotate(perimeter=Perimeter("poly")).get( name="3D BBox" ) self.assertAlmostEqual(ref_perim_3d, poly3d.perimeter.m, tol) def test_length(self): """ Testing Length() function on 3D fields. """ # ST_Length_Spheroid Z-aware, and thus does not need to use # a separate function internally. # `SELECT ST_Length_Spheroid( # line, 'SPHEROID["GRS 1980",6378137,298.257222101]') # FROM geo3d_interstate[2d|3d];` self._load_interstate_data() tol = 3 ref_length_2d = 4368.1721949481 ref_length_3d = 4368.62547052088 inter2d = Interstate2D.objects.annotate(length=Length("line")).get(name="I-45") self.assertAlmostEqual(ref_length_2d, inter2d.length.m, tol) inter3d = Interstate3D.objects.annotate(length=Length("line")).get(name="I-45") self.assertAlmostEqual(ref_length_3d, inter3d.length.m, tol) # Making sure `ST_Length3D` is used on for a projected # and 3D model rather than `ST_Length`. # `SELECT ST_Length(line) FROM geo3d_interstateproj2d;` ref_length_2d = 4367.71564892392 # `SELECT ST_Length3D(line) FROM geo3d_interstateproj3d;` ref_length_3d = 4368.16897234101 inter2d = InterstateProj2D.objects.annotate(length=Length("line")).get( name="I-45" ) self.assertAlmostEqual(ref_length_2d, inter2d.length.m, tol) inter3d = InterstateProj3D.objects.annotate(length=Length("line")).get( name="I-45" ) self.assertAlmostEqual(ref_length_3d, inter3d.length.m, tol) def test_scale(self): """ Testing Scale() function on Z values. """ self._load_city_data() # Mapping of City name to reference Z values. zscales = (-3, 4, 23) for zscale in zscales: for city in City3D.objects.annotate(scale=Scale("point", 1.0, 1.0, zscale)): self.assertEqual(city_dict[city.name][2] * zscale, city.scale.z) def test_translate(self): """ Testing Translate() function on Z values. """ self._load_city_data() ztranslations = (5.23, 23, -17) for ztrans in ztranslations: for city in City3D.objects.annotate( translate=Translate("point", 0, 0, ztrans) ): self.assertEqual(city_dict[city.name][2] + ztrans, city.translate.z)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geogapp/models.py
tests/gis_tests/geogapp/models.py
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 CityUnique(NamedModel): point = models.PointField(geography=True, unique=True) class Meta: required_db_features = { "supports_geography", "supports_geometry_field_unique_index", } 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])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geogapp/__init__.py
tests/gis_tests/geogapp/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geogapp/tests.py
tests/gis_tests/geogapp/tests.py
""" 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.core.exceptions import ValidationError from django.db import NotSupportedError, connection from django.db.models.functions import Cast from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from ..utils import FuncTestMixin from .models import City, CityUnique, 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) @skipUnlessDBFeature("supports_geography", "supports_geometry_field_unique_index") def test_geography_unique(self): """ Cast geography fields to geometry type when validating uniqueness to remove the reliance on unavailable ~= operator. """ htown = City.objects.get(name="Houston") CityUnique.objects.create(point=htown.point) duplicate = CityUnique(point=htown.point) msg = "City unique with this Point already exists." with self.assertRaisesMessage(ValidationError, msg): duplicate.validate_unique() @skipUnlessDBFeature("supports_geography") def test_operators_functions_unavailable_for_geography(self): """ Geography fields are cast to geometry if the relevant operators or functions are not available. """ z = Zipcode.objects.get(code="77002") point_field = "%s.%s::geometry" % ( connection.ops.quote_name(City._meta.db_table), connection.ops.quote_name("point"), ) # ST_Within. qs = City.objects.filter(point__within=z.poly) with CaptureQueriesContext(connection) as ctx: self.assertEqual(qs.count(), 1) self.assertIn(f"ST_Within({point_field}", ctx.captured_queries[0]["sql"]) # @ operator. qs = City.objects.filter(point__contained=z.poly) with CaptureQueriesContext(connection) as ctx: self.assertEqual(qs.count(), 1) self.assertIn(f"{point_field} @", ctx.captured_queries[0]["sql"]) # ~= operator. htown = City.objects.get(name="Houston") qs = City.objects.filter(point__exact=htown.point) with CaptureQueriesContext(connection) as ctx: self.assertEqual(qs.count(), 1) self.assertIn(f"{point_field} ~=", ctx.captured_queries[0]["sql"]) 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")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geoadmin/models.py
tests/gis_tests/geoadmin/models.py
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)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geoadmin/__init__.py
tests/gis_tests/geoadmin/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geoadmin/tests.py
tests/gis_tests/geoadmin/tests.py
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.get_model_admin(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" hidden></textarea>', output, ) def test_widget_invalid_string(self): geoadmin = self.admin_site.get_model_admin(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" hidden></textarea>', output, ) self.assertEqual(len(cm.records), 2) 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.get_model_admin(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.get_model_admin(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.get_model_admin(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)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geoadmin/urls.py
tests/gis_tests/geoadmin/urls.py
from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", include(admin.site.urls)), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/layermap/models.py
tests/gis_tests/layermap/models.py
from django.contrib.gis.db import models class NamedModel(models.Model): name = models.CharField(max_length=25) class Meta: abstract = True def __str__(self): return self.name class State(NamedModel): pass class County(NamedModel): state = models.ForeignKey(State, models.CASCADE) mpoly = models.MultiPolygonField(srid=4269, null=True) # Multipolygon in NAD83 class CountyFeat(NamedModel): poly = models.PolygonField(srid=4269) class City(NamedModel): name_txt = models.TextField(default="") name_short = models.CharField(max_length=5) population = models.IntegerField() density = models.DecimalField(max_digits=7, decimal_places=1) dt = models.DateField() point = models.PointField() class Meta: app_label = "layermap" class Interstate(NamedModel): length = models.DecimalField(max_digits=6, decimal_places=2) path = models.LineStringField() class Meta: app_label = "layermap" # Same as `City` above, but for testing model inheritance. class CityBase(NamedModel): population = models.IntegerField() density = models.DecimalField(max_digits=7, decimal_places=1) point = models.PointField() class ICity1(CityBase): dt = models.DateField() class Meta(CityBase.Meta): pass class ICity2(ICity1): dt_time = models.DateTimeField(auto_now=True) class Meta(ICity1.Meta): pass class Invalid(models.Model): point = models.PointField() class HasNulls(models.Model): uuid = models.UUIDField(primary_key=True, editable=False) geom = models.PolygonField(srid=4326, blank=True, null=True) datetime = models.DateTimeField(blank=True, null=True) integer = models.IntegerField(blank=True, null=True) num = models.FloatField(blank=True, null=True) boolean = models.BooleanField(blank=True, null=True) name = models.CharField(blank=True, null=True, max_length=20) class DoesNotAllowNulls(models.Model): uuid = models.UUIDField(primary_key=True, editable=False) geom = models.PolygonField(srid=4326) datetime = models.DateTimeField() integer = models.IntegerField() num = models.FloatField() boolean = models.BooleanField() name = models.CharField(max_length=20) # Mapping dictionaries for the models above. co_mapping = { "name": "Name", # ForeignKey's use another mapping dictionary for the _related_ Model # (State in this case). "state": {"name": "State"}, "mpoly": "MULTIPOLYGON", # Will convert POLYGON features into MULTIPOLYGONS. } cofeat_mapping = { "name": "Name", "poly": "POLYGON", } city_mapping = { "name": "Name", "population": "Population", "density": "Density", "dt": "Created", "point": "POINT", } inter_mapping = { "name": "Name", "length": "Length", "path": "LINESTRING", } has_nulls_mapping = { "geom": "POLYGON", "uuid": "uuid", "datetime": "datetime", "name": "name", "integer": "integer", "num": "num", "boolean": "boolean", }
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/layermap/__init__.py
tests/gis_tests/layermap/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/layermap/tests.py
tests/gis_tests/layermap/tests.py
import datetime import unittest from copy import copy from decimal import Decimal from pathlib import Path from django.conf import settings from django.contrib.gis.gdal import DataSource from django.contrib.gis.utils.layermapping import ( InvalidDecimal, InvalidString, LayerMapError, LayerMapping, MissingForeignKey, ) from django.db import connection from django.test import TestCase, override_settings from .models import ( City, County, CountyFeat, DoesNotAllowNulls, HasNulls, ICity1, ICity2, Interstate, Invalid, State, city_mapping, co_mapping, cofeat_mapping, has_nulls_mapping, inter_mapping, ) shp_path = Path(__file__).resolve().parent.parent / "data" city_shp = shp_path / "cities" / "cities.shp" co_shp = shp_path / "counties" / "counties.shp" inter_shp = shp_path / "interstates" / "interstates.shp" invalid_shp = shp_path / "invalid" / "emptypoints.shp" has_nulls_geojson = shp_path / "has_nulls" / "has_nulls.geojson" # Dictionaries to hold what's expected in the county shapefile. NAMES = ["Bexar", "Galveston", "Harris", "Honolulu", "Pueblo"] NUMS = [1, 2, 1, 19, 1] # Number of polygons for each. STATES = ["Texas", "Texas", "Texas", "Hawaii", "Colorado"] class LayerMapTest(TestCase): def test_init(self): "Testing LayerMapping initialization." # Model field that does not exist. bad1 = copy(city_mapping) bad1["foobar"] = "FooField" # Shapefile field that does not exist. bad2 = copy(city_mapping) bad2["name"] = "Nombre" # Nonexistent geographic field type. bad3 = copy(city_mapping) bad3["point"] = "CURVE" # Incrementing through the bad mapping dictionaries and # ensuring that a LayerMapError is raised. for bad_map in (bad1, bad2, bad3): with self.assertRaises(LayerMapError): LayerMapping(City, city_shp, bad_map) # A LookupError should be thrown for bogus encodings. with self.assertRaises(LookupError): LayerMapping(City, city_shp, city_mapping, encoding="foobar") def test_simple_layermap(self): "Test LayerMapping import of a simple point shapefile." # Setting up for the LayerMapping. lm = LayerMapping(City, city_shp, city_mapping) lm.save() # There should be three cities in the shape file. self.assertEqual(3, City.objects.count()) # Opening up the shapefile, and verifying the values in each # of the features made it to the model. ds = DataSource(city_shp) layer = ds[0] for feat in layer: city = City.objects.get(name=feat["Name"].value) self.assertEqual(feat["Population"].value, city.population) self.assertEqual(Decimal(str(feat["Density"])), city.density) self.assertEqual(feat["Created"].value, city.dt) # Comparing the geometries. pnt1, pnt2 = feat.geom, city.point self.assertAlmostEqual(pnt1.x, pnt2.x, 5) self.assertAlmostEqual(pnt1.y, pnt2.y, 5) def test_data_source_str(self): lm = LayerMapping(City, str(city_shp), city_mapping) lm.save() self.assertEqual(City.objects.count(), 3) def test_layermap_strict(self): "Testing the `strict` keyword, and import of a LineString shapefile." # When the `strict` keyword is set an error encountered will force # the importation to stop. with self.assertRaises(InvalidDecimal): lm = LayerMapping(Interstate, inter_shp, inter_mapping) lm.save(silent=True, strict=True) Interstate.objects.all().delete() # This LayerMapping should work b/c `strict` is not set. lm = LayerMapping(Interstate, inter_shp, inter_mapping) lm.save(silent=True) # Two interstate should have imported correctly. self.assertEqual(2, Interstate.objects.count()) # Verifying the values in the layer w/the model. ds = DataSource(inter_shp) # Only the first two features of this shapefile are valid. valid_feats = ds[0][:2] for feat in valid_feats: istate = Interstate.objects.get(name=feat["Name"].value) if feat.fid == 0: self.assertEqual(Decimal(str(feat["Length"])), istate.length) elif feat.fid == 1: # Everything but the first two decimal digits were truncated, # because the Interstate model's `length` field has # decimal_places=2. self.assertAlmostEqual(feat.get("Length"), float(istate.length), 2) for p1, p2 in zip(feat.geom, istate.path): self.assertAlmostEqual(p1[0], p2[0], 6) self.assertAlmostEqual(p1[1], p2[1], 6) def county_helper(self, county_feat=True): """ Helper function for ensuring the integrity of the mapped County models. """ for name, n, st in zip(NAMES, NUMS, STATES): # Should only be one record b/c of `unique` keyword. c = County.objects.get(name=name) self.assertEqual(n, len(c.mpoly)) self.assertEqual(st, c.state.name) # Checking ForeignKey mapping. # Multiple records because `unique` was not set. if county_feat: qs = CountyFeat.objects.filter(name=name) self.assertEqual(n, qs.count()) def test_layermap_unique_multigeometry_fk(self): """ The `unique`, and `transform`, geometry collection conversion, and ForeignKey mappings. """ # All the following should work. # Telling LayerMapping that we want no transformations performed on the # data. lm = LayerMapping(County, co_shp, co_mapping, transform=False) # Specifying the source spatial reference system via the `source_srs` # keyword. lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269) lm = LayerMapping(County, co_shp, co_mapping, source_srs="NAD83") # Unique may take tuple or string parameters. for arg in ("name", ("name", "mpoly")): lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg) # Now test for failures # Testing invalid params for the `unique` keyword. for e, arg in ( (TypeError, 5.0), (ValueError, "foobar"), (ValueError, ("name", "mpolygon")), ): with self.assertRaises(e): LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg) # No source reference system defined in the shapefile, should raise an # error. if connection.features.supports_transform: with self.assertRaises(LayerMapError): LayerMapping(County, co_shp, co_mapping) # Passing in invalid ForeignKey mapping parameters -- must be a # dictionary mapping for the model the ForeignKey points to. bad_fk_map1 = copy(co_mapping) bad_fk_map1["state"] = "name" bad_fk_map2 = copy(co_mapping) bad_fk_map2["state"] = {"nombre": "State"} with self.assertRaises(TypeError): LayerMapping(County, co_shp, bad_fk_map1, transform=False) with self.assertRaises(LayerMapError): LayerMapping(County, co_shp, bad_fk_map2, transform=False) # There exist no State models for the ForeignKey mapping to work -- # should raise a MissingForeignKey exception (this error would be # ignored if the `strict` keyword is not set). lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique="name") with self.assertRaises(MissingForeignKey): lm.save(silent=True, strict=True) # Now creating the state models so the ForeignKey mapping may work. State.objects.bulk_create( [State(name="Colorado"), State(name="Hawaii"), State(name="Texas")] ) # If a mapping is specified as a collection, all OGR fields that # are not collections will be converted into them. For example, a Point # column would be converted to MultiPoint. Other things being done # w/the keyword args: # `transform=False`: Specifies that no transform is to be done; this # has the effect of ignoring the spatial reference check (because # the county shapefile does not have implicit spatial reference # info). # # `unique='name'`: Creates models on the condition that they have # unique county names; geometries from each feature however will be # appended to the geometry collection of the unique model. Thus, # all of the various islands in Honolulu county will be in one # database record with a MULTIPOLYGON type. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique="name") lm.save(silent=True, strict=True) # A reference that doesn't use the unique keyword; a new database # record will created for each polygon. lm = LayerMapping(CountyFeat, co_shp, cofeat_mapping, transform=False) lm.save(silent=True, strict=True) # The county helper is called to ensure integrity of County models. self.county_helper() def test_test_fid_range_step(self): "Tests the `fid_range` keyword and the `step` keyword of .save()." # Function for clearing out all the counties before testing. def clear_counties(): County.objects.all().delete() State.objects.bulk_create( [State(name="Colorado"), State(name="Hawaii"), State(name="Texas")] ) # Initializing the LayerMapping object to use in these tests. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique="name") # Bad feature id ranges should raise a type error. bad_ranges = (5.0, "foo", co_shp) for bad in bad_ranges: with self.assertRaises(TypeError): lm.save(fid_range=bad) # Step keyword should not be allowed w/`fid_range`. fr = (3, 5) # layer[3:5] with self.assertRaises(LayerMapError): lm.save(fid_range=fr, step=10) lm.save(fid_range=fr) # Features IDs 3 & 4 are for Galveston County, Texas -- only # one model is returned because the `unique` keyword was set. qs = County.objects.all() self.assertEqual(1, qs.count()) self.assertEqual("Galveston", qs[0].name) # Features IDs 5 and beyond for Honolulu County, Hawaii, and # FID 0 is for Pueblo County, Colorado. clear_counties() lm.save(fid_range=slice(5, None), silent=True, strict=True) # layer[5:] lm.save(fid_range=slice(None, 1), silent=True, strict=True) # layer[:1] # Only Pueblo & Honolulu counties should be present because of # the `unique` keyword. Have to set `order_by` on this QuerySet # or else MySQL will return a different ordering than the other dbs. qs = County.objects.order_by("name") self.assertEqual(2, qs.count()) hi, co = tuple(qs) hi_idx, co_idx = tuple(map(NAMES.index, ("Honolulu", "Pueblo"))) self.assertEqual("Pueblo", co.name) self.assertEqual(NUMS[co_idx], len(co.mpoly)) self.assertEqual("Honolulu", hi.name) self.assertEqual(NUMS[hi_idx], len(hi.mpoly)) # Testing the `step` keyword -- should get the same counties # regardless of we use a step that divides equally, that is odd, # or that is larger than the dataset. for st in (4, 7, 1000): clear_counties() lm.save(step=st, strict=True) self.county_helper(county_feat=False) def test_model_inheritance(self): "Tests LayerMapping on inherited models. See #12093." icity_mapping = { "name": "Name", "population": "Population", "density": "Density", "point": "POINT", "dt": "Created", } # Parent model has geometry field. lm1 = LayerMapping(ICity1, city_shp, icity_mapping) lm1.save() # Grandparent has geometry field. lm2 = LayerMapping(ICity2, city_shp, icity_mapping) lm2.save() self.assertEqual(6, ICity1.objects.count()) self.assertEqual(3, ICity2.objects.count()) def test_invalid_layer(self): "Tests LayerMapping on invalid geometries. See #15378." invalid_mapping = {"point": "POINT"} lm = LayerMapping(Invalid, invalid_shp, invalid_mapping, source_srs=4326) lm.save(silent=True) def test_charfield_too_short(self): mapping = copy(city_mapping) mapping["name_short"] = "Name" lm = LayerMapping(City, city_shp, mapping) with self.assertRaises(InvalidString): lm.save(silent=True, strict=True) def test_textfield(self): "String content fits also in a TextField" mapping = copy(city_mapping) mapping["name_txt"] = "Name" lm = LayerMapping(City, city_shp, mapping) lm.save(silent=True, strict=True) self.assertEqual(City.objects.count(), 3) self.assertEqual(City.objects.get(name="Houston").name_txt, "Houston") def test_encoded_name(self): """Test a layer containing utf-8-encoded name""" city_shp = shp_path / "ch-city" / "ch-city.shp" lm = LayerMapping(City, city_shp, city_mapping) lm.save(silent=True, strict=True) self.assertEqual(City.objects.count(), 1) self.assertEqual(City.objects.all()[0].name, "Zürich") def test_null_geom_with_unique(self): """LayerMapping may be created with a unique and a null geometry.""" State.objects.bulk_create( [State(name="Colorado"), State(name="Hawaii"), State(name="Texas")] ) hw = State.objects.get(name="Hawaii") hu = County.objects.create(name="Honolulu", state=hw, mpoly=None) lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique="name") lm.save(silent=True, strict=True) hu.refresh_from_db() self.assertIsNotNone(hu.mpoly) self.assertEqual(hu.mpoly.ogr.num_coords, 449) def test_null_number_imported(self): """LayerMapping import of GeoJSON with a null numeric value.""" lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual(HasNulls.objects.count(), 3) self.assertEqual(HasNulls.objects.filter(num=0).count(), 1) self.assertEqual(HasNulls.objects.filter(num__isnull=True).count(), 1) def test_null_string_imported(self): "Test LayerMapping import of GeoJSON with a null string value." lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual(HasNulls.objects.filter(name="None").count(), 0) num_empty = 1 if connection.features.interprets_empty_strings_as_nulls else 0 self.assertEqual(HasNulls.objects.filter(name="").count(), num_empty) self.assertEqual(HasNulls.objects.filter(name__isnull=True).count(), 1) def test_nullable_boolean_imported(self): """LayerMapping import of GeoJSON with a nullable boolean value.""" lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual(HasNulls.objects.filter(boolean=True).count(), 1) self.assertEqual(HasNulls.objects.filter(boolean=False).count(), 1) self.assertEqual(HasNulls.objects.filter(boolean__isnull=True).count(), 1) def test_nullable_datetime_imported(self): """LayerMapping import of GeoJSON with a nullable date/time value.""" lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual( HasNulls.objects.filter(datetime__lt=datetime.date(1994, 8, 15)).count(), 1 ) self.assertEqual( HasNulls.objects.filter(datetime="2018-11-29T03:02:52").count(), 1 ) self.assertEqual(HasNulls.objects.filter(datetime__isnull=True).count(), 1) def test_uuids_imported(self): """LayerMapping import of GeoJSON with UUIDs.""" lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual( HasNulls.objects.filter( uuid="1378c26f-cbe6-44b0-929f-eb330d4991f5" ).count(), 1, ) def test_null_number_imported_not_allowed(self): """ LayerMapping import of GeoJSON with nulls to fields that don't permit them. """ lm = LayerMapping(DoesNotAllowNulls, has_nulls_geojson, has_nulls_mapping) lm.save(silent=True) # When a model fails to save due to IntegrityError (null in non-null # column), subsequent saves fail with "An error occurred in the current # transaction. You can't execute queries until the end of the 'atomic' # block." On Oracle and MySQL, the one object that did load appears in # this count. On other databases, no records appear. self.assertLessEqual(DoesNotAllowNulls.objects.count(), 1) class OtherRouter: def db_for_read(self, model, **hints): return "other" def db_for_write(self, model, **hints): return self.db_for_read(model, **hints) def allow_relation(self, obj1, obj2, **hints): # ContentType objects are created during a post-migrate signal while # performing fixture teardown using the default database alias and # don't abide by the database specified by this router. return True def allow_migrate(self, db, app_label, **hints): return True @override_settings(DATABASE_ROUTERS=[OtherRouter()]) class LayerMapRouterTest(TestCase): databases = {"default", "other"} @unittest.skipUnless(len(settings.DATABASES) > 1, "multiple databases required") def test_layermapping_default_db(self): lm = LayerMapping(City, city_shp, city_mapping) self.assertEqual(lm.using, "other")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geos_tests/test_io.py
tests/gis_tests/geos_tests/test_io.py
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): with self.subTest(geom=geom): self.assertEqual(ref, geom) # Should only accept string objects. bad_input = (1, 5.23, None, False, memoryview(b"foo")) msg = "'wkt' must be bytes or str (got {} instead)." for bad_wkt in bad_input: with ( self.subTest(bad_wkt=bad_wkt), self.assertRaisesMessage(TypeError, msg.format(bad_wkt)), ): wkt_r.read(bad_wkt) def test02_wktwriter(self): # Creating a WKTWriter instance, testing its ptr property. wkt_w = WKTWriter() msg = "Incompatible pointer type: " with self.assertRaisesMessage(TypeError, msg): 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_bin = b"000000000140140000000000004037000000000000" hex_str = "000000000140140000000000004037000000000000" wkb = memoryview(binascii.a2b_hex(hex_bin)) ref = GEOSGeometry(hex_bin) # read() should return a GEOSGeometry on either a hex string or # a WKB buffer. g1 = wkb_r.read(wkb) g2 = wkb_r.read(hex_bin) g3 = wkb_r.read(hex_str) for geom in (g1, g2, g3): with self.subTest(geom=geom): self.assertEqual(ref, geom) bad_input = (1, 5.23, None, False) msg = "'wkb' must be bytes, str or memoryview (got {} instead)." for bad_wkb in bad_input: with ( self.subTest(bad_wkb=bad_wkb), self.assertRaisesMessage(TypeError, msg.format(bad_wkb)), ): 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. msg = "Byte order parameter must be 0 (Big Endian) or 1 (Little Endian)." for bad_byteorder in (-1, 2, 523, "foo", None): # Equivalent of `wkb_w.byteorder = bad_byteorder` with ( self.subTest(bad_byteorder=bad_byteorder), self.assertRaisesMessage(ValueError, msg), ): 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 msg = "WKB output dimension must be 2 or 3" for bad_outdim in (-1, 0, 1, 4, 423, "foo", None): with ( self.subTest(bad_outdim=bad_outdim), self.assertRaisesMessage(ValueError, msg), ): 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 with self.subTest(byteorder=byteorder, hexes=hexes): 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 )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geos_tests/test_geos_mutation.py
tests/gis_tests/geos_tests/test_geos_mutation.py
# 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. from django.contrib.gis.geos import ( LinearRing, LineString, MultiPoint, Point, Polygon, fromstr, ) from django.test import SimpleTestCase def api_get_distance(x): return x.distance(Point(-200, -200)) def api_get_buffer(x): return x.buffer(10) def api_get_geom_typeid(x): return x.geom_typeid def api_get_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(SimpleTestCase): """ 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): with self.subTest(i=i): p._checkindex(i) for i in (2, -3): with ( self.subTest(i=i), self.assertRaisesMessage(IndexError, f"invalid index: {i}"), ): p._checkindex(i) def test01_PointMutations(self): "Testing Point mutations" for p in (Point(1, 2, 3), fromstr("POINT (1 2 3)")): with self.subTest(p=p): 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" msg = "Invalid parameters given for Point initialization." for i in (range(1), range(4)): with ( self.subTest(i=i), self.assertRaisesMessage(TypeError, msg), ): Point(i) 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: with self.subTest(p=p, f=f): 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)"), ): with self.subTest(ls=ls): 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: with self.subTest(f=f): 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))"), ): with self.subTest(pg=pg): 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: with self.subTest(f=f): 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: with self.subTest(mp=mp): 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: with self.subTest(f=f): self.assertEqual(f(lsa), f(mp), "MultiPoint " + f.__name__)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geos_tests/test_coordseq.py
tests/gis_tests/geos_tests/test_coordseq.py
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 = f"Invalid GEOS Geometry index: {i}" with self.subTest(i): with self.assertRaisesMessage(IndexError, msg): coord_seq[i]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geos_tests/test_geos.py
tests/gis_tests/geos_tests/test_geos.py
import ctypes import itertools import json import math 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 django.utils.version import PY312 from ..test_data import TestDataMixin class GEOSTest(SimpleTestCase, TestDataMixin): error_checking_geom = ( 'Error encountered checking Geometry returned from GEOS C function "{}".' ) def assertArgumentTypeError(self, i, bad_type): if PY312: msg = ( f"argument {i}: TypeError: '{bad_type}' object cannot be interpreted " "as an integer" ) else: msg = f"argument {i}: TypeError: wrong type" return self.assertRaisesMessage(ctypes.ArgumentError, msg) def test_wkt(self): "Testing WKT output." for g in self.geometries.wkt_out: with self.subTest(g=g): 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: with self.subTest(g=g): 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: with self.subTest(tg=tg): self.assertEqual(kml, geom.kml) def test_errors(self): "Testing the Error handlers." # string-based for err in self.geometries.errors: with ( self.subTest(err=err.wkt), self.assertRaisesMessage((GEOSException, ValueError), err.msg), ): fromstr(err.wkt) # Bad WKB with self.assertRaisesMessage( GEOSException, self.error_checking_geom.format("GEOSWKBReader_read_r") ): GEOSGeometry(memoryview(b"0")) class NotAGeometry: pass for geom in (NotAGeometry(), None): msg = f"Improper geometry input type: {type(geom)}" with ( self.subTest(geom=geom), self.assertRaisesMessage(TypeError, msg), ): GEOSGeometry(geom) 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) with self.subTest(g=g): 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) with self.subTest(g=g): 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) with self.subTest(p=p): 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) with self.subTest(g=g): 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) with self.subTest(fh=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): with self.subTest(g=g): 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)") @skipIf(geos_version_tuple() < (3, 12), "GEOS >= 3.12.0 is required") def test_equals_identical(self): tests = [ # Empty inputs of different types are not equals_identical. ("POINT EMPTY", "LINESTRING EMPTY", False), # Empty inputs of different dimensions are not equals_identical. ("POINT EMPTY", "POINT Z EMPTY", False), # Non-empty inputs of different dimensions are not # equals_identical. ("POINT Z (1 2 3)", "POINT M (1 2 3)", False), ("POINT ZM (1 2 3 4)", "POINT Z (1 2 3)", False), # Inputs with different structure are not equals_identical. ("LINESTRING (1 1, 2 2)", "MULTILINESTRING ((1 1, 2 2))", False), # Inputs with different types are not equals_identical. ( "GEOMETRYCOLLECTION (LINESTRING (1 1, 2 2))", "MULTILINESTRING ((1 1, 2 2))", False, ), # Same lines are equals_identical. ("LINESTRING M (1 1 0, 2 2 1)", "LINESTRING M (1 1 0, 2 2 1)", True), # Different lines are not equals_identical. ("LINESTRING M (1 1 0, 2 2 1)", "LINESTRING M (1 1 1, 2 2 1)", False), # Same polygons are equals_identical. ("POLYGON ((0 0, 1 0, 1 1, 0 0))", "POLYGON ((0 0, 1 0, 1 1, 0 0))", True), # Different polygons are not equals_identical. ("POLYGON ((0 0, 1 0, 1 1, 0 0))", "POLYGON ((1 0, 1 1, 0 0, 1 0))", False), # Different polygons (number of holes) are not equals_identical. ( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (1 1, 2 1, 2 2, 1 1))", ( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (1 1, 2 1, 2 2, 1 1), " "(3 3, 4 3, 4 4, 3 3))" ), False, ), # Same collections are equals_identical. ( "MULTILINESTRING ((1 1, 2 2), (2 2, 3 3))", "MULTILINESTRING ((1 1, 2 2), (2 2, 3 3))", True, ), # Different collections (structure) are not equals_identical. ( "MULTILINESTRING ((1 1, 2 2), (2 2, 3 3))", "MULTILINESTRING ((2 2, 3 3), (1 1, 2 2))", False, ), ] for g1, g2, is_equal_identical in tests: with self.subTest(g1=g1, g2=g2): self.assertIs( fromstr(g1).equals_identical(fromstr(g2)), is_equal_identical ) @skipIf(geos_version_tuple() < (3, 12), "GEOS >= 3.12.0 is required") def test_infinite_values_equals_identical(self): # Input with identical infinite values are equals_identical. g1 = Point(x=float("nan"), y=math.inf) g2 = Point(x=float("nan"), y=math.inf) self.assertIs(g1.equals_identical(g2), True) @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.11.0") def test_equals_identical_geos_version(self): g1 = fromstr("POINT (1 2 3)") g2 = fromstr("POINT (1 2 3)") msg = "GEOSGeometry.equals_identical() requires GEOS >= 3.12.0" with self.assertRaisesMessage(GEOSException, msg): g1.equals_identical(g2) @skipIf(geos_version_tuple() < (3, 12), "GEOS >= 3.12.0 is required") def test_hasm(self): pnt_xym = fromstr("POINT M (5 23 8)") self.assertTrue(pnt_xym.hasm) pnt_xyzm = fromstr("POINT (5 23 8 0)") self.assertTrue(pnt_xyzm.hasm) @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.11.0") def test_hasm_geos_version(self): p = fromstr("POINT (1 2 3)") msg = "GEOSGeometry.hasm requires GEOS >= 3.12.0." with self.assertRaisesMessage(GEOSException, msg): p.hasm 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) with self.subTest(p=p): 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) with self.subTest(mp=mp): 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) mpnt_len = len(mpnt) msg = f"invalid index: {mpnt_len}" with self.assertRaisesMessage(IndexError, msg): mpnt.__getitem__(mpnt_len) 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) with self.subTest(line=line): 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__. ls_len = len(ls) msg = f"invalid index: {ls_len}" with self.assertRaisesMessage(IndexError, msg): ls.__getitem__(ls_len) 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 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 def test_multilinestring(self): "Testing MultiLineString objects." prev = fromstr("POINT(0 0)") for line in self.geometries.multilinestrings: ml = fromstr(line.wkt) with self.subTest(line=line): 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) ml_len = len(ml) msg = f"invalid index: {ml_len}" with self.assertRaisesMessage(IndexError, msg): ml.__getitem__(ml_len) 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) with self.subTest(rr=rr): 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) with self.subTest(p=p): 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 poly_len = len(poly) msg = f"invalid index: {poly_len}" with self.assertRaisesMessage(IndexError, msg): poly.__getitem__(poly_len) with self.assertRaisesMessage(IndexError, msg): poly.__setitem__(poly_len, False) negative_index = -1 * poly_len - 1 msg = f"invalid index: {negative_index}" with self.assertRaisesMessage(IndexError, msg): poly.__getitem__(negative_index) # Testing __iter__ for r in poly: self.assertEqual(r.geom_type, "LinearRing") self.assertEqual(r.geom_typeid, 2) # Testing polygon construction. msg = ( "Parameter must be a sequence of LinearRings or " "objects that can initialize to LinearRings." ) with self.assertRaisesMessage(TypeError, msg): Polygon(0, [1, 2, 3]) with self.assertRaisesMessage(TypeError, msg): 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) with self.subTest(mp=mp): 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: mpoly_len = len(mpoly) self.assertEqual(mp.num_geom, mpoly.num_geom) self.assertEqual(mp.n_p, mpoly.num_coords) self.assertEqual(mp.num_geom, mpoly_len) msg = f"invalid index: {mpoly_len}" with self.assertRaisesMessage(IndexError, msg): mpoly.__getitem__(mpoly_len) 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: with self.subTest(p=p): 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 expected_value, coord_sequence in zip(p.ext_ring_cs, cs): self.assertEqual(expected_value, coord_sequence) # Construct the test value to set the coordinate # sequence with if len(expected_value) == 2: tset = (5, 23) else: tset = (5, 23, 8) coord_sequence = tset # Making sure every set point matches what we expect self.assertEqual(tset, coord_sequence) def test_relate_pattern(self): "Testing relate() and relate_pattern()." g = fromstr("POINT (0 0)") msg = "Invalid intersection matrix pattern." with self.assertRaisesMessage(GEOSException, msg): g.relate_pattern(0, "invalid pattern, yo")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geos_tests/__init__.py
tests/gis_tests/geos_tests/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geos_tests/test_mutable_list.py
tests/gis_tests/geos_tests/test_mutable_list.py
# 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. from django.contrib.gis.geos.mutable_list import ListMixin from django.test import SimpleTestCase 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(SimpleTestCase): """ 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): with self.subTest(i=i): 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(): with self.subTest(k=k): 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) with self.subTest(slen=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]) msg = ( f"attempt to assign sequence of size {sliceLen + 1} " f"to extended slice of size {sliceLen}" ) with self.assertRaisesMessage(ValueError, msg): setfcn(ul, i, j, k, sliceLen + 1) if sliceLen > 2: msg = ( f"attempt to assign sequence of size {sliceLen - 1}" f" to extended slice of size {sliceLen}" ) with self.assertRaisesMessage(ValueError, msg): 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) with self.subTest(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): with self.subTest(i=i): 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 with self.subTest(i=i): 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] with self.subTest(i=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): msg = f"invalid index: {i}" with self.subTest(i=i): with self.assertRaisesMessage(IndexError, msg): setfcn(ul, i) with self.assertRaisesMessage(IndexError, msg): getfcn(ul, i) with self.assertRaisesMessage(IndexError, msg): 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) with self.subTest(i=i): self.assertEqual(pl[:], ul[:], "insert at %d" % i) for i in self.limits_plus(0): pl, ul = self.lists_of_len() with self.subTest(i=i): 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.assertRaisesMessage(IndexError, "invalid index: 3"): popfcn(ul, self.limit) with self.assertRaisesMessage(IndexError, "invalid index: -4"): popfcn(ul, -1 - self.limit) pl, ul = self.lists_of_len() for val in range(self.limit): with self.subTest(val=val): self.assertEqual(pl.index(val), ul.index(val), "index of %d" % val) for val in self.limits_plus(2): with self.subTest(val=val): 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) with self.subTest(val=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) msg = "40 not found in object" with self.assertRaisesMessage(ValueError, msg): indexfcn(ul, 40) with self.assertRaisesMessage(ValueError, msg): 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 msg = "Invalid type encountered in the arguments." with self.assertRaisesMessage(TypeError, msg): setfcn(ul, 2, "hello") with self.assertRaisesMessage(TypeError, msg): 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] = [] msg = "Must have at least 3 items" for i in range(len(ul) - ul._minlength + 1, len(ul)): with self.subTest(i=i): with self.assertRaisesMessage(ValueError, msg): delfcn(ul, i) with self.assertRaisesMessage(ValueError, msg): setfcn(ul, i) del ul[: len(ul) - ul._minlength] ul._maxlength = 4 for i in range(0, ul._maxlength - len(ul)): with self.subTest(i=i): ul.append(i) with self.assertRaisesMessage(ValueError, "Cannot have more than 4 items"): 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.assertRaisesMessage( TypeError, "can only assign an iterable to a slice" ): 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): with self.subTest(i=i): 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.subTest(i=i), self.assertRaisesMessage(IndexError, f"invalid index: {i}"), ): 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
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/gdal_tests/test_geom.py
tests/gis_tests/gdal_tests/test_geom.py
import json import pickle from django.contrib.gis.gdal import ( CoordTransform, GDALException, OGRGeometry, OGRGeomType, SpatialReference, ) from django.contrib.gis.gdal.geometries import CircularString, CurvePolygon from django.contrib.gis.geos import GEOSException 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(4001) # 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_geom_type_repr(self): self.assertEqual(repr(OGRGeomType("point")), "<OGRGeomType: Point>") 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) def test_geometry_types(self): tests = [ ("Point", 1, True), ("LineString", 2, True), ("Polygon", 3, True), ("MultiPoint", 4, True), ("Multilinestring", 5, True), ("MultiPolygon", 6, True), ("GeometryCollection", 7, True), ("CircularString", 8, True), ("CompoundCurve", 9, True), ("CurvePolygon", 10, True), ("MultiCurve", 11, True), ("MultiSurface", 12, True), # 13 (Curve) and 14 (Surface) are abstract types. ("PolyhedralSurface", 15, False), ("TIN", 16, False), ("Triangle", 17, False), ("Linearring", 2, True), # Types 1 - 7 with Z dimension have 2.5D enums. ("Point Z", -2147483647, True), # 1001 ("LineString Z", -2147483646, True), # 1002 ("Polygon Z", -2147483645, True), # 1003 ("MultiPoint Z", -2147483644, True), # 1004 ("Multilinestring Z", -2147483643, True), # 1005 ("MultiPolygon Z", -2147483642, True), # 1006 ("GeometryCollection Z", -2147483641, True), # 1007 ("CircularString Z", 1008, True), ("CompoundCurve Z", 1009, True), ("CurvePolygon Z", 1010, True), ("MultiCurve Z", 1011, True), ("MultiSurface Z", 1012, True), ("PolyhedralSurface Z", 1015, False), ("TIN Z", 1016, False), ("Triangle Z", 1017, False), ("Point M", 2001, True), ("LineString M", 2002, True), ("Polygon M", 2003, True), ("MultiPoint M", 2004, True), ("MultiLineString M", 2005, True), ("MultiPolygon M", 2006, True), ("GeometryCollection M", 2007, True), ("CircularString M", 2008, True), ("CompoundCurve M", 2009, True), ("CurvePolygon M", 2010, True), ("MultiCurve M", 2011, True), ("MultiSurface M", 2012, True), ("PolyhedralSurface M", 2015, False), ("TIN M", 2016, False), ("Triangle M", 2017, False), ("Point ZM", 3001, True), ("LineString ZM", 3002, True), ("Polygon ZM", 3003, True), ("MultiPoint ZM", 3004, True), ("MultiLineString ZM", 3005, True), ("MultiPolygon ZM", 3006, True), ("GeometryCollection ZM", 3007, True), ("CircularString ZM", 3008, True), ("CompoundCurve ZM", 3009, True), ("CurvePolygon ZM", 3010, True), ("MultiCurve ZM", 3011, True), ("MultiSurface ZM", 3012, True), ("PolyhedralSurface ZM", 3015, False), ("TIN ZM", 3016, False), ("Triangle ZM", 3017, False), ] for test in tests: geom_type, num, supported = test with self.subTest(geom_type=geom_type, num=num, supported=supported): if supported: g = OGRGeometry(f"{geom_type} EMPTY") self.assertEqual(g.geom_type.num, num) else: type_ = geom_type.replace(" ", "") msg = f"Unsupported geometry type: {type_}" with self.assertRaisesMessage(TypeError, msg): OGRGeometry(f"{geom_type} EMPTY") def test_is_3d_and_set_3d(self): geom = OGRGeometry("POINT (1 2)") self.assertIs(geom.is_3d, False) geom.set_3d(True) self.assertIs(geom.is_3d, True) self.assertEqual(geom.wkt, "POINT (1 2 0)") geom.set_3d(False) self.assertIs(geom.is_3d, False) self.assertEqual(geom.wkt, "POINT (1 2)") msg = "Input to 'set_3d' must be a boolean, got 'None'" with self.assertRaisesMessage(ValueError, msg): geom.set_3d(None) def test_wkt_and_wkb_output(self): tests = [ # 2D ("POINT (1 2)", "0101000000000000000000f03f0000000000000040"), ( "LINESTRING (30 10,10 30)", "0102000000020000000000000000003e400000000000002" "44000000000000024400000000000003e40", ), ( "POLYGON ((30 10,40 40,20 40,30 10))", "010300000001000000040000000000000000003e400000000000002440000000000000" "44400000000000004440000000000000344000000000000044400000000000003e4000" "00000000002440", ), ( "MULTIPOINT (10 40,40 30)", "0104000000020000000101000000000000000000244000000000000044400101000000" "00000000000044400000000000003e40", ), ( "MULTILINESTRING ((10 10,20 20),(40 40,30 30,40 20))", "0105000000020000000102000000020000000000000000002440000000000000244000" "0000000000344000000000000034400102000000030000000000000000004440000000" "00000044400000000000003e400000000000003e400000000000004440000000000000" "3440", ), ( "MULTIPOLYGON (((30 20,45 40,10 40,30 20)),((15 5,40 10,10 20,15 5)))", "010600000002000000010300000001000000040000000000000000003e400000000000" "0034400000000000804640000000000000444000000000000024400000000000004440" "0000000000003e40000000000000344001030000000100000004000000000000000000" "2e40000000000000144000000000000044400000000000002440000000000000244000" "000000000034400000000000002e400000000000001440", ), ( "GEOMETRYCOLLECTION (POINT (40 10))", "010700000001000000010100000000000000000044400000000000002440", ), # 3D ( "POINT (1 2 3)", "0101000080000000000000f03f00000000000000400000000000000840", ), ( "LINESTRING (30 10 3,10 30 3)", "0102000080020000000000000000003e40000000000000244000000000000008400000" "0000000024400000000000003e400000000000000840", ), ( "POLYGON ((30 10 3,40 40 3,30 10 3))", "010300008001000000030000000000000000003e400000000000002440000000000000" "08400000000000004440000000000000444000000000000008400000000000003e4000" "000000000024400000000000000840", ), ( "MULTIPOINT (10 40 3,40 30 3)", "0104000080020000000101000080000000000000244000000000000044400000000000" "000840010100008000000000000044400000000000003e400000000000000840", ), ( "MULTILINESTRING ((10 10 3,20 20 3))", "0105000080010000000102000080020000000000000000002440000000000000244000"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/gdal_tests/test_ds.py
tests/gis_tests/gdal_tests/test_ds.py
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")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/gdal_tests/test_envelope.py
tests/gis_tests/gdal_tests/test_envelope.py
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)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/gdal_tests/__init__.py
tests/gis_tests/gdal_tests/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/gdal_tests/test_raster.py
tests/gis_tests/gdal_tests/test_raster.py
import os import shutil import struct import tempfile import zipfile from pathlib import Path from unittest import mock from django.contrib.gis.gdal import GDAL_VERSION, 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.core.files.temp import NamedTemporaryFile 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_gdalraster_input_as_path(self): rs_path = Path(__file__).parent.parent / "data" / "rasters" / "raster.tif" rs = GDALRaster(rs_path) self.assertEqual(str(rs_path), rs.name) 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 = 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 = 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 = 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. papsz_options = { "compress": "packbits", "blockxsize": 23, "blockysize": 23, } if GDAL_VERSION < (3, 7): datatype = 1 papsz_options["pixeltype"] = "signedbyte" else: datatype = 14 compressed = GDALRaster( { "datatype": datatype, "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": papsz_options, } ) # 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].datatype(), datatype) if GDAL_VERSION < (3, 7): 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 = 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 = 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 = 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 = 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 _remove_aux_file(self): pam_file = self.rs_path + ".aux.xml" if os.path.isfile(pam_file): os.remove(pam_file) def test_read_mode_error(self): # Open raster in read mode rs = GDALRaster(self.rs_path, write=False) band = rs.bands[0] self.addCleanup(self._remove_aux_file) # 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)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/gdal_tests/test_srs.py
tests/gis_tests/gdal_tests/test_srs.py
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) # 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={ None: ("EPSG", "4326"), # Top-level authority. "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={ None: ("EPSG", "32140"), # Top-level authority. "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={ None: (None, None), # Top-level authority. "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("+proj=longlat +datum=WGS84 +no_defs") 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) if GDAL_VERSION < (3, 9): self.assertIn("Langschoß", srs.xml) 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") 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) def test_srid(self): """The srid property returns top-level authority code.""" for s in srlist: if hasattr(s, "epsg"): srs = SpatialReference(s.wkt) self.assertEqual(srs.srid, s.epsg)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/gdal_tests/tests.py
tests/gis_tests/gdal_tests/tests.py
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"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/gdal_tests/test_driver.py
tests/gis_tests/gdal_tests/test_driver.py
import unittest from unittest import mock from django.contrib.gis.gdal import GDAL_VERSION, Driver, GDALException valid_drivers = ( # vector "ESRI Shapefile", "MapInfo File", "S57", "DGN", "Memory", "CSV", "GML", "KML", # raster "GTiff", "JPEG", "MEM", "PNG", ) invalid_drivers = ("Foo baz", "clucka", "ESRI Shp", "ESRI rast") aliases = { "eSrI": "ESRI Shapefile", "SHAPE": "ESRI Shapefile", "sHp": "ESRI Shapefile", "tiFf": "GTiff", "tIf": "GTiff", "jPEg": "JPEG", "jpG": "JPEG", } if GDAL_VERSION[:2] <= (3, 10): aliases.update( { "tiger": "TIGER", "tiger/line": "TIGER", } ) 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.capi.get_driver_count") @mock.patch("django.contrib.gis.gdal.driver.capi.register_all") def test_registered(self, reg, count): """ Prototypes are registered only if the driver count is zero. """ def check(count_val): reg.reset_mock() count.return_value = count_val Driver.ensure_registered() if count_val: self.assertFalse(reg.called) else: reg.assert_called_once_with() check(0) check(120)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/rasterapp/models.py
tests/gis_tests/rasterapp/models.py
from django.contrib.gis.db import models class RasterModel(models.Model): rast = models.RasterField( "A Verbose Raster Name", null=True, srid=4326, spatial_index=True, blank=True ) rastprojected = models.RasterField("A Projected Raster Table", srid=3086, null=True) geom = models.PointField(null=True) class Meta: required_db_features = ["supports_raster"] def __str__(self): return str(self.id) class RasterRelatedModel(models.Model): rastermodel = models.ForeignKey(RasterModel, models.CASCADE) class Meta: required_db_features = ["supports_raster"] def __str__(self): return str(self.id)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/rasterapp/__init__.py
tests/gis_tests/rasterapp/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/rasterapp/test_rasterfield.py
tests/gis_tests/rasterapp/test_rasterfield.py
import json from django.contrib.gis.db.models.fields import BaseSpatialField from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.db.models.lookups import DistanceLookupBase, GISLookup from django.contrib.gis.gdal import GDALRaster from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis.measure import D from django.contrib.gis.shortcuts import numpy from django.db import connection from django.db.models import F, Func, Q from django.test import TransactionTestCase, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from ..data.rasters.textrasters import JSON_RASTER from .models import RasterModel, RasterRelatedModel @skipUnlessDBFeature("supports_raster") class RasterFieldTest(TransactionTestCase): available_apps = ["gis_tests.rasterapp"] def setUp(self): rast = GDALRaster( { "srid": 4326, "origin": [0, 0], "scale": [-1, 1], "skew": [0, 0], "width": 5, "height": 5, "nr_of_bands": 2, "bands": [{"data": range(25)}, {"data": range(25, 50)}], } ) model_instance = RasterModel.objects.create( rast=rast, rastprojected=rast, geom="POINT (-95.37040 29.70486)", ) RasterRelatedModel.objects.create(rastermodel=model_instance) def test_field_null_value(self): """ Test creating a model where the RasterField has a null value. """ r = RasterModel.objects.create(rast=None) r.refresh_from_db() self.assertIsNone(r.rast) def test_access_band_data_directly_from_queryset(self): RasterModel.objects.create(rast=JSON_RASTER) qs = RasterModel.objects.all() qs[0].rast.bands[0].data() def test_deserialize_with_pixeltype_flags(self): no_data = 3 rast = GDALRaster( { "srid": 4326, "origin": [0, 0], "scale": [-1, 1], "skew": [0, 0], "width": 1, "height": 1, "nr_of_bands": 1, "bands": [{"data": [no_data], "nodata_value": no_data}], } ) r = RasterModel.objects.create(rast=rast) RasterModel.objects.filter(pk=r.pk).update( rast=Func(F("rast"), function="ST_SetBandIsNoData"), ) r.refresh_from_db() band = r.rast.bands[0].data() if numpy: band = band.flatten().tolist() self.assertEqual(band, [no_data]) self.assertEqual(r.rast.bands[0].nodata_value, no_data) def test_model_creation(self): """ Test RasterField through a test model. """ # Create model instance from JSON raster r = RasterModel.objects.create(rast=JSON_RASTER) r.refresh_from_db() # Test raster metadata properties self.assertEqual((5, 5), (r.rast.width, r.rast.height)) self.assertEqual([0.0, -1.0, 0.0, 0.0, 0.0, 1.0], r.rast.geotransform) self.assertIsNone(r.rast.bands[0].nodata_value) # Compare srs self.assertEqual(r.rast.srs.srid, 4326) # Compare pixel values band = r.rast.bands[0].data() # If numpy, convert result to list if numpy: band = band.flatten().tolist() # Loop through rows in band data and assert single # value is as expected. self.assertEqual( [ 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, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, ], band, ) def test_implicit_raster_transformation(self): """ Test automatic transformation of rasters with srid different from the field srid. """ # Parse json raster rast = json.loads(JSON_RASTER) # Update srid to another value rast["srid"] = 3086 # Save model and get it from db r = RasterModel.objects.create(rast=rast) r.refresh_from_db() # Confirm raster has been transformed to the default srid self.assertEqual(r.rast.srs.srid, 4326) # Confirm geotransform is in lat/lon expected = [ -87.9298551266551, 9.459646421449934e-06, 0.0, 23.94249275457565, 0.0, -9.459646421449934e-06, ] for val, exp in zip(r.rast.geotransform, expected): self.assertAlmostEqual(exp, val) def test_verbose_name_arg(self): """ RasterField should accept a positional verbose name argument. """ self.assertEqual( RasterModel._meta.get_field("rast").verbose_name, "A Verbose Raster Name" ) def test_all_gis_lookups_with_rasters(self): """ Evaluate all possible lookups for all input combinations (i.e. raster-raster, raster-geom, geom-raster) and for projected and unprojected coordinate systems. This test just checks that the lookup can be called, but doesn't check if the result makes logical sense. """ from django.contrib.gis.db.backends.postgis.operations import PostGISOperations # Create test raster and geom. rast = GDALRaster(json.loads(JSON_RASTER)) stx_pnt = GEOSGeometry("POINT (-95.370401017314293 29.704867409475465)", 4326) stx_pnt.transform(3086) lookups = [ (name, lookup) for name, lookup in BaseSpatialField.get_lookups().items() if issubclass(lookup, GISLookup) ] self.assertNotEqual(lookups, [], "No lookups found") # Loop through all the GIS lookups. for name, lookup in lookups: # Construct lookup filter strings. combo_keys = [ field + name for field in [ "rast__", "rast__", "rastprojected__0__", "rast__", "rastprojected__", "geom__", "rast__", ] ] if issubclass(lookup, DistanceLookupBase): # Set lookup values for distance lookups. combo_values = [ (rast, 50, "spheroid"), (rast, 0, 50, "spheroid"), (rast, 0, D(km=1)), (stx_pnt, 0, 500), (stx_pnt, D(km=1000)), (rast, 500), (json.loads(JSON_RASTER), 500), ] elif name == "relate": # Set lookup values for the relate lookup. combo_values = [ (rast, "T*T***FF*"), (rast, 0, "T*T***FF*"), (rast, 0, "T*T***FF*"), (stx_pnt, 0, "T*T***FF*"), (stx_pnt, "T*T***FF*"), (rast, "T*T***FF*"), (json.loads(JSON_RASTER), "T*T***FF*"), ] elif name == "isvalid": # The isvalid lookup doesn't make sense for rasters. continue elif PostGISOperations.gis_operators[name].func: # Set lookup values for all function based operators. combo_values = [ rast, (rast, 0), (rast, 0), (stx_pnt, 0), stx_pnt, rast, json.loads(JSON_RASTER), ] else: # Override band lookup for these, as it's not supported. combo_keys[2] = "rastprojected__" + name # Set lookup values for all other operators. combo_values = [ rast, None, rast, stx_pnt, stx_pnt, rast, json.loads(JSON_RASTER), ] # Create query filter combinations. self.assertEqual( len(combo_keys), len(combo_values), "Number of lookup names and values should be the same", ) combos = [x for x in zip(combo_keys, combo_values) if x[1]] self.assertEqual( [(n, x) for n, x in enumerate(combos) if x in combos[:n]], [], "There are repeated test lookups", ) combos = [{k: v} for k, v in combos] for combo in combos: # Apply this query filter. qs = RasterModel.objects.filter(**combo) # Evaluate normal filter qs. self.assertIn(qs.count(), [0, 1]) # Evaluate on conditional Q expressions. qs = RasterModel.objects.filter(Q(**combos[0]) & Q(**combos[1])) self.assertIn(qs.count(), [0, 1]) def test_dwithin_gis_lookup_output_with_rasters(self): """ Check the logical functionality of the dwithin lookup for different input parameters. """ # Create test raster and geom. rast = GDALRaster(json.loads(JSON_RASTER)) stx_pnt = GEOSGeometry("POINT (-95.370401017314293 29.704867409475465)", 4326) stx_pnt.transform(3086) # Filter raster with different lookup raster formats. qs = RasterModel.objects.filter(rastprojected__dwithin=(rast, D(km=1))) self.assertEqual(qs.count(), 1) qs = RasterModel.objects.filter( rastprojected__dwithin=(json.loads(JSON_RASTER), D(km=1)) ) self.assertEqual(qs.count(), 1) qs = RasterModel.objects.filter(rastprojected__dwithin=(JSON_RASTER, D(km=1))) self.assertEqual(qs.count(), 1) # Filter in an unprojected coordinate system. qs = RasterModel.objects.filter(rast__dwithin=(rast, 40)) self.assertEqual(qs.count(), 1) # Filter with band index transform. qs = RasterModel.objects.filter(rast__1__dwithin=(rast, 1, 40)) self.assertEqual(qs.count(), 1) qs = RasterModel.objects.filter(rast__1__dwithin=(rast, 40)) self.assertEqual(qs.count(), 1) qs = RasterModel.objects.filter(rast__dwithin=(rast, 1, 40)) self.assertEqual(qs.count(), 1) # Filter raster by geom. qs = RasterModel.objects.filter(rast__dwithin=(stx_pnt, 500)) self.assertEqual(qs.count(), 1) qs = RasterModel.objects.filter(rastprojected__dwithin=(stx_pnt, D(km=10000))) self.assertEqual(qs.count(), 1) qs = RasterModel.objects.filter(rast__dwithin=(stx_pnt, 5)) self.assertEqual(qs.count(), 0) qs = RasterModel.objects.filter(rastprojected__dwithin=(stx_pnt, D(km=100))) self.assertEqual(qs.count(), 0) # Filter geom by raster. qs = RasterModel.objects.filter(geom__dwithin=(rast, 500)) self.assertEqual(qs.count(), 1) # Filter through related model. qs = RasterRelatedModel.objects.filter(rastermodel__rast__dwithin=(rast, 40)) self.assertEqual(qs.count(), 1) # Filter through related model with band index transform qs = RasterRelatedModel.objects.filter(rastermodel__rast__1__dwithin=(rast, 40)) self.assertEqual(qs.count(), 1) # Filter through conditional statements. qs = RasterModel.objects.filter( Q(rast__dwithin=(rast, 40)) & Q(rastprojected__dwithin=(stx_pnt, D(km=10000))) ) self.assertEqual(qs.count(), 1) # Filter through different lookup. qs = RasterModel.objects.filter(rastprojected__bbcontains=rast) self.assertEqual(qs.count(), 1) def test_lookup_input_tuple_too_long(self): rast = GDALRaster(json.loads(JSON_RASTER)) msg = "Tuple too long for lookup bbcontains." with self.assertRaisesMessage(ValueError, msg): RasterModel.objects.filter(rast__bbcontains=(rast, 1, 2)) def test_lookup_input_band_not_allowed(self): rast = GDALRaster(json.loads(JSON_RASTER)) qs = RasterModel.objects.filter(rast__bbcontains=(rast, 1)) msg = "Band indices are not allowed for this operator, it works on bbox only." with self.assertRaisesMessage(ValueError, msg): qs.count() def test_isvalid_lookup_with_raster_error(self): qs = RasterModel.objects.filter(rast__isvalid=True) msg = ( "IsValid function requires a GeometryField in position 1, got RasterField." ) with self.assertRaisesMessage(TypeError, msg): qs.count() def test_result_of_gis_lookup_with_rasters(self): # Point is in the interior qs = RasterModel.objects.filter( rast__contains=GEOSGeometry("POINT (-0.5 0.5)", 4326) ) self.assertEqual(qs.count(), 1) # Point is in the exterior qs = RasterModel.objects.filter( rast__contains=GEOSGeometry("POINT (0.5 0.5)", 4326) ) self.assertEqual(qs.count(), 0) # A point on the boundary is not contained properly qs = RasterModel.objects.filter( rast__contains_properly=GEOSGeometry("POINT (0 0)", 4326) ) self.assertEqual(qs.count(), 0) # Raster is located left of the point qs = RasterModel.objects.filter(rast__left=GEOSGeometry("POINT (1 0)", 4326)) self.assertEqual(qs.count(), 1) def test_lookup_with_raster_bbox(self): rast = GDALRaster(json.loads(JSON_RASTER)) # Shift raster upward rast.origin.y = 2 # The raster in the model is not strictly below qs = RasterModel.objects.filter(rast__strictly_below=rast) self.assertEqual(qs.count(), 0) # Shift raster further upward rast.origin.y = 6 # The raster in the model is strictly below qs = RasterModel.objects.filter(rast__strictly_below=rast) self.assertEqual(qs.count(), 1) def test_lookup_with_polygonized_raster(self): rast = GDALRaster(json.loads(JSON_RASTER)) # Move raster to overlap with the model point on the left side rast.origin.x = -95.37040 + 1 rast.origin.y = 29.70486 # Raster overlaps with point in model qs = RasterModel.objects.filter(geom__intersects=rast) self.assertEqual(qs.count(), 1) # Change left side of raster to be nodata values rast.bands[0].data(data=[0, 0, 0, 1, 1], shape=(5, 1)) rast.bands[0].nodata_value = 0 qs = RasterModel.objects.filter(geom__intersects=rast) # Raster does not overlap anymore after polygonization # where the nodata zone is not included. self.assertEqual(qs.count(), 0) def test_lookup_value_error(self): # Test with invalid dict lookup parameter obj = {} msg = "Couldn't create spatial object from lookup value '%s'." % obj with self.assertRaisesMessage(ValueError, msg): RasterModel.objects.filter(geom__intersects=obj) # Test with invalid string lookup parameter obj = "00000" msg = "Couldn't create spatial object from lookup value '%s'." % obj with self.assertRaisesMessage(ValueError, msg): RasterModel.objects.filter(geom__intersects=obj) def test_db_function_errors(self): """ Errors are raised when using DB functions with raster content. """ point = GEOSGeometry("SRID=3086;POINT (-697024.9213808845 683729.1705516104)") rast = GDALRaster(json.loads(JSON_RASTER)) msg = "Distance function requires a geometric argument in position 2." with self.assertRaisesMessage(TypeError, msg): RasterModel.objects.annotate(distance_from_point=Distance("geom", rast)) with self.assertRaisesMessage(TypeError, msg): RasterModel.objects.annotate( distance_from_point=Distance("rastprojected", rast) ) msg = ( "Distance function requires a GeometryField in position 1, got RasterField." ) with self.assertRaisesMessage(TypeError, msg): RasterModel.objects.annotate( distance_from_point=Distance("rastprojected", point) ).count() def test_lhs_with_index_rhs_without_index(self): with CaptureQueriesContext(connection) as queries: RasterModel.objects.filter( rast__0__contains=json.loads(JSON_RASTER) ).exists() # It's easier to check the indexes in the generated SQL than to write # tests that cover all index combinations. self.assertRegex(queries[-1]["sql"], r"WHERE ST_Contains\([^)]*, 1, [^)]*, 1\)")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/rasterapp/migrations/0002_rastermodels.py
tests/gis_tests/rasterapp/migrations/0002_rastermodels.py
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"], }, ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/rasterapp/migrations/0001_setup_extensions.py
tests/gis_tests/rasterapp/migrations/0001_setup_extensions.py
from django.db import connection, migrations if connection.features.supports_raster: from django.contrib.postgres.operations import CreateExtension class Migration(migrations.Migration): operations = [ CreateExtension("postgis_raster"), ] else: class Migration(migrations.Migration): operations = []
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/rasterapp/migrations/__init__.py
tests/gis_tests/rasterapp/migrations/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/distapp/models.py
tests/gis_tests/distapp/models.py
from django.contrib.gis.db import models from ..utils import gisfield_may_be_null class NamedModel(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True def __str__(self): return self.name class SouthTexasCity(NamedModel): "City model on projected coordinate system for South Texas." point = models.PointField(srid=32140) radius = models.IntegerField(default=10000) class SouthTexasCityFt(NamedModel): "Same City model as above, but U.S. survey feet are the units." point = models.PointField(srid=2278) class AustraliaCity(NamedModel): "City model for Australia, using WGS84." point = models.PointField() radius = models.IntegerField(default=10000) allowed_distance = models.FloatField(default=0.5) ref_point = models.PointField(null=True) class CensusZipcode(NamedModel): "Model for a few South Texas ZIP codes (in original Census NAD83)." poly = models.PolygonField(srid=4269) class SouthTexasZipcode(NamedModel): "Model for a few South Texas ZIP codes." poly = models.PolygonField(srid=32140, null=gisfield_may_be_null) class Interstate(NamedModel): "Geodetic model for U.S. Interstates." path = models.LineStringField() class SouthTexasInterstate(NamedModel): "Projected model for South Texas Interstates." path = models.LineStringField(srid=32140)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/distapp/__init__.py
tests/gis_tests/distapp/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/distapp/tests.py
tests/gis_tests/distapp/tests.py
from django.contrib.gis.db.models.functions import ( Area, Distance, Length, Perimeter, Transform, Union, ) from django.contrib.gis.geos import GEOSGeometry, LineString, Point from django.contrib.gis.measure import D # alias for Distance from django.db import NotSupportedError, connection from django.db.models import ( Case, Count, Exists, F, IntegerField, OuterRef, Q, Value, When, ) from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from ..utils import FuncTestMixin, skipUnlessGISLookup from .models import ( AustraliaCity, CensusZipcode, Interstate, SouthTexasCity, SouthTexasCityFt, SouthTexasInterstate, SouthTexasZipcode, ) class DistanceTest(TestCase): fixtures = ["initial"] def setUp(self): # A point we are testing distances with -- using a WGS84 # coordinate that'll be implicitly transformed to that to # the coordinate system of the field, EPSG:32140 (Texas South Central # w/units in meters) self.stx_pnt = GEOSGeometry( "POINT (-95.370401017314293 29.704867409475465)", 4326 ) # Another one for Australia self.au_pnt = GEOSGeometry("POINT (150.791 -34.4919)", 4326) def get_names(self, qs): cities = [c.name for c in qs] cities.sort() return cities def test_init(self): """ Test initialization of distance models. """ self.assertEqual(9, SouthTexasCity.objects.count()) self.assertEqual(9, SouthTexasCityFt.objects.count()) self.assertEqual(11, AustraliaCity.objects.count()) self.assertEqual(4, SouthTexasZipcode.objects.count()) self.assertEqual(4, CensusZipcode.objects.count()) self.assertEqual(1, Interstate.objects.count()) self.assertEqual(1, SouthTexasInterstate.objects.count()) @skipUnlessGISLookup("dwithin") @skipUnlessDBFeature("has_Transform_function") def test_dwithin(self): """ Test the `dwithin` lookup type. """ # Distances -- all should be equal (except for the # degree/meter pair in au_cities, that's somewhat # approximate). tx_dists = [(7000, 22965.83), D(km=7), D(mi=4.349)] au_dists = [(0.5, 32000), D(km=32), D(mi=19.884)] # Expected cities for Australia and Texas. tx_cities = ["Downtown Houston", "Southside Place"] au_cities = ["Mittagong", "Shellharbour", "Thirroul", "Wollongong"] # Performing distance queries on two projected coordinate systems one # with units in meters and the other in units of U.S. survey feet. for dist in tx_dists: if isinstance(dist, tuple): dist1, dist2 = dist else: dist1 = dist2 = dist qs1 = SouthTexasCity.objects.filter(point__dwithin=(self.stx_pnt, dist1)) qs2 = SouthTexasCityFt.objects.filter(point__dwithin=(self.stx_pnt, dist2)) for qs in qs1, qs2: with self.subTest(dist=dist, qs=qs): self.assertEqual(tx_cities, self.get_names(qs)) # With a complex geometry expression self.assertFalse( SouthTexasCity.objects.exclude(point__dwithin=(Union("point", "point"), 0)) ) # Now performing the `dwithin` queries on a geodetic coordinate system. for dist in au_dists: with self.subTest(dist=dist): type_error = isinstance(dist, D) and not connection.ops.oracle if isinstance(dist, tuple): if connection.ops.oracle or connection.ops.spatialite: # Result in meters dist = dist[1] else: # Result in units of the field dist = dist[0] # Creating the query set. qs = AustraliaCity.objects.order_by("name") if type_error: # A ValueError should be raised on PostGIS when trying to # pass Distance objects into a DWithin query using a # geodetic field. with self.assertRaises(ValueError): AustraliaCity.objects.filter( point__dwithin=(self.au_pnt, dist) ).count() else: self.assertEqual( au_cities, self.get_names(qs.filter(point__dwithin=(self.au_pnt, dist))), ) @skipUnlessDBFeature("supports_distances_lookups") def test_distance_lookups(self): # Retrieving the cities within a 20km 'donut' w/a 7km radius 'hole' # (thus, Houston and Southside place will be excluded as tested in # the `test02_dwithin` above). for model in [SouthTexasCity, SouthTexasCityFt]: stx_pnt = self.stx_pnt.transform( model._meta.get_field("point").srid, clone=True ) qs = model.objects.filter(point__distance_gte=(stx_pnt, D(km=7))).filter( point__distance_lte=(stx_pnt, D(km=20)), ) cities = self.get_names(qs) self.assertEqual(cities, ["Bellaire", "Pearland", "West University Place"]) # Doing a distance query using Polygons instead of a Point. z = SouthTexasZipcode.objects.get(name="77005") qs = SouthTexasZipcode.objects.exclude(name="77005").filter( poly__distance_lte=(z.poly, D(m=275)) ) self.assertEqual(["77025", "77401"], self.get_names(qs)) # If we add a little more distance 77002 should be included. qs = SouthTexasZipcode.objects.exclude(name="77005").filter( poly__distance_lte=(z.poly, D(m=300)) ) self.assertEqual(["77002", "77025", "77401"], self.get_names(qs)) @skipUnlessDBFeature("supports_distances_lookups", "supports_distance_geodetic") def test_geodetic_distance_lookups(self): """ Test distance lookups on geodetic coordinate systems. """ # Line is from Canberra to Sydney. Query is for all other cities within # a 100km of that line (which should exclude only Hobart & # Adelaide). line = GEOSGeometry("LINESTRING(144.9630 -37.8143,151.2607 -33.8870)", 4326) dist_qs = AustraliaCity.objects.filter(point__distance_lte=(line, D(km=100))) expected_cities = [ "Batemans Bay", "Canberra", "Hillsdale", "Melbourne", "Mittagong", "Shellharbour", "Sydney", "Thirroul", "Wollongong", ] if connection.ops.spatialite: # SpatiaLite is less accurate and returns 102.8km for Batemans Bay. expected_cities.pop(0) self.assertEqual(expected_cities, self.get_names(dist_qs)) msg = "2, 3, or 4-element tuple required for 'distance_lte' lookup." with self.assertRaisesMessage(ValueError, msg): # Too many params. len( AustraliaCity.objects.filter( point__distance_lte=( "POINT(5 23)", D(km=100), "spheroid", "4", None, ) ) ) with self.assertRaisesMessage(ValueError, msg): # Too few params. len(AustraliaCity.objects.filter(point__distance_lte=("POINT(5 23)",))) msg = "For 4-element tuples the last argument must be the 'spheroid' directive." with self.assertRaisesMessage(ValueError, msg): len( AustraliaCity.objects.filter( point__distance_lte=("POINT(5 23)", D(km=100), "spheroid", "4") ) ) # Getting all cities w/in 550 miles of Hobart. hobart = AustraliaCity.objects.get(name="Hobart") qs = AustraliaCity.objects.exclude(name="Hobart").filter( point__distance_lte=(hobart.point, D(mi=550)) ) cities = self.get_names(qs) self.assertEqual(cities, ["Batemans Bay", "Canberra", "Melbourne"]) # Cities that are either really close or really far from Wollongong -- # and using different units of distance. wollongong = AustraliaCity.objects.get(name="Wollongong") d1, d2 = D(yd=19500), D(nm=400) # Yards (~17km) & Nautical miles. # Normal geodetic distance lookup (uses `distance_sphere` on PostGIS. gq1 = Q(point__distance_lte=(wollongong.point, d1)) gq2 = Q(point__distance_gte=(wollongong.point, d2)) qs1 = AustraliaCity.objects.exclude(name="Wollongong").filter(gq1 | gq2) # Geodetic distance lookup but telling GeoDjango to use # `distance_spheroid` instead (we should get the same results b/c # accuracy variance won't matter in this test case). querysets = [qs1] if connection.features.has_DistanceSpheroid_function: gq3 = Q(point__distance_lte=(wollongong.point, d1, "spheroid")) gq4 = Q(point__distance_gte=(wollongong.point, d2, "spheroid")) qs2 = AustraliaCity.objects.exclude(name="Wollongong").filter(gq3 | gq4) querysets.append(qs2) for qs in querysets: cities = self.get_names(qs) self.assertEqual(cities, ["Adelaide", "Hobart", "Shellharbour", "Thirroul"]) @skipUnlessDBFeature("supports_distances_lookups") def test_distance_lookups_with_expression_rhs(self): stx_pnt = self.stx_pnt.transform( SouthTexasCity._meta.get_field("point").srid, clone=True ) qs = SouthTexasCity.objects.filter( point__distance_lte=(stx_pnt, F("radius")), ).order_by("name") self.assertEqual( self.get_names(qs), [ "Bellaire", "Downtown Houston", "Southside Place", "West University Place", ], ) # With a combined expression qs = SouthTexasCity.objects.filter( point__distance_lte=(stx_pnt, F("radius") * 2), ).order_by("name") self.assertEqual(len(qs), 5) self.assertIn("Pearland", self.get_names(qs)) # With spheroid param if connection.features.supports_distance_geodetic: hobart = AustraliaCity.objects.get(name="Hobart") AustraliaCity.objects.update(ref_point=hobart.point) for ref_point in [hobart.point, F("ref_point")]: qs = AustraliaCity.objects.filter( point__distance_lte=(ref_point, F("radius") * 70, "spheroid"), ).order_by("name") self.assertEqual( self.get_names(qs), ["Canberra", "Hobart", "Melbourne"] ) # With a complex geometry expression self.assertFalse( SouthTexasCity.objects.filter( point__distance_gt=(Union("point", "point"), 0) ) ) self.assertEqual( SouthTexasCity.objects.filter( point__distance_lte=(Union("point", "point"), 0) ).count(), SouthTexasCity.objects.count(), ) @skipUnlessDBFeature("supports_distances_lookups") def test_distance_annotation_group_by(self): stx_pnt = self.stx_pnt.transform( SouthTexasCity._meta.get_field("point").srid, clone=True, ) qs = ( SouthTexasCity.objects.annotate( relative_distance=Case( When(point__distance_lte=(stx_pnt, D(km=20)), then=Value(20)), default=Value(100), output_field=IntegerField(), ), ) .values("relative_distance") .annotate(count=Count("pk")) ) self.assertCountEqual( qs, [ {"relative_distance": 20, "count": 5}, {"relative_distance": 100, "count": 4}, ], ) def test_mysql_geodetic_distance_error(self): if not connection.ops.mysql: self.skipTest("This is a MySQL-specific test.") msg = ( "Only numeric values of degree units are allowed on geodetic distance " "queries." ) with self.assertRaisesMessage(ValueError, msg): AustraliaCity.objects.filter( point__distance_lte=(Point(0, 0), D(m=100)) ).exists() @skipUnlessGISLookup("dwithin") @skipUnlessDBFeature("has_Transform_function") def test_dwithin_subquery(self): """dwithin lookup in a subquery using OuterRef as a parameter.""" qs = CensusZipcode.objects.annotate( annotated_value=Exists( SouthTexasCity.objects.filter( point__dwithin=(OuterRef("poly"), D(m=10)), ) ) ).filter(annotated_value=True) self.assertEqual(self.get_names(qs), ["77002", "77025", "77401"]) @skipUnlessGISLookup("dwithin") @skipUnlessDBFeature("supports_dwithin_distance_expr") def test_dwithin_with_expression_rhs(self): # LineString of Wollongong and Adelaide coords. ls = LineString(((150.902, -34.4245), (138.6, -34.9258)), srid=4326) qs = AustraliaCity.objects.filter( point__dwithin=(ls, F("allowed_distance")), ).order_by("name") self.assertEqual( self.get_names(qs), ["Adelaide", "Mittagong", "Shellharbour", "Thirroul", "Wollongong"], ) @skipIfDBFeature("supports_dwithin_distance_expr") def test_dwithin_with_expression_rhs_not_supported(self): ls = LineString(((150.902, -34.4245), (138.6, -34.9258)), srid=4326) msg = ( "This backend does not support expressions for specifying " "distance in the dwithin lookup." ) with self.assertRaisesMessage(NotSupportedError, msg): list( AustraliaCity.objects.filter( point__dwithin=(ls, F("allowed_distance")), ) ) """ ============================= Distance functions on PostGIS ============================= | Projected Geometry | Lon/lat Geometry | Geography (4326) ST_Distance(geom1, geom2) | OK (meters) | :-( (degrees) | OK (meters) ST_Distance(geom1, geom2, use_spheroid=False) | N/A | N/A | OK (meters), less accurate, quick Distance_Sphere(geom1, geom2) | N/A | OK (meters) | N/A Distance_Spheroid(geom1, geom2, spheroid) | N/A | OK (meters) | N/A ST_Perimeter(geom1) | OK | :-( (degrees) | OK ================================ Distance functions on SpatiaLite ================================ | Projected Geometry | Lon/lat Geometry ST_Distance(geom1, geom2) | OK (meters) | N/A ST_Distance(geom1, geom2, use_ellipsoid=True) | N/A | OK (meters) ST_Distance(geom1, geom2, use_ellipsoid=False) | N/A | OK (meters), less accurate, quick Perimeter(geom1) | OK | :-( (degrees) """ # NOQA class DistanceFunctionsTests(FuncTestMixin, TestCase): fixtures = ["initial"] @skipUnlessDBFeature("has_Area_function") def test_area(self): # Reference queries: # SELECT ST_Area(poly) FROM distapp_southtexaszipcode; area_sq_m = [ 5437908.90234375, 10183031.4389648, 11254471.0073242, 9881708.91772461, ] # Tolerance has to be lower for Oracle tol = 2 for i, z in enumerate( SouthTexasZipcode.objects.annotate(area=Area("poly")).order_by("name") ): self.assertAlmostEqual(area_sq_m[i], z.area.sq_m, tol) @skipUnlessDBFeature("has_Distance_function") def test_distance_simple(self): """ Test a simple distance query, with projected coordinates and without transformation. """ lagrange = GEOSGeometry("POINT(805066.295722839 4231496.29461335)", 32140) houston = ( SouthTexasCity.objects.annotate(dist=Distance("point", lagrange)) .order_by("id") .first() ) tol = 2 if connection.ops.oracle else 5 self.assertAlmostEqual(houston.dist.m, 147075.069813, tol) @skipUnlessDBFeature("has_Distance_function", "has_Transform_function") def test_distance_projected(self): """ Test the `Distance` function on projected coordinate systems. """ # The point for La Grange, TX lagrange = GEOSGeometry("POINT(-96.876369 29.905320)", 4326) # Reference distances in feet and in meters. Got these values from # using the provided raw SQL statements. # SELECT ST_Distance( # point, # ST_Transform( # ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), # 32140 # ) # ) # FROM distapp_southtexascity; m_distances = [ 147075.069813, 139630.198056, 140888.552826, 138809.684197, 158309.246259, 212183.594374, 70870.188967, 165337.758878, 139196.085105, ] # SELECT ST_Distance( # point, # ST_Transform( # ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), # 2278 # ) # ) # FROM distapp_southtexascityft; ft_distances = [ 482528.79154625, 458103.408123001, 462231.860397575, 455411.438904354, 519386.252102563, 696139.009211594, 232513.278304279, 542445.630586414, 456679.155883207, ] # Testing using different variations of parameters and using models # with different projected coordinate systems. dist1 = SouthTexasCity.objects.annotate( distance=Distance("point", lagrange) ).order_by("id") dist2 = SouthTexasCityFt.objects.annotate( distance=Distance("point", lagrange) ).order_by("id") dist_qs = [dist1, dist2] # Ensuring expected distances are returned for each distance queryset. for qs in dist_qs: for i, c in enumerate(qs): with self.subTest(c=c): self.assertAlmostEqual(m_distances[i], c.distance.m, -1) self.assertAlmostEqual(ft_distances[i], c.distance.survey_ft, -1) @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic") def test_distance_geodetic(self): """ Test the `Distance` function on geodetic coordinate systems. """ # Testing geodetic distance calculation with a non-point geometry # (a LineString of Wollongong and Shellharbour coords). ls = LineString(((150.902, -34.4245), (150.87, -34.5789)), srid=4326) # Reference query: # SELECT ST_distance_sphere( # point, # ST_GeomFromText( # 'LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', # 4326 # ) # ) # FROM distapp_australiacity ORDER BY name; distances = [ 1120954.92533513, 140575.720018241, 640396.662906304, 60580.9693849269, 972807.955955075, 568451.8357838, 40435.4335201384, 0, 68272.3896586844, 12375.0643697706, 0, ] qs = AustraliaCity.objects.annotate(distance=Distance("point", ls)).order_by( "name" ) for city, distance in zip(qs, distances): with self.subTest(city=city, distance=distance): # Testing equivalence to within a meter (kilometer on # SpatiaLite). tol = -3 if connection.ops.spatialite else 0 self.assertAlmostEqual(distance, city.distance.m, tol) @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic") def test_distance_geodetic_spheroid(self): tol = 2 if connection.ops.oracle else 4 # Got the reference distances using the raw SQL statements: # SELECT ST_distance_spheroid( # point, # ST_GeomFromText('POINT(151.231341 -33.952685)', 4326), # 'SPHEROID["WGS 84",6378137.0,298.257223563]' # ) # FROM distapp_australiacity WHERE (NOT (id = 11)); # SELECT ST_distance_sphere( # point, # ST_GeomFromText('POINT(151.231341 -33.952685)', 4326) # ) # FROM distapp_australiacity # WHERE (NOT (id = 11)); st_distance_sphere spheroid_distances = [ 60504.0628957201, 77023.9489850262, 49154.8867574404, 90847.4358768573, 217402.811919332, 709599.234564757, 640011.483550888, 7772.00667991925, 1047861.78619339, 1165126.55236034, ] sphere_distances = [ 60580.9693849267, 77144.0435286473, 49199.4415344719, 90804.7533823494, 217713.384600405, 709134.127242793, 639828.157159169, 7786.82949717788, 1049204.06569028, 1162623.7238134, ] # Testing with spheroid distances first. hillsdale = AustraliaCity.objects.get(name="Hillsdale") qs = ( AustraliaCity.objects.exclude(id=hillsdale.id) .annotate(distance=Distance("point", hillsdale.point, spheroid=True)) .order_by("id") ) for i, c in enumerate(qs): with self.subTest(c=c): self.assertAlmostEqual(spheroid_distances[i], c.distance.m, tol) if connection.ops.postgis or connection.ops.spatialite: # PostGIS uses sphere-only distances by default, testing these as # well. qs = ( AustraliaCity.objects.exclude(id=hillsdale.id) .annotate(distance=Distance("point", hillsdale.point)) .order_by("id") ) for i, c in enumerate(qs): with self.subTest(c=c): self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol) @skipIfDBFeature("supports_distance_geodetic") @skipUnlessDBFeature("has_Distance_function") def test_distance_function_raw_result(self): distance = ( Interstate.objects.annotate( d=Distance(Point(0, 0, srid=4326), Point(0, 1, srid=4326)), ) .first() .d ) self.assertEqual(distance, 1) @skipUnlessDBFeature("has_Distance_function") def test_distance_function_d_lookup(self): qs = Interstate.objects.annotate( d=Distance(Point(0, 0, srid=3857), Point(0, 1, srid=3857)), ).filter(d=D(m=1)) self.assertTrue(qs.exists()) @skipUnlessDBFeature("supports_tolerance_parameter") def test_distance_function_tolerance_escaping(self): qs = ( Interstate.objects.annotate( d=Distance( Point(500, 500, srid=3857), Point(0, 0, srid=3857), tolerance="0.05) = 1 OR 1=1 OR (1+1", ), ) .filter(d=D(m=1)) .values("pk") ) msg = "The tolerance parameter has the wrong type" with self.assertRaisesMessage(TypeError, msg): qs.exists() @skipUnlessDBFeature("supports_tolerance_parameter") def test_distance_function_tolerance(self): # Tolerance is greater than distance. qs = ( Interstate.objects.annotate( d=Distance( Point(0, 0, srid=3857), Point(1, 1, srid=3857), tolerance=1.5, ), ) .filter(d=0) .values("pk") ) self.assertIs(qs.exists(), True) @skipIfDBFeature("supports_distance_geodetic") @skipUnlessDBFeature("has_Distance_function") def test_distance_function_raw_result_d_lookup(self): qs = Interstate.objects.annotate( d=Distance(Point(0, 0, srid=4326), Point(0, 1, srid=4326)), ).filter(d=D(m=1)) msg = "Distance measure is supplied, but units are unknown for result." with self.assertRaisesMessage(ValueError, msg): list(qs) @skipUnlessDBFeature("has_Distance_function", "has_Transform_function") def test_distance_transform(self): """ Test the `Distance` function used with `Transform` on a geographic field. """ # We'll be using a Polygon (created by buffering the centroid # of 77005 to 100m) -- which aren't allowed in geographic distance # queries normally, however our field has been transformed to # a non-geographic system. z = SouthTexasZipcode.objects.get(name="77005") # Reference query: # SELECT ST_Distance( # ST_Transform("distapp_censuszipcode"."poly", 32140), # ST_GeomFromText('<buffer_wkt>', 32140)) # FROM "distapp_censuszipcode"; dists_m = [3553.30384972258, 1243.18391525602, 2186.15439472242] # Having our buffer in the SRID of the transformation and of the field # -- should get the same results. The first buffer has no need for # transformation SQL because it is the same SRID as what was given # to `transform()`. The second buffer will need to be transformed, # however. buf1 = z.poly.centroid.buffer(100) buf2 = buf1.transform(4269, clone=True) ref_zips = ["77002", "77025", "77401"] for buf in [buf1, buf2]: qs = ( CensusZipcode.objects.exclude(name="77005") .annotate(distance=Distance(Transform("poly", 32140), buf)) .order_by("name") ) self.assertEqual(ref_zips, sorted(c.name for c in qs)) for i, z in enumerate(qs): self.assertAlmostEqual(z.distance.m, dists_m[i], 5) @skipUnlessDBFeature("has_Distance_function") def test_distance_order_by(self): qs = ( SouthTexasCity.objects.annotate( distance=Distance("point", Point(3, 3, srid=32140)) ) .order_by("distance") .values_list("name", flat=True) .filter(name__in=("San Antonio", "Pearland")) ) self.assertSequenceEqual(qs, ["San Antonio", "Pearland"]) @skipUnlessDBFeature("has_Length_function") def test_length(self): """ Test the `Length` function. """ # Reference query (should use `length_spheroid`). # SELECT ST_length_spheroid( # ST_GeomFromText('<wkt>', 4326) # 'SPHEROID["WGS 84",6378137,298.257223563, # AUTHORITY["EPSG","7030"]]' # ); len_m1 = 473504.769553813 len_m2 = 4617.668 if connection.features.supports_length_geodetic: qs = Interstate.objects.annotate(length=Length("path")) tol = 2 if connection.ops.oracle else 3 self.assertAlmostEqual(len_m1, qs[0].length.m, tol) # TODO: test with spheroid argument (True and False) else: # Does not support geodetic coordinate systems. with self.assertRaises(NotSupportedError): list(Interstate.objects.annotate(length=Length("path"))) # Now doing length on a projected coordinate system. i10 = SouthTexasInterstate.objects.annotate(length=Length("path")).get( name="I-10" ) self.assertAlmostEqual(len_m2, i10.length.m, 2) self.assertTrue( SouthTexasInterstate.objects.annotate(length=Length("path")) .filter(length__gt=4000) .exists() ) # Length with an explicit geometry value. qs = Interstate.objects.annotate(length=Length(i10.path)) self.assertAlmostEqual(qs.first().length.m, len_m2, 2) @skipUnlessDBFeature("has_Perimeter_function") def test_perimeter(self): """ Test the `Perimeter` function. """ # Reference query: # SELECT ST_Perimeter(distapp_southtexaszipcode.poly) # FROM distapp_southtexaszipcode; perim_m = [ 18404.3550889361, 15627.2108551001, 20632.5588368978, 17094.5996143697, ] tol = 2 if connection.ops.oracle else 7 qs = SouthTexasZipcode.objects.annotate(perimeter=Perimeter("poly")).order_by( "name" ) for i, z in enumerate(qs): self.assertAlmostEqual(perim_m[i], z.perimeter.m, tol) # Running on points; should return 0. qs = SouthTexasCity.objects.annotate(perim=Perimeter("point")) for city in qs: self.assertEqual(0, city.perim.m) @skipUnlessDBFeature("has_Perimeter_function") def test_perimeter_geodetic(self): # Currently only Oracle supports calculating the perimeter on geodetic # geometries (without being transformed). qs1 = CensusZipcode.objects.annotate(perim=Perimeter("poly")) if connection.features.supports_perimeter_geodetic: self.assertAlmostEqual(qs1[0].perim.m, 18406.3818954314, 3) else: with self.assertRaises(NotSupportedError): list(qs1) # But should work fine when transformed to projected coordinates qs2 = CensusZipcode.objects.annotate( perim=Perimeter(Transform("poly", 32140)) ).filter(name="77002") self.assertAlmostEqual(qs2[0].perim.m, 18404.355, 3) @skipUnlessDBFeature( "supports_null_geometries", "has_Area_function", "has_Distance_function" ) def test_measurement_null_fields(self): """ Test the measurement functions on fields with NULL values. """ # Creating SouthTexasZipcode w/NULL value. SouthTexasZipcode.objects.create(name="78212") # Performing distance/area queries against the NULL PolygonField, # and ensuring the result of the operations is None. htown = SouthTexasCity.objects.get(name="Downtown Houston") z = SouthTexasZipcode.objects.annotate( distance=Distance("poly", htown.point), area=Area("poly") ).get(name="78212") self.assertIsNone(z.distance) self.assertIsNone(z.area)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/inspectapp/models.py
tests/gis_tests/inspectapp/models.py
from django.contrib.gis.db import models class AllOGRFields(models.Model): f_decimal = models.FloatField() f_float = models.FloatField() f_int = models.IntegerField() f_char = models.CharField(max_length=10) f_date = models.DateField() f_datetime = models.DateTimeField() f_time = models.TimeField() geom = models.PolygonField() point = models.PointField() class Fields3D(models.Model): point = models.PointField(dim=3) pointg = models.PointField(dim=3, geography=True) line = models.LineStringField(dim=3) poly = models.PolygonField(dim=3) class Meta: required_db_features = {"supports_3d_storage"}
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/inspectapp/__init__.py
tests/gis_tests/inspectapp/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/inspectapp/tests.py
tests/gis_tests/inspectapp/tests.py
import os import re from io import StringIO from django.contrib.gis.gdal import GDAL_VERSION, Driver, GDALException from django.contrib.gis.utils.ogrinspect import ogrinspect from django.core.management import call_command from django.db import connection, connections from django.db.backends.sqlite3.creation import DatabaseCreation from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import modify_settings from ..test_data import TEST_DATA from .models import AllOGRFields class InspectDbTests(TestCase): def test_geom_columns(self): """ Test the geo-enabled inspectdb command. """ out = StringIO() call_command( "inspectdb", table_name_filter=lambda tn: tn == "inspectapp_allogrfields", stdout=out, ) output = out.getvalue() if connection.features.supports_geometry_field_introspection: self.assertIn("geom = models.PolygonField()", output) self.assertIn("point = models.PointField()", output) else: self.assertIn("geom = models.GeometryField(", output) self.assertIn("point = models.GeometryField(", output) @skipUnlessDBFeature("supports_3d_storage") def test_3d_columns(self): out = StringIO() call_command( "inspectdb", table_name_filter=lambda tn: tn == "inspectapp_fields3d", stdout=out, ) output = out.getvalue() if connection.features.supports_geometry_field_introspection: self.assertIn("point = models.PointField(dim=3)", output) if connection.features.supports_geography: self.assertIn( "pointg = models.PointField(geography=True, dim=3)", output ) else: self.assertIn("pointg = models.PointField(dim=3)", output) self.assertIn("line = models.LineStringField(dim=3)", output) self.assertIn("poly = models.PolygonField(dim=3)", output) else: self.assertIn("point = models.GeometryField(", output) self.assertIn("pointg = models.GeometryField(", output) self.assertIn("line = models.GeometryField(", output) self.assertIn("poly = models.GeometryField(", output) @modify_settings( INSTALLED_APPS={"append": "django.contrib.gis"}, ) class OGRInspectTest(SimpleTestCase): maxDiff = 1024 def test_poly(self): shp_file = os.path.join(TEST_DATA, "test_poly", "test_poly.shp") model_def = ogrinspect(shp_file, "MyModel") expected = [ "# This is an auto-generated Django model module created by ogrinspect.", "from django.contrib.gis.db import models", "", "", "class MyModel(models.Model):", " float = models.FloatField()", " int = models.BigIntegerField()", " str = models.CharField(max_length=80)", " geom = models.PolygonField()", ] self.assertEqual(model_def, "\n".join(expected)) def test_poly_multi(self): shp_file = os.path.join(TEST_DATA, "test_poly", "test_poly.shp") model_def = ogrinspect(shp_file, "MyModel", multi_geom=True) self.assertIn("geom = models.MultiPolygonField()", model_def) # Same test with a 25D-type geometry field shp_file = os.path.join(TEST_DATA, "gas_lines", "gas_leitung.shp") model_def = ogrinspect(shp_file, "MyModel", multi_geom=True) self.assertIn("geom = models.MultiLineStringField(srid=31253)", model_def) def test_date_field(self): shp_file = os.path.join(TEST_DATA, "cities", "cities.shp") model_def = ogrinspect(shp_file, "City") expected = [ "# This is an auto-generated Django model module created by ogrinspect.", "from django.contrib.gis.db import models", "", "", "class City(models.Model):", " name = models.CharField(max_length=80)", " population = models.BigIntegerField()", " density = models.FloatField()", " created = models.DateField()", " geom = models.PointField()", ] self.assertEqual(model_def, "\n".join(expected)) def test_time_field(self): # Getting the database identifier used by OGR, if None returned # GDAL does not have the support compiled in. ogr_db = get_ogr_db_string() if not ogr_db: self.skipTest("Unable to setup an OGR connection to your database") try: # Writing shapefiles via GDAL currently does not support writing # OGRTime fields, so we need to actually use a database model_def = ogrinspect( ogr_db, "Measurement", layer_key=AllOGRFields._meta.db_table, decimal=["f_decimal"], ) except GDALException: self.skipTest("Unable to setup an OGR connection to your database") self.assertTrue( model_def.startswith( "# This is an auto-generated Django model module created by " "ogrinspect.\n" "from django.contrib.gis.db import models\n" "\n" "\n" "class Measurement(models.Model):\n" ) ) # The ordering of model fields might vary depending on several factors # (version of GDAL, etc.). if connection.vendor == "sqlite" and GDAL_VERSION < (3, 4): # SpatiaLite introspection is somewhat lacking on GDAL < 3.4 # (#29461). self.assertIn(" f_decimal = models.CharField(max_length=0)", model_def) else: self.assertIn( " f_decimal = models.DecimalField(max_digits=0, decimal_places=0)", model_def, ) self.assertIn(" f_int = models.IntegerField()", model_def) if not connection.ops.mariadb: # Probably a bug between GDAL and MariaDB on time fields. self.assertIn(" f_datetime = models.DateTimeField()", model_def) self.assertIn(" f_time = models.TimeField()", model_def) if connection.vendor == "sqlite" and GDAL_VERSION < (3, 4): self.assertIn(" f_float = models.CharField(max_length=0)", model_def) else: self.assertIn(" f_float = models.FloatField()", model_def) max_length = 0 if connection.vendor == "sqlite" else 10 self.assertIn( " f_char = models.CharField(max_length=%s)" % max_length, model_def ) self.assertIn(" f_date = models.DateField()", model_def) # Some backends may have srid=-1 self.assertIsNotNone( re.search(r" geom = models.PolygonField\(([^\)])*\)", model_def) ) def test_management_command(self): shp_file = os.path.join(TEST_DATA, "cities", "cities.shp") out = StringIO() call_command("ogrinspect", shp_file, "City", stdout=out) output = out.getvalue() self.assertIn("class City(models.Model):", output) def test_mapping_option(self): expected = ( " geom = models.PointField()\n" "\n" "\n" "# Auto-generated `LayerMapping` dictionary for City model\n" "city_mapping = {\n" " 'name': 'Name',\n" " 'population': 'Population',\n" " 'density': 'Density',\n" " 'created': 'Created',\n" " 'geom': 'POINT',\n" "}\n" ) shp_file = os.path.join(TEST_DATA, "cities", "cities.shp") out = StringIO() call_command("ogrinspect", shp_file, "--mapping", "City", stdout=out) self.assertIn(expected, out.getvalue()) def get_ogr_db_string(): """ Construct the DB string that GDAL will use to inspect the database. GDAL will create its own connection to the database, so we re-use the connection settings from the Django test. """ db = connections.settings["default"] # Map from the django backend into the OGR driver name and database # identifier https://gdal.org/drivers/vector/ # # TODO: Support Oracle (OCI). drivers = { "django.contrib.gis.db.backends.postgis": ( "PostgreSQL", "PG:dbname='%(db_name)s'", " ", ), "django.contrib.gis.db.backends.mysql": ("MySQL", 'MYSQL:"%(db_name)s"', ","), "django.contrib.gis.db.backends.spatialite": ("SQLite", "%(db_name)s", ""), } db_engine = db["ENGINE"] if db_engine not in drivers: return None drv_name, db_str, param_sep = drivers[db_engine] # Ensure that GDAL library has driver support for the database. try: Driver(drv_name) except GDALException: return None # SQLite/SpatiaLite in-memory databases if DatabaseCreation.is_in_memory_db(db["NAME"]): return None # Build the params of the OGR database connection string params = [db_str % {"db_name": db["NAME"]}] def add(key, template): value = db.get(key, None) # Don't add the parameter if it is not in django's settings if value: params.append(template % value) add("HOST", "host='%s'") add("PORT", "port='%s'") add("USER", "user='%s'") add("PASSWORD", "password='%s'") return param_sep.join(params)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/relatedapp/models.py
tests/gis_tests/relatedapp/models.py
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()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/relatedapp/__init__.py
tests/gis_tests/relatedapp/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/relatedapp/tests.py
tests/gis_tests/relatedapp/tests.py
from django.contrib.gis.db.models import Collect, Count, Extent, F, MakeLine, Q, Union from django.contrib.gis.db.models.functions import Centroid 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 ..utils import skipUnlessGISLookup 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). tests = [ (u1, ref_u1), (u2, ref_u2), (u3, ref_u1), ] for union, ref in tests: for point, ref_point in zip(sorted(union), sorted(ref), strict=True): self.assertIs(point.equals_exact(ref_point, tolerance=6), True) 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()) @skipUnlessGISLookup("within") 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().order_by("pk") def_qs = Location.objects.defer("point").order_by("pk") 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) @skipUnlessGISLookup("within") 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)) @skipUnlessDBFeature("supports_collect_aggr") def test_collect_filter(self): qs = City.objects.annotate( parcel_center=Collect( "parcel__center1", filter=~Q(parcel__name__icontains="ignore"), ), parcel_center_nonexistent=Collect( "parcel__center1", filter=Q(parcel__name__icontains="nonexistent"), ), parcel_center_single=Collect( "parcel__center1", filter=Q(parcel__name__contains="Alpha"), ), ) city = qs.get(name="Aurora") self.assertEqual( city.parcel_center.wkt, GEOSGeometry("MULTIPOINT (1.7128 -2.006, 4.7128 5.006)"), ) self.assertIsNone(city.parcel_center_nonexistent) self.assertIn( city.parcel_center_single.wkt, [ GEOSGeometry("MULTIPOINT (1.7128 -2.006)"), GEOSGeometry("POINT (1.7128 -2.006)"), # SpatiaLite collapse to POINT. ], ) @skipUnlessDBFeature("has_Centroid_function", "supports_collect_aggr") def test_centroid_collect_filter(self): qs = City.objects.annotate( parcel_centroid=Centroid( Collect( "parcel__center1", filter=~Q(parcel__name__icontains="ignore"), ) ) ) city = qs.get(name="Aurora") if connection.ops.mariadb: self.assertIsNone(city.parcel_centroid) else: self.assertIsInstance(city.parcel_centroid, Point) self.assertAlmostEqual(city.parcel_centroid[0], 3.2128, 4) self.assertAlmostEqual(city.parcel_centroid[1], 1.5, 4) @skipUnlessDBFeature("supports_make_line_aggr") def test_make_line_filter(self): qs = City.objects.annotate( parcel_line=MakeLine( "parcel__center1", filter=~Q(parcel__name__icontains="ignore"), ), parcel_line_nonexistent=MakeLine( "parcel__center1", filter=Q(parcel__name__icontains="nonexistent"), ), ) city = qs.get(name="Aurora") self.assertIn( city.parcel_line.wkt, # The default ordering is flaky, so check both. [ "LINESTRING (1.7128 -2.006, 4.7128 5.006)", "LINESTRING (4.7128 5.006, 1.7128 -2.006)", ], ) self.assertIsNone(city.parcel_line_nonexistent) @skipUnlessDBFeature("supports_extent_aggr") def test_extent_filter(self): qs = City.objects.annotate( parcel_border=Extent( "parcel__border1", filter=~Q(parcel__name__icontains="ignore"), ), parcel_border_nonexistent=Extent( "parcel__border1", filter=Q(parcel__name__icontains="nonexistent"), ), parcel_border_no_filter=Extent("parcel__border1"), ) city = qs.get(name="Aurora") self.assertEqual(city.parcel_border, (0.0, 0.0, 22.0, 22.0)) self.assertIsNone(city.parcel_border_nonexistent) self.assertEqual(city.parcel_border_no_filter, (0.0, 0.0, 32.0, 32.0)) @skipUnlessDBFeature("supports_union_aggr") def test_union_filter(self): qs = City.objects.annotate( parcel_point_union=Union( "parcel__center2", filter=~Q(parcel__name__icontains="ignore"), ), parcel_point_nonexistent=Union( "parcel__center2", filter=Q(parcel__name__icontains="nonexistent"), ), parcel_point_union_single=Union( "parcel__center2", filter=Q(parcel__name__contains="Alpha"), ), ) city = qs.get(name="Aurora") self.assertIn( city.parcel_point_union.wkt, [ GEOSGeometry("MULTIPOINT (12.75 10.05, 3.7128 -5.006)"), GEOSGeometry("MULTIPOINT (3.7128 -5.006, 12.75 10.05)"), ], ) self.assertIsNone(city.parcel_point_nonexistent) self.assertEqual(city.parcel_point_union_single.wkt, "POINT (3.7128 -5.006)") 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.
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geoapp/test_regress.py
tests/gis_tests/geoapp/test_regress.py
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 ..utils import skipUnlessGISLookup 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"] ) @skipUnlessGISLookup("contains") 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)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/gis_tests/geoapp/test_expressions.py
tests/gis_tests/geoapp/test_expressions.py
from django.contrib.gis.db.models import F, GeometryField, Value, functions from django.contrib.gis.geos import Point, Polygon from django.db import connection from django.db.models import Count, Min from django.test import TestCase, skipUnlessDBFeature from .models import City, ManyPointModel, MultiFields class GeoExpressionsTests(TestCase): fixtures = ["initial"] def test_geometry_value_annotation(self): p = Point(1, 1, srid=4326) point = City.objects.annotate(p=Value(p, GeometryField(srid=4326))).first().p self.assertEqual(point, p) @skipUnlessDBFeature("supports_transform") def test_geometry_value_annotation_different_srid(self): p = Point(1, 1, srid=32140) point = City.objects.annotate(p=Value(p, GeometryField(srid=4326))).first().p self.assertTrue(point.equals_exact(p.transform(4326, clone=True), 10**-5)) self.assertEqual(point.srid, 4326) @skipUnlessDBFeature("supports_geography") def test_geography_value(self): p = Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))) area = ( City.objects.annotate( a=functions.Area(Value(p, GeometryField(srid=4326, geography=True))) ) .first() .a ) self.assertAlmostEqual(area.sq_km, 12305.1, 0) def test_update_from_other_field(self): p1 = Point(1, 1, srid=4326) p2 = Point(2, 2, srid=4326) obj = ManyPointModel.objects.create( point1=p1, point2=p2, point3=p2.transform(3857, clone=True), ) # Updating a point to a point of the same SRID. ManyPointModel.objects.filter(pk=obj.pk).update(point2=F("point1")) obj.refresh_from_db() self.assertEqual(obj.point2, p1) # Updating a point to a point with a different SRID. if connection.features.supports_transform: ManyPointModel.objects.filter(pk=obj.pk).update(point3=F("point1")) obj.refresh_from_db() self.assertTrue( obj.point3.equals_exact(p1.transform(3857, clone=True), 0.1) ) def test_multiple_annotation(self): multi_field = MultiFields.objects.create( point=Point(1, 1), city=City.objects.get(name="Houston"), poly=Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))), ) qs = ( City.objects.values("name") .order_by("name") .annotate( distance=Min( functions.Distance("multifields__point", multi_field.city.point) ), ) .annotate(count=Count("multifields")) ) self.assertTrue(qs.first()) @skipUnlessDBFeature("has_Translate_function") def test_update_with_expression(self): city = City.objects.create(point=Point(1, 1, srid=4326)) City.objects.filter(pk=city.pk).update(point=functions.Translate("point", 1, 1)) city.refresh_from_db() self.assertEqual(city.point, Point(2, 2, srid=4326))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false