Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
giswqs
GitHub Repository: giswqs/geemap
Path: blob/master/tests/test_coreutils.py
2313 views
1
#!/usr/bin/env python
2
"""Tests for `coreutils` module."""
3
4
import json
5
import os
6
import string
7
import sys
8
import tempfile
9
from typing import Any
10
import unittest
11
from unittest import mock
12
import uuid
13
14
import ee
15
16
from geemap import coreutils
17
from tests import fake_ee
18
19
20
class FakeSecretNotFoundError(Exception):
21
"""google.colab.userdata.SecretNotFoundError fake."""
22
23
24
class FakeNotebookAccessError(Exception):
25
"""google.colab.userdata.NotebookAccessError fake."""
26
27
28
def _read_json_file(path: str) -> dict[str, Any]:
29
script_dir = os.path.dirname(os.path.abspath(__file__))
30
file_path = os.path.join(script_dir, f"data/{path}")
31
with open(file_path, encoding="utf-8") as f:
32
return json.load(f)
33
34
35
@mock.patch.object(ee, "Feature", fake_ee.Feature)
36
@mock.patch.object(ee, "Image", fake_ee.Image)
37
@mock.patch.object(ee, "ImageCollection", fake_ee.ImageCollection)
38
class TestCoreUtils(unittest.TestCase):
39
"""Tests for core utilss."""
40
41
def test_get_environment_invalid_key(self):
42
"""Verifies None is returned if keys are invalid."""
43
self.assertIsNone(coreutils.get_env_var(None))
44
self.assertIsNone(coreutils.get_env_var(""))
45
46
@mock.patch.dict(os.environ, {"key": "value"})
47
def test_get_env_var_unknown_key(self):
48
"""Verifies None is returned if the environment variable could not be found."""
49
self.assertIsNone(coreutils.get_env_var("unknown-key"))
50
51
@mock.patch.dict(os.environ, {"key": "value"})
52
def test_get_env_var_from_env(self):
53
"""Verifies environment variables are read from environment variables."""
54
self.assertEqual(coreutils.get_env_var("key"), "value")
55
56
@mock.patch.dict("sys.modules", {"google.colab": mock.Mock()})
57
def test_get_env_var_from_colab(self):
58
"""Verifies environment variables are read from Colab secrets."""
59
mock_colab = sys.modules["google.colab"]
60
mock_colab.userdata.get.return_value = "colab-value"
61
62
self.assertEqual(coreutils.get_env_var("key"), "colab-value")
63
mock_colab.userdata.get.assert_called_once_with("key")
64
65
@mock.patch.dict(os.environ, {"key": "environ-value"})
66
@mock.patch.dict("sys.modules", {"google.colab": mock.Mock()})
67
def test_get_env_var_colab_fails_fallback_to_env(self):
68
"""Verifies environment variables are read if a Colab secret read fails."""
69
mock_colab = sys.modules["google.colab"]
70
mock_colab.userdata.SecretNotFoundError = FakeSecretNotFoundError
71
mock_colab.userdata.NotebookAccessError = FakeNotebookAccessError
72
mock_colab.userdata.get.side_effect = FakeNotebookAccessError()
73
74
self.assertEqual(coreutils.get_env_var("key"), "environ-value")
75
76
def test_build_computed_object_tree_feature(self):
77
"""Tests building a JSON computed object tree for a Feature."""
78
tree = coreutils.build_computed_object_tree(ee.Feature({}))
79
expected = _read_json_file("feature_tree.json")
80
self.assertEqual(tree, expected)
81
82
def test_build_computed_object_tree_image(self):
83
"""Tests building a JSON computed object tree for an Image."""
84
tree = coreutils.build_computed_object_tree(ee.Image(0))
85
expected = _read_json_file("image_tree.json")
86
self.assertEqual(tree, expected)
87
88
def test_build_computed_object_tree_image_collection(self):
89
"""Tests building a JSON computed object tree for an ImageCollection."""
90
tree = coreutils.build_computed_object_tree(ee.ImageCollection([ee.Image(0)]))
91
expected = _read_json_file("image_collection_tree.json")
92
self.assertEqual(tree, expected)
93
94
95
class TestHelpers(unittest.TestCase):
96
97
def test_hex_to_rgb(self):
98
"""Tests hex_to_rgb."""
99
self.assertEqual(coreutils.hex_to_rgb(), (255, 255, 255))
100
self.assertEqual(coreutils.hex_to_rgb("FFFFFF"), (255, 255, 255))
101
self.assertEqual(coreutils.hex_to_rgb("#FFFFFF"), (255, 255, 255))
102
self.assertEqual(coreutils.hex_to_rgb("000000"), (0, 0, 0))
103
self.assertEqual(coreutils.hex_to_rgb("ff0000"), (255, 0, 0))
104
self.assertEqual(coreutils.hex_to_rgb("00ff00"), (0, 255, 0))
105
self.assertEqual(coreutils.hex_to_rgb("0000ff"), (0, 0, 255))
106
self.assertEqual(coreutils.hex_to_rgb("FFF"), (15, 15, 15))
107
self.assertEqual(coreutils.hex_to_rgb("#ABC"), (10, 11, 12))
108
self.assertEqual(coreutils.hex_to_rgb("000"), (0, 0, 0))
109
with self.assertRaises(ValueError):
110
coreutils.hex_to_rgb("garbage")
111
112
def test_random_string(self):
113
"""Tests random_string."""
114
s = coreutils.random_string()
115
self.assertEqual(len(s), 3)
116
self.assertTrue(all(c in string.ascii_lowercase for c in s))
117
118
s = coreutils.random_string(10)
119
self.assertEqual(len(s), 10)
120
self.assertTrue(all(c in string.ascii_lowercase for c in s))
121
122
def test_github_raw_url(self):
123
url = "https://github.com/opengeos/geemap/blob/master/geemap/geemap.py"
124
expected = (
125
"https://raw.githubusercontent.com/opengeos/geemap/master/geemap/geemap.py"
126
)
127
self.assertEqual(coreutils.github_raw_url(url), expected)
128
129
url = "https://example.com/file.txt"
130
self.assertEqual(coreutils.github_raw_url(url), url)
131
132
url = "https://github.com/opengeos/geemap"
133
self.assertEqual(coreutils.github_raw_url(url), url)
134
135
url = 123
136
self.assertEqual(
137
coreutils.github_raw_url(url), url
138
) # pytype: disable=wrong-arg-types
139
140
def test_temp_file_path(self):
141
"""Tests temp_file_path."""
142
path = coreutils.temp_file_path("txt")
143
self.assertIsInstance(path, str)
144
self.assertTrue(path.startswith(tempfile.gettempdir()))
145
self.assertTrue(path.endswith(".txt"))
146
filename = os.path.basename(path)
147
file_id, _ = os.path.splitext(filename)
148
try:
149
uuid.UUID(file_id, version=4)
150
except ValueError:
151
self.fail("file id is not a valid UUID4")
152
153
path2 = coreutils.temp_file_path(".geojson")
154
self.assertTrue(path2.endswith(".geojson"))
155
filename2 = os.path.basename(path2)
156
file_id2, _ = os.path.splitext(filename2)
157
try:
158
uuid.UUID(file_id2, version=4)
159
except ValueError:
160
self.fail("file id is not a valid UUID4")
161
162
163
if __name__ == "__main__":
164
unittest.main()
165
166