Dataset Viewer
Auto-converted to Parquet Duplicate
language
stringclasses
2 values
source_code
stringlengths
0
963k
test_code
stringlengths
300
420k
source_path
stringlengths
29
179
test_path
stringlengths
36
183
repo_name
stringclasses
58 values
instruction
stringlengths
380
1.3k
meta_class
stringlengths
2
57
python
import contextlib import os @contextlib.contextmanager def override_environ(**kwargs): save_env = dict(os.environ) for key, value in kwargs.items(): if value is None: del os.environ[key] else: os.environ[key] = value try: yield finally: os.environ.clear() os.environ.update(save_env)
import copy import filecmp import os import tarfile import zipfile from collections import deque from io import BytesIO from unittest import mock import pytest from requests import compat from requests._internal_utils import unicode_is_ascii from requests.cookies import RequestsCookieJar from requests.structures import CaseInsensitiveDict from requests.utils import ( _parse_content_type_header, add_dict_to_cookiejar, address_in_network, dotted_netmask, extract_zipped_paths, get_auth_from_url, get_encoding_from_headers, get_encodings_from_content, get_environ_proxies, get_netrc_auth, guess_filename, guess_json_utf, is_ipv4_address, is_valid_cidr, iter_slices, parse_dict_header, parse_header_links, prepend_scheme_if_needed, requote_uri, select_proxy, set_environ, should_bypass_proxies, super_len, to_key_val_list, to_native_string, unquote_header_value, unquote_unreserved, urldefragauth, ) from .compat import StringIO, cStringIO class TestSuperLen: @pytest.mark.parametrize( "stream, value", ( (StringIO.StringIO, "Test"), (BytesIO, b"Test"), pytest.param( cStringIO, "Test", marks=pytest.mark.skipif("cStringIO is None") ), ), ) def test_io_streams(self, stream, value): """Ensures that we properly deal with different kinds of IO streams.""" assert super_len(stream()) == 0 assert super_len(stream(value)) == 4 def test_super_len_correctly_calculates_len_of_partially_read_file(self): """Ensure that we handle partially consumed file like objects.""" s = StringIO.StringIO() s.write("foobarbogus") assert super_len(s) == 0 @pytest.mark.parametrize("error", [IOError, OSError]) def test_super_len_handles_files_raising_weird_errors_in_tell(self, error): """If tell() raises errors, assume the cursor is at position zero.""" class BoomFile: def __len__(self): return 5 def tell(self): raise error() assert super_len(BoomFile()) == 0 @pytest.mark.parametrize("error", [IOError, OSError]) def test_super_len_tell_ioerror(self, error): """Ensure that if tell gives an IOError super_len doesn't fail""" class NoLenBoomFile: def tell(self): raise error() def seek(self, offset, whence): pass assert super_len(NoLenBoomFile()) == 0 def test_string(self): assert super_len("Test") == 4 @pytest.mark.parametrize( "mode, warnings_num", ( ("r", 1), ("rb", 0), ), ) def test_file(self, tmpdir, mode, warnings_num, recwarn): file_obj = tmpdir.join("test.txt") file_obj.write("Test") with file_obj.open(mode) as fd: assert super_len(fd) == 4 assert len(recwarn) == warnings_num def test_tarfile_member(self, tmpdir): file_obj = tmpdir.join("test.txt") file_obj.write("Test") tar_obj = str(tmpdir.join("test.tar")) with tarfile.open(tar_obj, "w") as tar: tar.add(str(file_obj), arcname="test.txt") with tarfile.open(tar_obj) as tar: member = tar.extractfile("test.txt") assert super_len(member) == 4 def test_super_len_with__len__(self): foo = [1, 2, 3, 4] len_foo = super_len(foo) assert len_foo == 4 def test_super_len_with_no__len__(self): class LenFile: def __init__(self): self.len = 5 assert super_len(LenFile()) == 5 def test_super_len_with_tell(self): foo = StringIO.StringIO("12345") assert super_len(foo) == 5 foo.read(2) assert super_len(foo) == 3 def test_super_len_with_fileno(self): with open(__file__, "rb") as f: length = super_len(f) file_data = f.read() assert length == len(file_data) def test_super_len_with_no_matches(self): """Ensure that objects without any length methods default to 0""" assert super_len(object()) == 0 class TestGetNetrcAuth: def test_works(self, tmp_path, monkeypatch): netrc_path = tmp_path / ".netrc" monkeypatch.setenv("NETRC", str(netrc_path)) with open(netrc_path, "w") as f: f.write("machine example.com login aaaa password bbbb\n") auth = get_netrc_auth("http://example.com/thing") assert auth == ("aaaa", "bbbb") def test_not_vulnerable_to_bad_url_parsing(self, tmp_path, monkeypatch): netrc_path = tmp_path / ".netrc" monkeypatch.setenv("NETRC", str(netrc_path)) with open(netrc_path, "w") as f: f.write("machine example.com login aaaa password bbbb\n") auth = get_netrc_auth("http://example.com:@evil.com/&apos;") assert auth is None class TestToKeyValList: @pytest.mark.parametrize( "value, expected", ( ([("key", "val")], [("key", "val")]), ((("key", "val"),), [("key", "val")]), ({"key": "val"}, [("key", "val")]), (None, None), ), ) def test_valid(self, value, expected): assert to_key_val_list(value) == expected def test_invalid(self): with pytest.raises(ValueError): to_key_val_list("string") class TestUnquoteHeaderValue: @pytest.mark.parametrize( "value, expected", ( (None, None), ("Test", "Test"), ('"Test"', "Test"), ('"Test\\\\"', "Test\\"), ('"\\\\Comp\\Res"', "\\Comp\\Res"), ), ) def test_valid(self, value, expected): assert unquote_header_value(value) == expected def test_is_filename(self): assert unquote_header_value('"\\\\Comp\\Res"', True) == "\\\\Comp\\Res" class TestGetEnvironProxies: """Ensures that IP addresses are correctly matches with ranges in no_proxy variable. """ @pytest.fixture(autouse=True, params=["no_proxy", "NO_PROXY"]) def no_proxy(self, request, monkeypatch): monkeypatch.setenv( request.param, "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1" ) @pytest.mark.parametrize( "url", ( "http://192.168.0.1:5000/", "http://192.168.0.1/", "http://172.16.1.1/", "http://172.16.1.1:5000/", "http://localhost.localdomain:5000/v1.0/", ), ) def test_bypass(self, url): assert get_environ_proxies(url, no_proxy=None) == {} @pytest.mark.parametrize( "url", ( "http://192.168.1.1:5000/", "http://192.168.1.1/", "http://www.requests.com/", ), ) def test_not_bypass(self, url): assert get_environ_proxies(url, no_proxy=None) != {} @pytest.mark.parametrize( "url", ( "http://192.168.1.1:5000/", "http://192.168.1.1/", "http://www.requests.com/", ), ) def test_bypass_no_proxy_keyword(self, url): no_proxy = "192.168.1.1,requests.com" assert get_environ_proxies(url, no_proxy=no_proxy) == {} @pytest.mark.parametrize( "url", ( "http://192.168.0.1:5000/", "http://192.168.0.1/", "http://172.16.1.1/", "http://172.16.1.1:5000/", "http://localhost.localdomain:5000/v1.0/", ), ) def test_not_bypass_no_proxy_keyword(self, url, monkeypatch): # This is testing that the 'no_proxy' argument overrides the # environment variable 'no_proxy' monkeypatch.setenv("http_proxy", "http://proxy.example.com:3128/") no_proxy = "192.168.1.1,requests.com" assert get_environ_proxies(url, no_proxy=no_proxy) != {} class TestIsIPv4Address: def test_valid(self): assert is_ipv4_address("8.8.8.8") @pytest.mark.parametrize("value", ("8.8.8.8.8", "localhost.localdomain")) def test_invalid(self, value): assert not is_ipv4_address(value) class TestIsValidCIDR: def test_valid(self): assert is_valid_cidr("192.168.1.0/24") @pytest.mark.parametrize( "value", ( "8.8.8.8", "192.168.1.0/a", "192.168.1.0/128", "192.168.1.0/-1", "192.168.1.999/24", ), ) def test_invalid(self, value): assert not is_valid_cidr(value) class TestAddressInNetwork: def test_valid(self): assert address_in_network("192.168.1.1", "192.168.1.0/24") def test_invalid(self): assert not address_in_network("172.16.0.1", "192.168.1.0/24") class TestGuessFilename: @pytest.mark.parametrize( "value", (1, type("Fake", (object,), {"name": 1})()), ) def test_guess_filename_invalid(self, value): assert guess_filename(value) is None @pytest.mark.parametrize( "value, expected_type", ( (b"value", compat.bytes), (b"value".decode("utf-8"), compat.str), ), ) def test_guess_filename_valid(self, value, expected_type): obj = type("Fake", (object,), {"name": value})() result = guess_filename(obj) assert result == value assert isinstance(result, expected_type) class TestExtractZippedPaths: @pytest.mark.parametrize( "path", ( "/", __file__, pytest.__file__, "/etc/invalid/location", ), ) def test_unzipped_paths_unchanged(self, path): assert path == extract_zipped_paths(path) def test_zipped_paths_extracted(self, tmpdir): zipped_py = tmpdir.join("test.zip") with zipfile.ZipFile(zipped_py.strpath, "w") as f: f.write(__file__) _, name = os.path.splitdrive(__file__) zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r"\/")) extracted_path = extract_zipped_paths(zipped_path) assert extracted_path != zipped_path assert os.path.exists(extracted_path) assert filecmp.cmp(extracted_path, __file__) def test_invalid_unc_path(self): path = r"\\localhost\invalid\location" assert extract_zipped_paths(path) == path class TestContentEncodingDetection: def test_none(self): encodings = get_encodings_from_content("") assert not len(encodings) @pytest.mark.parametrize( "content", ( # HTML5 meta charset attribute '<meta charset="UTF-8">', # HTML4 pragma directive '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">', # XHTML 1.x served with text/html MIME type '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />', # XHTML 1.x served as XML '<?xml version="1.0" encoding="UTF-8"?>', ), ) def test_pragmas(self, content): encodings = get_encodings_from_content(content) assert len(encodings) == 1 assert encodings[0] == "UTF-8" def test_precedence(self): content = """ <?xml version="1.0" encoding="XML"?> <meta charset="HTML5"> <meta http-equiv="Content-type" content="text/html;charset=HTML4" /> """.strip() assert get_encodings_from_content(content) == ["HTML5", "HTML4", "XML"] class TestGuessJSONUTF: @pytest.mark.parametrize( "encoding", ( "utf-32", "utf-8-sig", "utf-16", "utf-8", "utf-16-be", "utf-16-le", "utf-32-be", "utf-32-le", ), ) def test_encoded(self, encoding): data = "{}".encode(encoding) assert guess_json_utf(data) == encoding def test_bad_utf_like_encoding(self): assert guess_json_utf(b"\x00\x00\x00\x00") is None @pytest.mark.parametrize( ("encoding", "expected"), ( ("utf-16-be", "utf-16"), ("utf-16-le", "utf-16"), ("utf-32-be", "utf-32"), ("utf-32-le", "utf-32"), ), ) def test_guess_by_bom(self, encoding, expected): data = "\ufeff{}".encode(encoding) assert guess_json_utf(data) == expected USER = PASSWORD = "%!*'();:@&=+$,/?#[] " ENCODED_USER = compat.quote(USER, "") ENCODED_PASSWORD = compat.quote(PASSWORD, "") @pytest.mark.parametrize( "url, auth", ( ( f"http://{ENCODED_USER}:{ENCODED_PASSWORD}@request.com/url.html#test", (USER, PASSWORD), ), ("http://user:[email protected]/path?query=yes", ("user", "pass")), ( "http://user:pass%[email protected]/path?query=yes", ("user", "pass pass"), ), ("http://user:pass [email protected]/path?query=yes", ("user", "pass pass")), ( "http://user%25user:[email protected]/path?query=yes", ("user%user", "pass"), ), ( "http://user:pass%[email protected]/path?query=yes", ("user", "pass#pass"), ), ("http://complex.url.com/path?query=yes", ("", "")), ), ) def test_get_auth_from_url(url, auth): assert get_auth_from_url(url) == auth @pytest.mark.parametrize( "uri, expected", ( ( # Ensure requoting doesn't break expectations "http://example.com/fiz?buz=%25ppicture", "http://example.com/fiz?buz=%25ppicture", ), ( # Ensure we handle unquoted percent signs in redirects "http://example.com/fiz?buz=%ppicture", "http://example.com/fiz?buz=%25ppicture", ), ), ) def test_requote_uri_with_unquoted_percents(uri, expected): """See: https://github.com/psf/requests/issues/2356""" assert requote_uri(uri) == expected @pytest.mark.parametrize( "uri, expected", ( ( # Illegal bytes "http://example.com/?a=%--", "http://example.com/?a=%--", ), ( # Reserved characters "http://example.com/?a=%300", "http://example.com/?a=00", ), ), ) def test_unquote_unreserved(uri, expected): assert unquote_unreserved(uri) == expected @pytest.mark.parametrize( "mask, expected", ( (8, "255.0.0.0"), (24, "255.255.255.0"), (25, "255.255.255.128"), ), ) def test_dotted_netmask(mask, expected): assert dotted_netmask(mask) == expected http_proxies = { "http": "http://http.proxy", "http://some.host": "http://some.host.proxy", } all_proxies = { "all": "socks5://http.proxy", "all://some.host": "socks5://some.host.proxy", } mixed_proxies = { "http": "http://http.proxy", "http://some.host": "http://some.host.proxy", "all": "socks5://http.proxy", } @pytest.mark.parametrize( "url, expected, proxies", ( ("hTTp://u:[email protected]/path", "http://some.host.proxy", http_proxies), ("hTTp://u:[email protected]/path", "http://http.proxy", http_proxies), ("hTTp:///path", "http://http.proxy", http_proxies), ("hTTps://Other.Host", None, http_proxies), ("file:///etc/motd", None, http_proxies), ("hTTp://u:[email protected]/path", "socks5://some.host.proxy", all_proxies), ("hTTp://u:[email protected]/path", "socks5://http.proxy", all_proxies), ("hTTp:///path", "socks5://http.proxy", all_proxies), ("hTTps://Other.Host", "socks5://http.proxy", all_proxies), ("http://u:[email protected]/path", "http://http.proxy", mixed_proxies), ("http://u:[email protected]/path", "http://some.host.proxy", mixed_proxies), ("https://u:[email protected]/path", "socks5://http.proxy", mixed_proxies), ("https://u:[email protected]/path", "socks5://http.proxy", mixed_proxies), ("https://", "socks5://http.proxy", mixed_proxies), # XXX: unsure whether this is reasonable behavior ("file:///etc/motd", "socks5://http.proxy", all_proxies), ), ) def test_select_proxies(url, expected, proxies): """Make sure we can select per-host proxies correctly.""" assert select_proxy(url, proxies) == expected @pytest.mark.parametrize( "value, expected", ( ('foo="is a fish", bar="as well"', {"foo": "is a fish", "bar": "as well"}), ("key_without_value", {"key_without_value": None}), ), ) def test_parse_dict_header(value, expected): assert parse_dict_header(value) == expected @pytest.mark.parametrize( "value, expected", ( ("application/xml", ("application/xml", {})), ( "application/json ; charset=utf-8", ("application/json", {"charset": "utf-8"}), ), ( "application/json ; Charset=utf-8", ("application/json", {"charset": "utf-8"}), ), ("text/plain", ("text/plain", {})), ( "multipart/form-data; boundary = something ; boundary2='something_else' ; no_equals ", ( "multipart/form-data", { "boundary": "something", "boundary2": "something_else", "no_equals": True, }, ), ), ( 'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ', ( "multipart/form-data", { "boundary": "something", "boundary2": "something_else", "no_equals": True, }, ), ), ( "multipart/form-data; boundary = something ; 'boundary2=something_else' ; no_equals ", ( "multipart/form-data", { "boundary": "something", "boundary2": "something_else", "no_equals": True, }, ), ), ( 'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ', ( "multipart/form-data", { "boundary": "something", "boundary2": "something_else", "no_equals": True, }, ), ), ("application/json ; ; ", ("application/json", {})), ), ) def test__parse_content_type_header(value, expected): assert _parse_content_type_header(value) == expected @pytest.mark.parametrize( "value, expected", ( (CaseInsensitiveDict(), None), ( CaseInsensitiveDict({"content-type": "application/json; charset=utf-8"}), "utf-8", ), (CaseInsensitiveDict({"content-type": "text/plain"}), "ISO-8859-1"), ), ) def test_get_encoding_from_headers(value, expected): assert get_encoding_from_headers(value) == expected @pytest.mark.parametrize( "value, length", ( ("", 0), ("T", 1), ("Test", 4), ("Cont", 0), ("Other", -5), ("Content", None), ), ) def test_iter_slices(value, length): if length is None or (length <= 0 and len(value) > 0): # Reads all content at once assert len(list(iter_slices(value, length))) == 1 else: assert len(list(iter_slices(value, 1))) == length @pytest.mark.parametrize( "value, expected", ( ( '<http:/.../front.jpeg>; rel=front; type="image/jpeg"', [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}], ), ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]), ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]), ( '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;', [ {"url": "http:/.../front.jpeg", "type": "image/jpeg"}, {"url": "http://.../back.jpeg"}, ], ), ("", []), ), ) def test_parse_header_links(value, expected): assert parse_header_links(value) == expected @pytest.mark.parametrize( "value, expected", ( ("example.com/path", "http://example.com/path"), ("//example.com/path", "http://example.com/path"), ("example.com:80", "http://example.com:80"), ( "http://user:[email protected]/path?query", "http://user:[email protected]/path?query", ), ("http://[email protected]/path?query", "http://[email protected]/path?query"), ), ) def test_prepend_scheme_if_needed(value, expected): assert prepend_scheme_if_needed(value, "http") == expected @pytest.mark.parametrize( "value, expected", ( ("T", "T"), (b"T", "T"), ("T", "T"), ), ) def test_to_native_string(value, expected): assert to_native_string(value) == expected @pytest.mark.parametrize( "url, expected", ( ("http://u:[email protected]/path?a=1#test", "http://example.com/path?a=1"), ("http://example.com/path", "http://example.com/path"), ("//u:[email protected]/path", "//example.com/path"), ("//example.com/path", "//example.com/path"), ("example.com/path", "//example.com/path"), ("scheme:u:[email protected]/path", "scheme://example.com/path"), ), ) def test_urldefragauth(url, expected): assert urldefragauth(url) == expected @pytest.mark.parametrize( "url, expected", ( ("http://192.168.0.1:5000/", True), ("http://192.168.0.1/", True), ("http://172.16.1.1/", True), ("http://172.16.1.1:5000/", True), ("http://localhost.localdomain:5000/v1.0/", True), ("http://google.com:6000/", True), ("http://172.16.1.12/", False), ("http://172.16.1.12:5000/", False), ("http://google.com:5000/v1.0/", False), ("file:///some/path/on/disk", True), ), ) def test_should_bypass_proxies(url, expected, monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not """ monkeypatch.setenv( "no_proxy", "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000", ) monkeypatch.setenv( "NO_PROXY", "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000", ) assert should_bypass_proxies(url, no_proxy=None) == expected @pytest.mark.parametrize( "url, expected", ( ("http://172.16.1.1/", "172.16.1.1"), ("http://172.16.1.1:5000/", "172.16.1.1"), ("http://user:[email protected]", "172.16.1.1"), ("http://user:[email protected]:5000", "172.16.1.1"), ("http://hostname/", "hostname"), ("http://hostname:5000/", "hostname"), ("http://user:pass@hostname", "hostname"), ("http://user:pass@hostname:5000", "hostname"), ), ) def test_should_bypass_proxies_pass_only_hostname(url, expected): """The proxy_bypass function should be called with a hostname or IP without a port number or auth credentials. """ with mock.patch("requests.utils.proxy_bypass") as proxy_bypass: should_bypass_proxies(url, no_proxy=None) proxy_bypass.assert_called_once_with(expected) @pytest.mark.parametrize( "cookiejar", ( compat.cookielib.CookieJar(), RequestsCookieJar(), ), ) def test_add_dict_to_cookiejar(cookiejar): """Ensure add_dict_to_cookiejar works for non-RequestsCookieJar CookieJars """ cookiedict = {"test": "cookies", "good": "cookies"} cj = add_dict_to_cookiejar(cookiejar, cookiedict) cookies = {cookie.name: cookie.value for cookie in cj} assert cookiedict == cookies @pytest.mark.parametrize( "value, expected", ( ("test", True), ("æíöû", False), ("ジェーピーニック", False), ), ) def test_unicode_is_ascii(value, expected): assert unicode_is_ascii(value) is expected @pytest.mark.parametrize( "url, expected", ( ("http://192.168.0.1:5000/", True), ("http://192.168.0.1/", True), ("http://172.16.1.1/", True), ("http://172.16.1.1:5000/", True), ("http://localhost.localdomain:5000/v1.0/", True), ("http://172.16.1.12/", False), ("http://172.16.1.12:5000/", False), ("http://google.com:5000/v1.0/", False), ), ) def test_should_bypass_proxies_no_proxy(url, expected, monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not using the 'no_proxy' argument """ no_proxy = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1" # Test 'no_proxy' argument assert should_bypass_proxies(url, no_proxy=no_proxy) == expected @pytest.mark.skipif(os.name != "nt", reason="Test only on Windows") @pytest.mark.parametrize( "url, expected, override", ( ("http://192.168.0.1:5000/", True, None), ("http://192.168.0.1/", True, None), ("http://172.16.1.1/", True, None), ("http://172.16.1.1:5000/", True, None), ("http://localhost.localdomain:5000/v1.0/", True, None), ("http://172.16.1.22/", False, None), ("http://172.16.1.22:5000/", False, None), ("http://google.com:5000/v1.0/", False, None), ("http://mylocalhostname:5000/v1.0/", True, "<local>"), ("http://192.168.0.1/", False, ""), ), ) def test_should_bypass_proxies_win_registry(url, expected, override, monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not with Windows registry settings """ if override is None: override = "192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1" import winreg class RegHandle: def Close(self): pass ie_settings = RegHandle() proxyEnableValues = deque([1, "1"]) def OpenKey(key, subkey): return ie_settings def QueryValueEx(key, value_name): if key is ie_settings: if value_name == "ProxyEnable": # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD) proxyEnableValues.rotate() return [proxyEnableValues[0]] elif value_name == "ProxyOverride": return [override] monkeypatch.setenv("http_proxy", "") monkeypatch.setenv("https_proxy", "") monkeypatch.setenv("ftp_proxy", "") monkeypatch.setenv("no_proxy", "") monkeypatch.setenv("NO_PROXY", "") monkeypatch.setattr(winreg, "OpenKey", OpenKey) monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx) assert should_bypass_proxies(url, None) == expected @pytest.mark.skipif(os.name != "nt", reason="Test only on Windows") def test_should_bypass_proxies_win_registry_bad_values(monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not with Windows invalid registry settings. """ import winreg class RegHandle: def Close(self): pass ie_settings = RegHandle() def OpenKey(key, subkey): return ie_settings def QueryValueEx(key, value_name): if key is ie_settings: if value_name == "ProxyEnable": # Invalid response; Should be an int or int-y value return [""] elif value_name == "ProxyOverride": return ["192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1"] monkeypatch.setenv("http_proxy", "") monkeypatch.setenv("https_proxy", "") monkeypatch.setenv("no_proxy", "") monkeypatch.setenv("NO_PROXY", "") monkeypatch.setattr(winreg, "OpenKey", OpenKey) monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx) assert should_bypass_proxies("http://172.16.1.1/", None) is False @pytest.mark.parametrize( "env_name, value", ( ("no_proxy", "192.168.0.0/24,127.0.0.1,localhost.localdomain"), ("no_proxy", None), ("a_new_key", "192.168.0.0/24,127.0.0.1,localhost.localdomain"), ("a_new_key", None), ), ) def test_set_environ(env_name, value): """Tests set_environ will set environ values and will restore the environ.""" environ_copy = copy.deepcopy(os.environ) with set_environ(env_name, value): assert os.environ.get(env_name) == value assert os.environ == environ_copy def test_set_environ_raises_exception(): """Tests set_environ will raise exceptions in context when the value parameter is None.""" with pytest.raises(Exception) as exception: with set_environ("test1", None): raise Exception("Expected exception") assert "Expected exception" in str(exception.value) @pytest.mark.skipif(os.name != "nt", reason="Test only on Windows") def test_should_bypass_proxies_win_registry_ProxyOverride_value(monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not with Windows ProxyOverride registry value ending with a semicolon. """ import winreg class RegHandle: def Close(self): pass ie_settings = RegHandle() def OpenKey(key, subkey): return ie_settings def QueryValueEx(key, value_name): if key is ie_settings: if value_name == "ProxyEnable": return [1] elif value_name == "ProxyOverride": return [ "192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1;<-loopback>;" ] monkeypatch.setenv("NO_PROXY", "") monkeypatch.setenv("no_proxy", "") monkeypatch.setattr(winreg, "OpenKey", OpenKey) monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx) assert should_bypass_proxies("http://example.com/", None) is False
./temp_repos/requests/tests/utils.py
./temp_repos/requests/tests/test_utils.py
requests
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: os, contextlib Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external dependencies listed above. 3. Test both success and failure scenarios. 4. Use the AAA (Arrange, Act, Assert) pattern.
Unknown
python
""" requests.hooks ~~~~~~~~~~~~~~ This module provides the capabilities for the Requests hooks system. Available hooks: ``response``: The response generated from a Request. """ HOOKS = ["response"] def default_hooks(): return {event: [] for event in HOOKS} # TODO: response is the only one def dispatch_hook(key, hooks, hook_data, **kwargs): """Dispatches a hook dictionary on a given piece of data.""" hooks = hooks or {} hooks = hooks.get(key) if hooks: if hasattr(hooks, "__call__"): hooks = [hooks] for hook in hooks: _hook_data = hook(hook_data, **kwargs) if _hook_data is not None: hook_data = _hook_data return hook_data
import pytest from requests import hooks def hook(value): return value[1:] @pytest.mark.parametrize( "hooks_list, result", ( (hook, "ata"), ([hook, lambda x: None, hook], "ta"), ), ) def test_hooks(hooks_list, result): assert hooks.dispatch_hook("response", {"response": hooks_list}, "Data") == result def test_default_hooks(): assert hooks.default_hooks() == {"response": []}
./temp_repos/requests/src/requests/hooks.py
./temp_repos/requests/tests/test_hooks.py
requests
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external dependencies listed above. 3. Test both success and failure scenarios. 4. Use the AAA (Arrange, Act, Assert) pattern.
Unknown
python
"""Module containing bug report helper(s).""" import json import platform import ssl import sys import idna import urllib3 from . import __version__ as requests_version try: import charset_normalizer except ImportError: charset_normalizer = None try: import chardet except ImportError: chardet = None try: from urllib3.contrib import pyopenssl except ImportError: pyopenssl = None OpenSSL = None cryptography = None else: import cryptography import OpenSSL def _implementation(): """Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 3.10.3 it will return {'name': 'CPython', 'version': '3.10.3'}. This function works best on CPython and PyPy: in particular, it probably doesn't work for Jython or IronPython. Future investigation should be done to work out the correct shape of the code for those platforms. """ implementation = platform.python_implementation() if implementation == "CPython": implementation_version = platform.python_version() elif implementation == "PyPy": implementation_version = "{}.{}.{}".format( sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro, ) if sys.pypy_version_info.releaselevel != "final": implementation_version = "".join( [implementation_version, sys.pypy_version_info.releaselevel] ) elif implementation == "Jython": implementation_version = platform.python_version() # Complete Guess elif implementation == "IronPython": implementation_version = platform.python_version() # Complete Guess else: implementation_version = "Unknown" return {"name": implementation, "version": implementation_version} def info(): """Generate information for a bug report.""" try: platform_info = { "system": platform.system(), "release": platform.release(), } except OSError: platform_info = { "system": "Unknown", "release": "Unknown", } implementation_info = _implementation() urllib3_info = {"version": urllib3.__version__} charset_normalizer_info = {"version": None} chardet_info = {"version": None} if charset_normalizer: charset_normalizer_info = {"version": charset_normalizer.__version__} if chardet: chardet_info = {"version": chardet.__version__} pyopenssl_info = { "version": None, "openssl_version": "", } if OpenSSL: pyopenssl_info = { "version": OpenSSL.__version__, "openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}", } cryptography_info = { "version": getattr(cryptography, "__version__", ""), } idna_info = { "version": getattr(idna, "__version__", ""), } system_ssl = ssl.OPENSSL_VERSION_NUMBER system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""} return { "platform": platform_info, "implementation": implementation_info, "system_ssl": system_ssl_info, "using_pyopenssl": pyopenssl is not None, "using_charset_normalizer": chardet is None, "pyOpenSSL": pyopenssl_info, "urllib3": urllib3_info, "chardet": chardet_info, "charset_normalizer": charset_normalizer_info, "cryptography": cryptography_info, "idna": idna_info, "requests": { "version": requests_version, }, } def main(): """Pretty-print the bug information as JSON.""" print(json.dumps(info(), sort_keys=True, indent=2)) if __name__ == "__main__": main()
from unittest import mock from requests.help import info def test_system_ssl(): """Verify we're actually setting system_ssl when it should be available.""" assert info()["system_ssl"]["version"] != "" class VersionedPackage: def __init__(self, version): self.__version__ = version def test_idna_without_version_attribute(): """Older versions of IDNA don't provide a __version__ attribute, verify that if we have such a package, we don't blow up. """ with mock.patch("requests.help.idna", new=None): assert info()["idna"] == {"version": ""} def test_idna_with_version_attribute(): """Verify we're actually setting idna version when it should be available.""" with mock.patch("requests.help.idna", new=VersionedPackage("2.6")): assert info()["idna"] == {"version": "2.6"}
./temp_repos/requests/src/requests/help.py
./temp_repos/requests/tests/test_help.py
requests
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: OpenSSL, platform, urllib3.contrib, idna, ssl, urllib3, chardet, json, charset_normalizer, cryptography Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external dependencies listed above. 3. Test both success and failure scenarios. 4. Use the AAA (Arrange, Act, Assert) pattern.
Unknown
python
""" Built-in, globally-available admin actions. """ from django.contrib import messages from django.contrib.admin import helpers from django.contrib.admin.decorators import action from django.contrib.admin.utils import model_ngettext from django.core.exceptions import PermissionDenied from django.template.response import TemplateResponse from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy @action( permissions=["delete"], description=gettext_lazy("Delete selected %(verbose_name_plural)s"), ) def delete_selected(modeladmin, request, queryset): """ Default action which deletes the selected objects. This action first displays a confirmation page which shows all the deletable objects, or, if the user has no permission one of the related childs (foreignkeys), a "permission denied" message. Next, it deletes all selected objects and redirects back to the change list. """ opts = modeladmin.model._meta app_label = opts.app_label # Populate deletable_objects, a data structure of all related objects that # will also be deleted. ( deletable_objects, model_count, perms_needed, protected, ) = modeladmin.get_deleted_objects(queryset, request) # The user has already confirmed the deletion. # Do the deletion and return None to display the change list view again. if request.POST.get("post") and not protected: if perms_needed: raise PermissionDenied n = len(queryset) if n: modeladmin.log_deletions(request, queryset) modeladmin.delete_queryset(request, queryset) modeladmin.message_user( request, _("Successfully deleted %(count)d %(items)s.") % {"count": n, "items": model_ngettext(modeladmin.opts, n)}, messages.SUCCESS, ) # Return None to display the change list page again. return None objects_name = model_ngettext(queryset) if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": objects_name} else: title = _("Delete multiple objects") context = { **modeladmin.admin_site.each_context(request), "title": title, "subtitle": None, "objects_name": str(objects_name), "deletable_objects": [deletable_objects], "model_count": dict(model_count).items(), "queryset": queryset, "perms_lacking": perms_needed, "protected": protected, "opts": opts, "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME, "media": modeladmin.media, } request.current_app = modeladmin.admin_site.name # Display the confirmation page return TemplateResponse( request, modeladmin.delete_selected_confirmation_template or [ "admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.model_name), "admin/%s/delete_selected_confirmation.html" % app_label, "admin/delete_selected_confirmation.html", ], context, )
from django.contrib import admin from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.test import TestCase from .models import Band class AdminActionsTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) content_type = ContentType.objects.get_for_model(Band) Permission.objects.create( name="custom", codename="custom_band", content_type=content_type ) for user_type in ("view", "add", "change", "delete", "custom"): username = "%suser" % user_type user = User.objects.create_user( username=username, password="secret", is_staff=True ) permission = Permission.objects.get( codename="%s_band" % user_type, content_type=content_type ) user.user_permissions.add(permission) setattr(cls, username, user) def test_get_actions_respects_permissions(self): class MockRequest: pass class BandAdmin(admin.ModelAdmin): actions = ["custom_action"] @admin.action def custom_action(modeladmin, request, queryset): pass def has_custom_permission(self, request): return request.user.has_perm("%s.custom_band" % self.opts.app_label) ma = BandAdmin(Band, admin.AdminSite()) mock_request = MockRequest() mock_request.GET = {} cases = [ (None, self.viewuser, ["custom_action"]), ("view", self.superuser, ["delete_selected", "custom_action"]), ("view", self.viewuser, ["custom_action"]), ("add", self.adduser, ["custom_action"]), ("change", self.changeuser, ["custom_action"]), ("delete", self.deleteuser, ["delete_selected", "custom_action"]), ("custom", self.customuser, ["custom_action"]), ] for permission, user, expected in cases: with self.subTest(permission=permission, user=user): if permission is None: if hasattr(BandAdmin.custom_action, "allowed_permissions"): del BandAdmin.custom_action.allowed_permissions else: BandAdmin.custom_action.allowed_permissions = (permission,) mock_request.user = user actions = ma.get_actions(mock_request) self.assertEqual(list(actions.keys()), expected) def test_actions_inheritance(self): class AdminBase(admin.ModelAdmin): actions = ["custom_action"] @admin.action def custom_action(modeladmin, request, queryset): pass class AdminA(AdminBase): pass class AdminB(AdminBase): actions = None ma1 = AdminA(Band, admin.AdminSite()) action_names = [name for _, name, _ in ma1._get_base_actions()] self.assertEqual(action_names, ["delete_selected", "custom_action"]) # `actions = None` removes actions from superclasses. ma2 = AdminB(Band, admin.AdminSite()) action_names = [name for _, name, _ in ma2._get_base_actions()] self.assertEqual(action_names, ["delete_selected"]) def test_global_actions_description(self): @admin.action(description="Site-wide admin action 1.") def global_action_1(modeladmin, request, queryset): pass @admin.action def global_action_2(modeladmin, request, queryset): pass admin_site = admin.AdminSite() admin_site.add_action(global_action_1) admin_site.add_action(global_action_2) class BandAdmin(admin.ModelAdmin): pass ma = BandAdmin(Band, admin_site) self.assertEqual( [description for _, _, description in ma._get_base_actions()], [ "Delete selected %(verbose_name_plural)s", "Site-wide admin action 1.", "Global action 2", ], ) def test_actions_replace_global_action(self): @admin.action(description="Site-wide admin action 1.") def global_action_1(modeladmin, request, queryset): pass @admin.action(description="Site-wide admin action 2.") def global_action_2(modeladmin, request, queryset): pass admin.site.add_action(global_action_1, name="custom_action_1") admin.site.add_action(global_action_2, name="custom_action_2") @admin.action(description="Local admin action 1.") def custom_action_1(modeladmin, request, queryset): pass class BandAdmin(admin.ModelAdmin): actions = [custom_action_1, "custom_action_2"] @admin.action(description="Local admin action 2.") def custom_action_2(self, request, queryset): pass ma = BandAdmin(Band, admin.site) self.assertEqual(ma.check(), []) self.assertEqual( [ desc for _, name, desc in ma._get_base_actions() if name.startswith("custom_action") ], [ "Local admin action 1.", "Local admin action 2.", ], )
./temp_repos/django/django/contrib/admin/actions.py
./temp_repos/django/tests/modeladmin/test_actions.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.contrib.admin.decorators, django.contrib.admin, django.core.exceptions, django.contrib.admin.utils, django.contrib, django.utils.translation, django.template.response Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external dependencies listed above. 3. Test both success and failure scenarios. 4. Use the AAA (Arrange, Act, Assert) pattern.
Unknown
python
from ctypes import c_void_p class CPointerBase: """ Base class for objects that have a pointer access property that controls access to the underlying C pointer. """ _ptr = None # Initially the pointer is NULL. ptr_type = c_void_p destructor = None null_ptr_exception_class = AttributeError @property def ptr(self): # Raise an exception if the pointer isn't valid so that NULL pointers # aren't passed to routines -- that's very bad. if self._ptr: return self._ptr raise self.null_ptr_exception_class( "NULL %s pointer encountered." % self.__class__.__name__ ) @ptr.setter def ptr(self, ptr): # Only allow the pointer to be set with pointers of the compatible # type or None (NULL). if not (ptr is None or isinstance(ptr, self.ptr_type)): raise TypeError("Incompatible pointer type: %s." % type(ptr)) self._ptr = ptr def __del__(self): """ Free the memory used by the C++ object. """ if self.destructor and self._ptr: try: self.destructor(self.ptr) except (AttributeError, ImportError, TypeError): pass # Some part might already have been garbage collected
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
./temp_repos/django/django/contrib/gis/ptr.py
./temp_repos/django/tests/gis_tests/test_ptr.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'CPointerBase'. Context: - Class Name: CPointerBase - Dependencies to Mock: None detected - Key Imports: ctypes Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external dependencies listed above. 3. Test both success and failure scenarios. 4. Use the AAA (Arrange, Act, Assert) pattern.
CPointerBase
python
""" This module houses the GeoIP2 object, a wrapper for the MaxMind GeoIP2(R) Python API (https://geoip2.readthedocs.io/). This is an alternative to the Python GeoIP2 interface provided by MaxMind. GeoIP(R) is a registered trademark of MaxMind, Inc. For IP-based geolocation, this module requires the GeoLite2 Country and City datasets, in binary format (CSV will not work!). The datasets may be downloaded from MaxMind at https://dev.maxmind.com/geoip/geoip2/geolite2/. Grab GeoLite2-Country.mmdb.gz and GeoLite2-City.mmdb.gz, and unzip them in the directory corresponding to settings.GEOIP_PATH. """ import ipaddress import socket from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import validate_ipv46_address from django.utils._os import to_path from django.utils.functional import cached_property __all__ = ["HAS_GEOIP2"] try: import geoip2.database except ImportError: # pragma: no cover HAS_GEOIP2 = False else: HAS_GEOIP2 = True __all__ += ["GeoIP2", "GeoIP2Exception"] # These are the values stored in the `database_type` field of the metadata. # See https://maxmind.github.io/MaxMind-DB/#database_type for details. SUPPORTED_DATABASE_TYPES = { "DBIP-City-Lite", "DBIP-Country-Lite", "GeoIP2-City", "GeoIP2-Country", "GeoLite2-City", "GeoLite2-Country", } class GeoIP2Exception(Exception): pass class GeoIP2: # The flags for GeoIP memory caching. # Try MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that order. MODE_AUTO = 0 # Use the C extension with memory map. MODE_MMAP_EXT = 1 # Read from memory map. Pure Python. MODE_MMAP = 2 # Read database as standard file. Pure Python. MODE_FILE = 4 # Load database into memory. Pure Python. MODE_MEMORY = 8 cache_options = frozenset( (MODE_AUTO, MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, MODE_MEMORY) ) _path = None _reader = None def __init__(self, path=None, cache=0, country=None, city=None): """ Initialize the GeoIP object. No parameters are required to use default settings. Keyword arguments may be passed in to customize the locations of the GeoIP datasets. * path: Base directory to where GeoIP data is located or the full path to where the city or country data files (*.mmdb) are located. Assumes that both the city and country data sets are located in this directory; overrides the GEOIP_PATH setting. * cache: The cache settings when opening up the GeoIP datasets. May be an integer in (0, 1, 2, 4, 8) corresponding to the MODE_AUTO, MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, and MODE_MEMORY, `GeoIPOptions` C API settings, respectively. Defaults to 0, meaning MODE_AUTO. * country: The name of the GeoIP country data file. Defaults to 'GeoLite2-Country.mmdb'; overrides the GEOIP_COUNTRY setting. * city: The name of the GeoIP city data file. Defaults to 'GeoLite2-City.mmdb'; overrides the GEOIP_CITY setting. """ if cache not in self.cache_options: raise GeoIP2Exception("Invalid GeoIP caching option: %s" % cache) path = path or getattr(settings, "GEOIP_PATH", None) city = city or getattr(settings, "GEOIP_CITY", "GeoLite2-City.mmdb") country = country or getattr(settings, "GEOIP_COUNTRY", "GeoLite2-Country.mmdb") if not path: raise GeoIP2Exception( "GeoIP path must be provided via parameter or the GEOIP_PATH setting." ) path = to_path(path) # Try the path first in case it is the full path to a database. for path in (path, path / city, path / country): if path.is_file(): self._path = path self._reader = geoip2.database.Reader(path, mode=cache) break else: raise GeoIP2Exception( "Path must be a valid database or directory containing databases." ) database_type = self._metadata.database_type if database_type not in SUPPORTED_DATABASE_TYPES: raise GeoIP2Exception(f"Unable to handle database edition: {database_type}") def __del__(self): # Cleanup any GeoIP file handles lying around. if self._reader: self._reader.close() def __repr__(self): m = self._metadata version = f"v{m.binary_format_major_version}.{m.binary_format_minor_version}" return f"<{self.__class__.__name__} [{version}] _path='{self._path}'>" @cached_property def _metadata(self): return self._reader.metadata() @cached_property def is_city(self): return "City" in self._metadata.database_type @cached_property def is_country(self): return "Country" in self._metadata.database_type def _query(self, query, *, require_city=False): if not isinstance(query, (str, ipaddress.IPv4Address, ipaddress.IPv6Address)): raise TypeError( "GeoIP query must be a string or instance of IPv4Address or " "IPv6Address, not type %s" % type(query).__name__, ) if require_city and not self.is_city: raise GeoIP2Exception(f"Invalid GeoIP city data file: {self._path}") if isinstance(query, str): try: validate_ipv46_address(query) except ValidationError: # GeoIP2 only takes IP addresses, so try to resolve a hostname. query = socket.gethostbyname(query) function = self._reader.city if self.is_city else self._reader.country return function(query) def city(self, query): """ Return a dictionary of city information for the given IP address or Fully Qualified Domain Name (FQDN). Some information in the dictionary may be undefined (None). """ response = self._query(query, require_city=True) region = response.subdivisions[0] if response.subdivisions else None return { "accuracy_radius": response.location.accuracy_radius, "city": response.city.name, "continent_code": response.continent.code, "continent_name": response.continent.name, "country_code": response.country.iso_code, "country_name": response.country.name, "is_in_european_union": response.country.is_in_european_union, "latitude": response.location.latitude, "longitude": response.location.longitude, "metro_code": response.location.metro_code, "postal_code": response.postal.code, "region_code": region.iso_code if region else None, "region_name": region.name if region else None, "time_zone": response.location.time_zone, # Kept for backward compatibility. "dma_code": response.location.metro_code, "region": region.iso_code if region else None, } def country_code(self, query): "Return the country code for the given IP Address or FQDN." return self.country(query)["country_code"] def country_name(self, query): "Return the country name for the given IP Address or FQDN." return self.country(query)["country_name"] def country(self, query): """ Return a dictionary with the country code and name when given an IP address or a Fully Qualified Domain Name (FQDN). For example, both '24.124.1.80' and 'djangoproject.com' are valid parameters. """ response = self._query(query, require_city=False) return { "continent_code": response.continent.code, "continent_name": response.continent.name, "country_code": response.country.iso_code, "country_name": response.country.name, "is_in_european_union": response.country.is_in_european_union, } def lon_lat(self, query): "Return a tuple of the (longitude, latitude) for the given query." data = self.city(query) return data["longitude"], data["latitude"] def lat_lon(self, query): "Return a tuple of the (latitude, longitude) for the given query." data = self.city(query) return data["latitude"], data["longitude"] def geos(self, query): "Return a GEOS Point object for the given query." # Allows importing and using GeoIP2() when GEOS is not installed. from django.contrib.gis.geos import Point return Point(self.lon_lat(query), srid=4326)
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()
./temp_repos/django/django/contrib/gis/geoip2.py
./temp_repos/django/tests/gis_tests/test_geoip2.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'GeoIP2Exception'. Context: - Class Name: GeoIP2Exception - Dependencies to Mock: cache, path, country, city - Key Imports: django.utils.functional, django.conf, django.contrib.gis.geos, django.core.validators, ipaddress, django.core.exceptions, django.utils._os, geoip2.database, socket Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external dependencies listed above. 3. Test both success and failure scenarios. 4. Use the AAA (Arrange, Act, Assert) pattern.
GeoIP2Exception
python
""" ******** Models for test_data.py *********** The following classes are for testing basic data marshalling, including NULL values, where allowed. The basic idea is to have a model for each Django data type. """ import uuid from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from .base import BaseModel try: from PIL import Image # NOQA except ImportError: ImageData = None else: class ImageData(models.Model): data = models.ImageField(null=True) class BinaryData(models.Model): data = models.BinaryField(null=True) class BooleanData(models.Model): data = models.BooleanField(default=False, null=True) class CharData(models.Model): data = models.CharField(max_length=30, null=True) class DateData(models.Model): data = models.DateField(null=True) class DateTimeData(models.Model): data = models.DateTimeField(null=True) class DecimalData(models.Model): data = models.DecimalField(null=True, decimal_places=3, max_digits=5) class EmailData(models.Model): data = models.EmailField(null=True) class FileData(models.Model): data = models.FileField(null=True) class FilePathData(models.Model): data = models.FilePathField(null=True) class FloatData(models.Model): data = models.FloatField(null=True) class IntegerData(models.Model): data = models.IntegerField(null=True) class BigIntegerData(models.Model): data = models.BigIntegerField(null=True) class GenericIPAddressData(models.Model): data = models.GenericIPAddressField(null=True) class PositiveBigIntegerData(models.Model): data = models.PositiveBigIntegerField(null=True) class PositiveIntegerData(models.Model): data = models.PositiveIntegerField(null=True) class PositiveSmallIntegerData(models.Model): data = models.PositiveSmallIntegerField(null=True) class SlugData(models.Model): data = models.SlugField(null=True) class SmallData(models.Model): data = models.SmallIntegerField(null=True) class TextData(models.Model): data = models.TextField(null=True) class TimeData(models.Model): data = models.TimeField(null=True) class Tag(models.Model): """A tag on an item.""" data = models.SlugField() content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Meta: ordering = ["data"] class GenericData(models.Model): data = models.CharField(max_length=30) tags = GenericRelation(Tag) # The following test classes are all for validation # of related objects; in particular, forward, backward, # and self references. class Anchor(models.Model): """This is a model that can be used as something for other models to point at""" data = models.CharField(max_length=30) class Meta: ordering = ("id",) class UniqueAnchor(models.Model): """This is a model that can be used as something for other models to point at""" data = models.CharField(unique=True, max_length=30) class FKData(models.Model): data = models.ForeignKey(Anchor, models.SET_NULL, null=True) class M2MData(models.Model): data = models.ManyToManyField(Anchor) class O2OData(models.Model): # One to one field can't be null here, since it is a PK. data = models.OneToOneField(Anchor, models.CASCADE, primary_key=True) class FKSelfData(models.Model): data = models.ForeignKey("self", models.CASCADE, null=True) class M2MSelfData(models.Model): data = models.ManyToManyField("self", symmetrical=False) class FKDataToField(models.Model): data = models.ForeignKey(UniqueAnchor, models.SET_NULL, null=True, to_field="data") class FKDataToO2O(models.Model): data = models.ForeignKey(O2OData, models.SET_NULL, null=True) class M2MIntermediateData(models.Model): data = models.ManyToManyField(Anchor, through="Intermediate") class Intermediate(models.Model): left = models.ForeignKey(M2MIntermediateData, models.CASCADE) right = models.ForeignKey(Anchor, models.CASCADE) extra = models.CharField(max_length=30, blank=True, default="doesn't matter") # The following test classes are for validating the # deserialization of objects that use a user-defined # field as the primary key. # Some of these data types have been commented out # because they can't be used as a primary key on one # or all database backends. class BooleanPKData(models.Model): data = models.BooleanField(primary_key=True, default=False) class CharPKData(models.Model): data = models.CharField(max_length=30, primary_key=True) class DatePKData(models.Model): data = models.DateField(primary_key=True) class DateTimePKData(models.Model): data = models.DateTimeField(primary_key=True) class DecimalPKData(models.Model): data = models.DecimalField(primary_key=True, decimal_places=3, max_digits=5) class EmailPKData(models.Model): data = models.EmailField(primary_key=True) class FilePathPKData(models.Model): data = models.FilePathField(primary_key=True) class FloatPKData(models.Model): data = models.FloatField(primary_key=True) class IntegerPKData(models.Model): data = models.IntegerField(primary_key=True) class GenericIPAddressPKData(models.Model): data = models.GenericIPAddressField(primary_key=True) class PositiveIntegerPKData(models.Model): data = models.PositiveIntegerField(primary_key=True) class PositiveSmallIntegerPKData(models.Model): data = models.PositiveSmallIntegerField(primary_key=True) class SlugPKData(models.Model): data = models.SlugField(primary_key=True) class SmallPKData(models.Model): data = models.SmallIntegerField(primary_key=True) class TextPKData(models.Model): data = models.TextField(primary_key=True) class Meta: required_db_features = ["supports_index_on_text_field"] class TimePKData(models.Model): data = models.TimeField(primary_key=True) class UUIDData(models.Model): data = models.UUIDField(primary_key=True) class UUIDDefaultData(models.Model): data = models.UUIDField(primary_key=True, default=uuid.uuid4) class FKToUUID(models.Model): data = models.ForeignKey(UUIDData, models.CASCADE) # Tests for handling fields with pre_save functions, or # models with save functions that modify data class AutoNowDateTimeData(models.Model): data = models.DateTimeField(null=True, auto_now=True) class ModifyingSaveData(models.Model): data = models.IntegerField(null=True) def save(self, *args, **kwargs): """ A save method that modifies the data in the object. A user-defined save() method isn't called when objects are deserialized (#4459). """ self.data = 666 super().save(*args, **kwargs) # Tests for serialization of models using inheritance. # Regression for #7202, #7350 class AbstractBaseModel(models.Model): parent_data = models.IntegerField() class Meta: abstract = True class InheritAbstractModel(AbstractBaseModel): child_data = models.IntegerField() class InheritBaseModel(BaseModel): child_data = models.IntegerField() class ExplicitInheritBaseModel(BaseModel): parent = models.OneToOneField(BaseModel, models.CASCADE, parent_link=True) child_data = models.IntegerField() class LengthModel(models.Model): data = models.IntegerField() def __len__(self): return self.data
""" 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))
./temp_repos/django/tests/serializers/models/data.py
./temp_repos/django/tests/gis_tests/test_data.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'BinaryData'. Context: - Class Name: BinaryData - Dependencies to Mock: None detected - Key Imports: base, django.contrib.contenttypes.fields, django.db, django.contrib.contenttypes.models, uuid, PIL Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external dependencies listed above. 3. Test both success and failure scenarios. 4. Use the AAA (Arrange, Act, Assert) pattern.
BinaryData
python
from ctypes import c_void_p from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.libgdal import GDAL_VERSION from django.contrib.gis.gdal.prototypes import ds as capi from django.utils.encoding import force_bytes, force_str class Driver(GDALBase): """ Wrap a GDAL/OGR Data Source Driver. For more information, see the C API documentation: https://gdal.org/api/vector_c_api.html https://gdal.org/api/raster_c_api.html """ # Case-insensitive aliases for some GDAL/OGR Drivers. # For a complete list of original driver names see # https://gdal.org/drivers/vector/ # https://gdal.org/drivers/raster/ _alias = { # vector "esri": "ESRI Shapefile", "shp": "ESRI Shapefile", "shape": "ESRI Shapefile", # raster "tiff": "GTiff", "tif": "GTiff", "jpeg": "JPEG", "jpg": "JPEG", } if GDAL_VERSION[:2] <= (3, 10): _alias.update( { "tiger": "TIGER", "tiger/line": "TIGER", } ) def __init__(self, dr_input): """ Initialize an GDAL/OGR driver on either a string or integer input. """ if isinstance(dr_input, str): # If a string name of the driver was passed in self.ensure_registered() # Checking the alias dictionary (case-insensitive) to see if an # alias exists for the given driver. if dr_input.lower() in self._alias: name = self._alias[dr_input.lower()] else: name = dr_input # Attempting to get the GDAL/OGR driver by the string name. driver = c_void_p(capi.get_driver_by_name(force_bytes(name))) elif isinstance(dr_input, int): self.ensure_registered() driver = capi.get_driver(dr_input) elif isinstance(dr_input, c_void_p): driver = dr_input else: raise GDALException( "Unrecognized input type for GDAL/OGR Driver: %s" % type(dr_input) ) # Making sure we get a valid pointer to the OGR Driver if not driver: raise GDALException( "Could not initialize GDAL/OGR Driver on input: %s" % dr_input ) self.ptr = driver def __str__(self): return self.name @classmethod def ensure_registered(cls): """ Attempt to register all the data source drivers. """ # Only register all if the driver count is 0 (or else all drivers will # be registered over and over again). if not capi.get_driver_count(): capi.register_all() @classmethod def driver_count(cls): """ Return the number of GDAL/OGR data source drivers registered. """ return capi.get_driver_count() @property def name(self): """ Return description/name string for this driver. """ return force_str(capi.get_driver_description(self.ptr))
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)
./temp_repos/django/django/contrib/gis/gdal/driver.py
./temp_repos/django/tests/gis_tests/gdal_tests/test_driver.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Driver'. Context: - Class Name: Driver - Dependencies to Mock: dr_input - Key Imports: django.contrib.gis.gdal.libgdal, django.contrib.gis.gdal.prototypes, django.contrib.gis.gdal.error, django.utils.encoding, ctypes, django.contrib.gis.gdal.base Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external dependencies listed above. 3. Test both success and failure scenarios. 4. Use the AAA (Arrange, Act, Assert) pattern.
Driver
python
""" This module houses the ctypes function prototypes for GDAL DataSource (raster) related data structures. """ from ctypes import POINTER, c_bool, c_char_p, c_double, c_int, c_void_p from functools import partial from django.contrib.gis.gdal.libgdal import std_call from django.contrib.gis.gdal.prototypes.generation import ( chararray_output, const_string_output, double_output, int_output, void_output, voidptr_output, ) # For more detail about c function names and definitions see # https://gdal.org/api/raster_c_api.html # https://gdal.org/doxygen/gdalwarper_8h.html # https://gdal.org/api/gdal_utils.html # Prepare partial functions that use cpl error codes void_output = partial(void_output, cpl=True) const_string_output = partial(const_string_output, cpl=True) double_output = partial(double_output, cpl=True) # Raster Data Source Routines create_ds = voidptr_output( std_call("GDALCreate"), [c_void_p, c_char_p, c_int, c_int, c_int, c_int, c_void_p] ) open_ds = voidptr_output(std_call("GDALOpen"), [c_char_p, c_int]) close_ds = void_output(std_call("GDALClose"), [c_void_p], errcheck=False) flush_ds = int_output(std_call("GDALFlushCache"), [c_void_p]) copy_ds = voidptr_output( std_call("GDALCreateCopy"), [c_void_p, c_char_p, c_void_p, c_int, POINTER(c_char_p), c_void_p, c_void_p], ) add_band_ds = void_output(std_call("GDALAddBand"), [c_void_p, c_int]) get_ds_description = const_string_output(std_call("GDALGetDescription"), [c_void_p]) get_ds_driver = voidptr_output(std_call("GDALGetDatasetDriver"), [c_void_p]) get_ds_info = const_string_output(std_call("GDALInfo"), [c_void_p, c_void_p]) get_ds_xsize = int_output(std_call("GDALGetRasterXSize"), [c_void_p]) get_ds_ysize = int_output(std_call("GDALGetRasterYSize"), [c_void_p]) get_ds_raster_count = int_output(std_call("GDALGetRasterCount"), [c_void_p]) get_ds_raster_band = voidptr_output(std_call("GDALGetRasterBand"), [c_void_p, c_int]) get_ds_projection_ref = const_string_output( std_call("GDALGetProjectionRef"), [c_void_p] ) set_ds_projection_ref = void_output(std_call("GDALSetProjection"), [c_void_p, c_char_p]) get_ds_geotransform = void_output( std_call("GDALGetGeoTransform"), [c_void_p, POINTER(c_double * 6)], errcheck=False ) set_ds_geotransform = void_output( std_call("GDALSetGeoTransform"), [c_void_p, POINTER(c_double * 6)] ) get_ds_metadata = chararray_output( std_call("GDALGetMetadata"), [c_void_p, c_char_p], errcheck=False ) set_ds_metadata = void_output( std_call("GDALSetMetadata"), [c_void_p, POINTER(c_char_p), c_char_p] ) get_ds_metadata_domain_list = chararray_output( std_call("GDALGetMetadataDomainList"), [c_void_p], errcheck=False ) get_ds_metadata_item = const_string_output( std_call("GDALGetMetadataItem"), [c_void_p, c_char_p, c_char_p] ) set_ds_metadata_item = const_string_output( std_call("GDALSetMetadataItem"), [c_void_p, c_char_p, c_char_p, c_char_p] ) free_dsl = void_output(std_call("CSLDestroy"), [POINTER(c_char_p)], errcheck=False) # Raster Band Routines band_io = void_output( std_call("GDALRasterIO"), [ c_void_p, c_int, c_int, c_int, c_int, c_int, c_void_p, c_int, c_int, c_int, c_int, c_int, ], ) get_band_xsize = int_output(std_call("GDALGetRasterBandXSize"), [c_void_p]) get_band_ysize = int_output(std_call("GDALGetRasterBandYSize"), [c_void_p]) get_band_index = int_output(std_call("GDALGetBandNumber"), [c_void_p]) get_band_description = const_string_output(std_call("GDALGetDescription"), [c_void_p]) get_band_ds = voidptr_output(std_call("GDALGetBandDataset"), [c_void_p]) get_band_datatype = int_output(std_call("GDALGetRasterDataType"), [c_void_p]) get_band_color_interp = int_output( std_call("GDALGetRasterColorInterpretation"), [c_void_p] ) get_band_nodata_value = double_output( std_call("GDALGetRasterNoDataValue"), [c_void_p, POINTER(c_int)] ) set_band_nodata_value = void_output( std_call("GDALSetRasterNoDataValue"), [c_void_p, c_double] ) delete_band_nodata_value = void_output( std_call("GDALDeleteRasterNoDataValue"), [c_void_p] ) get_band_statistics = void_output( std_call("GDALGetRasterStatistics"), [ c_void_p, c_int, c_int, POINTER(c_double), POINTER(c_double), POINTER(c_double), POINTER(c_double), c_void_p, c_void_p, ], ) compute_band_statistics = void_output( std_call("GDALComputeRasterStatistics"), [ c_void_p, c_int, POINTER(c_double), POINTER(c_double), POINTER(c_double), POINTER(c_double), c_void_p, c_void_p, ], ) # Reprojection routine reproject_image = void_output( std_call("GDALReprojectImage"), [ c_void_p, c_char_p, c_void_p, c_char_p, c_int, c_double, c_double, c_void_p, c_void_p, c_void_p, ], ) auto_create_warped_vrt = voidptr_output( std_call("GDALAutoCreateWarpedVRT"), [c_void_p, c_char_p, c_char_p, c_int, c_double, c_void_p], ) # Create VSI gdal raster files from in-memory buffers. # https://gdal.org/api/cpl.html#cpl-vsi-h create_vsi_file_from_mem_buffer = voidptr_output( std_call("VSIFileFromMemBuffer"), [c_char_p, c_void_p, c_int, c_int] ) get_mem_buffer_from_vsi_file = voidptr_output( std_call("VSIGetMemFileBuffer"), [c_char_p, POINTER(c_int), c_bool] ) unlink_vsi_file = int_output(std_call("VSIUnlink"), [c_char_p])
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) bandmemjson = rsmemjson.bands[0] if numpy: numpy.testing.assert_equal( bandmemjson.data(), numpy.array(range(25)).reshape(5, 5) ) else: self.assertEqual(bandmemjson.data(), list(range(25))) def test_band_statistics_automatic_refresh(self): rsmem = GDALRaster( { "srid": 4326, "width": 2, "height": 2, "bands": [{"data": [0] * 4, "nodata_value": 99}], } ) band = rsmem.bands[0] # Populate statistics cache self.assertEqual(band.statistics(), (0, 0, 0, 0)) # Change data band.data([1, 1, 0, 0]) # Statistics are properly updated self.assertEqual(band.statistics(), (0.0, 1.0, 0.5, 0.5)) # Change nodata_value band.nodata_value = 0 # Statistics are properly updated self.assertEqual(band.statistics(), (1.0, 1.0, 1.0, 0.0)) def test_band_statistics_empty_band(self): rsmem = GDALRaster( { "srid": 4326, "width": 1, "height": 1, "bands": [{"data": [0], "nodata_value": 0}], } ) self.assertEqual(rsmem.bands[0].statistics(), (None, None, None, None)) def test_band_delete_nodata(self): rsmem = GDALRaster( { "srid": 4326, "width": 1, "height": 1, "bands": [{"data": [0], "nodata_value": 1}], } ) rsmem.bands[0].nodata_value = None self.assertIsNone(rsmem.bands[0].nodata_value) def test_band_data_replication(self): band = GDALRaster( { "srid": 4326, "width": 3, "height": 3, "bands": [{"data": range(10, 19), "nodata_value": 0}], } ).bands[0] # Variations for input (data, shape, expected result). combos = ( ([1], (1, 1), [1] * 9), (range(3), (1, 3), [0, 0, 0, 1, 1, 1, 2, 2, 2]), (range(3), (3, 1), [0, 1, 2, 0, 1, 2, 0, 1, 2]), ) for combo in combos: band.data(combo[0], shape=combo[1]) if numpy: numpy.testing.assert_equal( band.data(), numpy.array(combo[2]).reshape(3, 3) ) else: self.assertEqual(band.data(), list(combo[2]))
./temp_repos/django/django/contrib/gis/gdal/prototypes/raster.py
./temp_repos/django/tests/gis_tests/gdal_tests/test_raster.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.contrib.gis.gdal.libgdal, django.contrib.gis.gdal.prototypes.generation, functools, ctypes Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external dependencies listed above. 3. Test both success and failure scenarios. 4. Use the AAA (Arrange, Act, Assert) pattern.
Unknown
python
""" Creates the default Site object. """ from django.apps import apps as global_apps from django.conf import settings from django.core.management.color import no_style from django.db import DEFAULT_DB_ALIAS, connections, router def create_default_site( app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, apps=global_apps, **kwargs, ): try: Site = apps.get_model("sites", "Site") except LookupError: return if not router.allow_migrate_model(using, Site): return if not Site.objects.using(using).exists(): # The default settings set SITE_ID = 1, and some tests in Django's test # suite rely on this value. However, if database sequences are reused # (e.g. in the test suite after flush/syncdb), it isn't guaranteed that # the next id will be 1, so we coerce it. See #15573 and #16353. This # can also crop up outside of tests - see #15346. if verbosity >= 2: print("Creating example.com Site object") Site( pk=getattr(settings, "SITE_ID", 1), domain="example.com", name="example.com" ).save(using=using) # We set an explicit pk instead of relying on auto-incrementation, # so we need to reset the database sequence. See #17415. sequence_sql = connections[using].ops.sequence_reset_sql(no_style(), [Site]) if sequence_sql: if verbosity >= 2: print("Resetting sequence") with connections[using].cursor() as cursor: for command in sequence_sql: cursor.execute(command)
import datetime import os import shutil import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from admin_scripts.tests import AdminScriptTestCase from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles import storage from django.contrib.staticfiles.management.commands import collectstatic, runserver from django.core.exceptions import ImproperlyConfigured from django.core.management import CommandError, call_command from django.core.management.base import SystemCheckError from django.test import RequestFactory, override_settings from django.test.utils import extend_sys_path from django.utils._os import symlinks_supported from django.utils.functional import empty from .cases import CollectionTestCase, StaticFilesTestCase, TestDefaults from .settings import TEST_ROOT, TEST_SETTINGS from .storage import DummyStorage class TestNoFilesCreated: def test_no_files_created(self): """ Make sure no files were create in the destination directory. """ self.assertEqual(os.listdir(settings.STATIC_ROOT), []) class TestRunserver(StaticFilesTestCase): @override_settings(MIDDLEWARE=["django.middleware.common.CommonMiddleware"]) def test_middleware_loaded_only_once(self): command = runserver.Command() with mock.patch("django.middleware.common.CommonMiddleware") as mocked: command.get_handler(use_static_handler=True, insecure_serving=True) self.assertEqual(mocked.call_count, 1) def test_404_response(self): command = runserver.Command() handler = command.get_handler(use_static_handler=True, insecure_serving=True) missing_static_file = os.path.join(settings.STATIC_URL, "unknown.css") req = RequestFactory().get(missing_static_file) with override_settings(DEBUG=False): response = handler.get_response(req) self.assertEqual(response.status_code, 404) with override_settings(DEBUG=True): response = handler.get_response(req) self.assertEqual(response.status_code, 404) class TestFindStatic(TestDefaults, CollectionTestCase): """ Test ``findstatic`` management command. """ def _get_file(self, filepath): path = call_command( "findstatic", filepath, all=False, verbosity=0, stdout=StringIO() ) with open(path, encoding="utf-8") as f: return f.read() def test_all_files(self): """ findstatic returns all candidate files if run without --first and -v1. """ result = call_command( "findstatic", "test/file.txt", verbosity=1, stdout=StringIO() ) lines = [line.strip() for line in result.split("\n")] self.assertEqual( len(lines), 3 ) # three because there is also the "Found <file> here" line self.assertIn("project", lines[1]) self.assertIn("apps", lines[2]) def test_all_files_less_verbose(self): """ findstatic returns all candidate files if run without --first and -v0. """ result = call_command( "findstatic", "test/file.txt", verbosity=0, stdout=StringIO() ) lines = [line.strip() for line in result.split("\n")] self.assertEqual(len(lines), 2) self.assertIn("project", lines[0]) self.assertIn("apps", lines[1]) def test_all_files_more_verbose(self): """ findstatic returns all candidate files if run without --first and -v2. Also, test that findstatic returns the searched locations with -v2. """ result = call_command( "findstatic", "test/file.txt", verbosity=2, stdout=StringIO() ) lines = [line.strip() for line in result.split("\n")] self.assertIn("project", lines[1]) self.assertIn("apps", lines[2]) self.assertIn("Looking in the following locations:", lines[3]) searched_locations = ", ".join(lines[4:]) # AppDirectoriesFinder searched locations self.assertIn( os.path.join("staticfiles_tests", "apps", "test", "static"), searched_locations, ) self.assertIn( os.path.join("staticfiles_tests", "apps", "no_label", "static"), searched_locations, ) # FileSystemFinder searched locations self.assertIn(TEST_SETTINGS["STATICFILES_DIRS"][1][1], searched_locations) self.assertIn(TEST_SETTINGS["STATICFILES_DIRS"][0], searched_locations) self.assertIn(str(TEST_SETTINGS["STATICFILES_DIRS"][2]), searched_locations) # DefaultStorageFinder searched locations self.assertIn( os.path.join("staticfiles_tests", "project", "site_media", "media"), searched_locations, ) def test_missing_args_message(self): msg = "Enter at least one staticfile." with self.assertRaisesMessage(CommandError, msg): call_command("findstatic") class TestConfiguration(StaticFilesTestCase): def test_location_empty(self): msg = "without having set the STATIC_ROOT setting to a filesystem path" err = StringIO() for root in ["", None]: with override_settings(STATIC_ROOT=root): with self.assertRaisesMessage(ImproperlyConfigured, msg): call_command( "collectstatic", interactive=False, verbosity=0, stderr=err ) def test_local_storage_detection_helper(self): staticfiles_storage = storage.staticfiles_storage try: storage.staticfiles_storage._wrapped = empty with self.settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": ( "django.contrib.staticfiles.storage.StaticFilesStorage" ) }, } ): command = collectstatic.Command() self.assertTrue(command.is_local_storage()) storage.staticfiles_storage._wrapped = empty with self.settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.DummyStorage" }, } ): command = collectstatic.Command() self.assertFalse(command.is_local_storage()) collectstatic.staticfiles_storage = storage.FileSystemStorage() command = collectstatic.Command() self.assertTrue(command.is_local_storage()) collectstatic.staticfiles_storage = DummyStorage() command = collectstatic.Command() self.assertFalse(command.is_local_storage()) finally: staticfiles_storage._wrapped = empty collectstatic.staticfiles_storage = staticfiles_storage storage.staticfiles_storage = staticfiles_storage @override_settings(STATICFILES_DIRS=("test")) def test_collectstatis_check(self): msg = "The STATICFILES_DIRS setting is not a tuple or list." with self.assertRaisesMessage(SystemCheckError, msg): call_command("collectstatic", skip_checks=False) class TestCollectionHelpSubcommand(AdminScriptTestCase): @override_settings(STATIC_ROOT=None) def test_missing_settings_dont_prevent_help(self): """ Even if the STATIC_ROOT setting is not set, one can still call the `manage.py help collectstatic` command. """ self.write_settings("settings.py", apps=["django.contrib.staticfiles"]) out, err = self.run_manage(["help", "collectstatic"]) self.assertNoOutput(err) class TestCollection(TestDefaults, CollectionTestCase): """ Test ``collectstatic`` management command. """ def test_ignore(self): """ -i patterns are ignored. """ self.assertFileNotFound("test/test.ignoreme") def test_common_ignore_patterns(self): """ Common ignore patterns (*~, .*, CVS) are ignored. """ self.assertFileNotFound("test/.hidden") self.assertFileNotFound("test/backup~") self.assertFileNotFound("test/CVS") def test_pathlib(self): self.assertFileContains("pathlib.txt", "pathlib") class TestCollectionPathLib(TestCollection): def mkdtemp(self): tmp_dir = super().mkdtemp() return Path(tmp_dir) class TestCollectionVerbosity(CollectionTestCase): copying_msg = "Copying " run_collectstatic_in_setUp = False post_process_msg = "Post-processed" staticfiles_copied_msg = "static files copied to" def test_verbosity_0(self): stdout = StringIO() self.run_collectstatic(verbosity=0, stdout=stdout) self.assertEqual(stdout.getvalue(), "") def test_verbosity_1(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout) output = stdout.getvalue() self.assertIn(self.staticfiles_copied_msg, output) self.assertNotIn(self.copying_msg, output) def test_verbosity_2(self): stdout = StringIO() self.run_collectstatic(verbosity=2, stdout=stdout) output = stdout.getvalue() self.assertIn(self.staticfiles_copied_msg, output) self.assertIn(self.copying_msg, output) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": ( "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" ) }, } ) def test_verbosity_1_with_post_process(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout, post_process=True) self.assertNotIn(self.post_process_msg, stdout.getvalue()) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": ( "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" ) }, } ) def test_verbosity_2_with_post_process(self): stdout = StringIO() self.run_collectstatic(verbosity=2, stdout=stdout, post_process=True) self.assertIn(self.post_process_msg, stdout.getvalue()) class TestCollectionClear(CollectionTestCase): """ Test the ``--clear`` option of the ``collectstatic`` management command. """ run_collectstatic_in_setUp = False def run_collectstatic(self, **kwargs): clear_filepath = os.path.join(settings.STATIC_ROOT, "cleared.txt") with open(clear_filepath, "w") as f: f.write("should be cleared") super().run_collectstatic(clear=True, **kwargs) def test_cleared_not_found(self): self.assertFileNotFound("cleared.txt") def test_dir_not_exists(self, **kwargs): shutil.rmtree(settings.STATIC_ROOT) super().run_collectstatic(clear=True) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.PathNotImplementedStorage" }, } ) def test_handle_path_notimplemented(self): self.run_collectstatic() self.assertFileNotFound("cleared.txt") def test_verbosity_0(self): for kwargs in [{}, {"dry_run": True}]: with self.subTest(kwargs=kwargs): stdout = StringIO() self.run_collectstatic(verbosity=0, stdout=stdout, **kwargs) self.assertEqual(stdout.getvalue(), "") def test_verbosity_1(self): for deletion_message, kwargs in [ ("Deleting", {}), ("Pretending to delete", {"dry_run": True}), ]: with self.subTest(kwargs=kwargs): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout, **kwargs) output = stdout.getvalue() self.assertIn("static file", output) self.assertIn("deleted", output) self.assertNotIn(deletion_message, output) def test_verbosity_2(self): for deletion_message, kwargs in [ ("Deleting", {}), ("Pretending to delete", {"dry_run": True}), ]: with self.subTest(kwargs=kwargs): stdout = StringIO() self.run_collectstatic(verbosity=2, stdout=stdout, **kwargs) output = stdout.getvalue() self.assertIn("static file", output) self.assertIn("deleted", output) self.assertIn(deletion_message, output) class TestInteractiveMessages(CollectionTestCase): overwrite_warning_msg = "This will overwrite existing files!" delete_warning_msg = "This will DELETE ALL FILES in this location!" files_copied_msg = "static files copied" @staticmethod def mock_input(stdout): def _input(msg): stdout.write(msg) return "yes" return _input def test_warning_when_clearing_staticdir(self): stdout = StringIO() self.run_collectstatic() with mock.patch("builtins.input", side_effect=self.mock_input(stdout)): call_command("collectstatic", interactive=True, clear=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertIn(self.delete_warning_msg, output) def test_warning_when_overwriting_files_in_staticdir(self): stdout = StringIO() self.run_collectstatic() with mock.patch("builtins.input", side_effect=self.mock_input(stdout)): call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) def test_no_warning_when_staticdir_does_not_exist(self): stdout = StringIO() shutil.rmtree(settings.STATIC_ROOT) call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) self.assertIn(self.files_copied_msg, output) def test_no_warning_for_empty_staticdir(self): stdout = StringIO() with tempfile.TemporaryDirectory( prefix="collectstatic_empty_staticdir_test" ) as static_dir: with override_settings(STATIC_ROOT=static_dir): call_command("collectstatic", interactive=True, stdout=stdout) output = stdout.getvalue() self.assertNotIn(self.overwrite_warning_msg, output) self.assertNotIn(self.delete_warning_msg, output) self.assertIn(self.files_copied_msg, output) def test_cancelled(self): self.run_collectstatic() with mock.patch("builtins.input", side_effect=lambda _: "no"): with self.assertRaisesMessage( CommandError, "Collecting static files cancelled" ): call_command("collectstatic", interactive=True) class TestCollectionNoDefaultIgnore(TestDefaults, CollectionTestCase): """ The ``--no-default-ignore`` option of the ``collectstatic`` management command. """ def run_collectstatic(self): super().run_collectstatic(use_default_ignore_patterns=False) def test_no_common_ignore_patterns(self): """ With --no-default-ignore, common ignore patterns (*~, .*, CVS) are not ignored. """ self.assertFileContains("test/.hidden", "should be ignored") self.assertFileContains("test/backup~", "should be ignored") self.assertFileContains("test/CVS", "should be ignored") @override_settings( INSTALLED_APPS=[ "staticfiles_tests.apps.staticfiles_config.IgnorePatternsAppConfig", "staticfiles_tests.apps.test", ] ) class TestCollectionCustomIgnorePatterns(CollectionTestCase): def test_custom_ignore_patterns(self): """ A custom ignore_patterns list, ['*.css', '*/vendor/*.js'] in this case, can be specified in an AppConfig definition. """ self.assertFileNotFound("test/nonascii.css") self.assertFileContains("test/.hidden", "should be ignored") self.assertFileNotFound(os.path.join("test", "vendor", "module.js")) class TestCollectionDryRun(TestNoFilesCreated, CollectionTestCase): """ Test ``--dry-run`` option for ``collectstatic`` management command. """ def run_collectstatic(self): super().run_collectstatic(dry_run=True) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" }, } ) class TestCollectionDryRunManifestStaticFilesStorage(TestCollectionDryRun): pass class TestCollectionFilesOverride(CollectionTestCase): """ Test overriding duplicated files by ``collectstatic`` management command. Check for proper handling of apps order in installed apps even if file modification dates are in different order: 'staticfiles_test_app', 'staticfiles_tests.apps.no_label', """ def setUp(self): self.temp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.temp_dir) # get modification and access times for no_label/static/file2.txt self.orig_path = os.path.join( TEST_ROOT, "apps", "no_label", "static", "file2.txt" ) self.orig_mtime = os.path.getmtime(self.orig_path) self.orig_atime = os.path.getatime(self.orig_path) # prepare duplicate of file2.txt from a temporary app # this file will have modification time older than # no_label/static/file2.txt anyway it should be taken to STATIC_ROOT # because the temporary app is before 'no_label' app in installed apps self.temp_app_path = os.path.join(self.temp_dir, "staticfiles_test_app") self.testfile_path = os.path.join(self.temp_app_path, "static", "file2.txt") os.makedirs(self.temp_app_path) with open(os.path.join(self.temp_app_path, "__init__.py"), "w+"): pass os.makedirs(os.path.dirname(self.testfile_path)) with open(self.testfile_path, "w+") as f: f.write("duplicate of file2.txt") os.utime(self.testfile_path, (self.orig_atime - 1, self.orig_mtime - 1)) settings_with_test_app = self.modify_settings( INSTALLED_APPS={"prepend": "staticfiles_test_app"}, ) with extend_sys_path(self.temp_dir): settings_with_test_app.enable() self.addCleanup(settings_with_test_app.disable) super().setUp() def test_ordering_override(self): """ Test if collectstatic takes files in proper order """ self.assertFileContains("file2.txt", "duplicate of file2.txt") # run collectstatic again self.run_collectstatic() self.assertFileContains("file2.txt", "duplicate of file2.txt") # The collectstatic test suite already has conflicting files since both # project/test/file.txt and apps/test/static/test/file.txt are collected. To # properly test for the warning not happening unless we tell it to explicitly, # we remove the project directory and will add back a conflicting file later. @override_settings(STATICFILES_DIRS=[]) class TestCollectionOverwriteWarning(CollectionTestCase): """ Test warning in ``collectstatic`` output when a file is skipped because a previous file was already written to the same path. """ # If this string is in the collectstatic output, it means the warning we're # looking for was emitted. warning_string = "Found another file" def _collectstatic_output(self, verbosity=3, **kwargs): """ Run collectstatic, and capture and return the output. """ out = StringIO() call_command( "collectstatic", interactive=False, verbosity=verbosity, stdout=out, **kwargs, ) return out.getvalue() def test_no_warning(self): """ There isn't a warning if there isn't a duplicate destination. """ output = self._collectstatic_output(clear=True) self.assertNotIn(self.warning_string, output) def test_warning_at_verbosity_2(self): """ There is a warning when there are duplicate destinations at verbosity 2+. """ with tempfile.TemporaryDirectory() as static_dir: duplicate = os.path.join(static_dir, "test", "file.txt") os.mkdir(os.path.dirname(duplicate)) with open(duplicate, "w+") as f: f.write("duplicate of file.txt") with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True, verbosity=2) self.assertIn(self.warning_string, output) def test_no_warning_at_verbosity_1(self): """ There is no individual warning at verbosity 1, but summary is shown. """ with tempfile.TemporaryDirectory() as static_dir: duplicate = os.path.join(static_dir, "test", "file.txt") os.mkdir(os.path.dirname(duplicate)) with open(duplicate, "w+") as f: f.write("duplicate of file.txt") with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True, verbosity=1) self.assertNotIn(self.warning_string, output) self.assertIn("1 skipped due to conflict", output) def test_summary_multiple_conflicts(self): """ Summary shows correct count for multiple conflicts. """ with tempfile.TemporaryDirectory() as static_dir: duplicate1 = os.path.join(static_dir, "test", "file.txt") os.makedirs(os.path.dirname(duplicate1)) with open(duplicate1, "w+") as f: f.write("duplicate of file.txt") duplicate2 = os.path.join(static_dir, "test", "file1.txt") with open(duplicate2, "w+") as f: f.write("duplicate of file1.txt") duplicate3 = os.path.join(static_dir, "test", "nonascii.css") shutil.copy2(duplicate1, duplicate3) with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True, verbosity=1) self.assertIn("3 skipped due to conflict", output) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.DummyStorage" }, } ) class TestCollectionNonLocalStorage(TestNoFilesCreated, CollectionTestCase): """ Tests for a Storage that implements get_modified_time() but not path() (#15035). """ def test_storage_properties(self): # Properties of the Storage as described in the ticket. storage = DummyStorage() self.assertEqual( storage.get_modified_time("name"), datetime.datetime(1970, 1, 1, tzinfo=datetime.UTC), ) with self.assertRaisesMessage( NotImplementedError, "This backend doesn't support absolute paths." ): storage.path("name") class TestCollectionNeverCopyStorage(CollectionTestCase): @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NeverCopyRemoteStorage" }, } ) def test_skips_newer_files_in_remote_storage(self): """ collectstatic skips newer files in a remote storage. run_collectstatic() in setUp() copies the static files, then files are always skipped after NeverCopyRemoteStorage is activated since NeverCopyRemoteStorage.get_modified_time() returns a datetime in the future to simulate an unmodified file. """ stdout = StringIO() self.run_collectstatic(stdout=stdout, verbosity=2) output = stdout.getvalue() self.assertIn("Skipping 'test.txt' (not modified)", output) @unittest.skipUnless(symlinks_supported(), "Must be able to symlink to run this test.") class TestCollectionLinks(TestDefaults, CollectionTestCase): """ Test ``--link`` option for ``collectstatic`` management command. Note that by inheriting ``TestDefaults`` we repeat all the standard file resolving tests here, to make sure using ``--link`` does not change the file-selection semantics. """ def run_collectstatic(self, clear=False, link=True, **kwargs): super().run_collectstatic(link=link, clear=clear, **kwargs) def test_links_created(self): """ With ``--link``, symbolic links are created. """ self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, "test.txt"))) def test_broken_symlink(self): """ Test broken symlink gets deleted. """ path = os.path.join(settings.STATIC_ROOT, "test.txt") os.unlink(path) self.run_collectstatic() self.assertTrue(os.path.islink(path)) def test_symlinks_and_files_replaced(self): """ Running collectstatic in non-symlink mode replaces symlinks with files, while symlink mode replaces files with symlinks. """ path = os.path.join(settings.STATIC_ROOT, "test.txt") self.assertTrue(os.path.islink(path)) self.run_collectstatic(link=False) self.assertFalse(os.path.islink(path)) self.run_collectstatic(link=True) self.assertTrue(os.path.islink(path)) def test_clear_broken_symlink(self): """ With ``--clear``, broken symbolic links are deleted. """ nonexistent_file_path = os.path.join(settings.STATIC_ROOT, "nonexistent.txt") broken_symlink_path = os.path.join(settings.STATIC_ROOT, "symlink.txt") os.symlink(nonexistent_file_path, broken_symlink_path) self.run_collectstatic(clear=True) self.assertFalse(os.path.lexists(broken_symlink_path)) @override_settings( STORAGES={ **settings.STORAGES, STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.PathNotImplementedStorage" }, } ) def test_no_remote_link(self): with self.assertRaisesMessage( CommandError, "Can't symlink to a remote destination." ): self.run_collectstatic()
./temp_repos/django/django/contrib/sites/management.py
./temp_repos/django/tests/staticfiles_tests/test_management.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.db, django.conf, django.apps, django.core.management.color Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external dependencies listed above. 3. Test both success and failure scenarios. 4. Use the AAA (Arrange, Act, Assert) pattern.
Unknown
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
31