edq-utils 0.0.1__py3-none-any.whl → 0.0.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of edq-utils might be problematic. Click here for more details.
- edq/__init__.py +5 -1
- edq/py.typed +0 -0
- edq/testing/__init__.py +3 -0
- edq/testing/run.py +112 -0
- edq/testing/unittest.py +54 -0
- edq/util/__init__.py +3 -0
- edq/util/dirent.py +228 -44
- edq/util/dirent_test.py +823 -25
- edq/util/json.py +163 -0
- edq/util/json_test.py +228 -0
- edq/util/pyimport.py +73 -0
- edq/util/pyimport_test.py +83 -0
- edq/util/reflection.py +32 -0
- edq/util/testdata/dirent-operations/symlink_file_empty +0 -0
- edq/util/time.py +75 -0
- edq/util/time_test.py +107 -0
- {edq_utils-0.0.1.dist-info → edq_utils-0.0.3.dist-info}/METADATA +3 -1
- edq_utils-0.0.3.dist-info/RECORD +28 -0
- edq_utils-0.0.1.dist-info/RECORD +0 -16
- /edq/util/testdata/dirent-operations/{symlinklink_a.txt → symlink_a.txt} +0 -0
- /edq/util/testdata/dirent-operations/{symlinklink_dir_1 → symlink_dir_1}/b.txt +0 -0
- /edq/util/testdata/dirent-operations/{symlinklink_dir_1 → symlink_dir_1}/dir_2/c.txt +0 -0
- {edq_utils-0.0.1.dist-info → edq_utils-0.0.3.dist-info}/WHEEL +0 -0
- {edq_utils-0.0.1.dist-info → edq_utils-0.0.3.dist-info}/licenses/LICENSE +0 -0
- {edq_utils-0.0.1.dist-info → edq_utils-0.0.3.dist-info}/top_level.txt +0 -0
edq/util/json.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This file standardizes how we write and read JSON.
|
|
3
|
+
Specifically, we try to be flexible when reading (using JSON5),
|
|
4
|
+
and strict when writing (using vanilla JSON).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import abc
|
|
8
|
+
import enum
|
|
9
|
+
import json
|
|
10
|
+
import typing
|
|
11
|
+
|
|
12
|
+
import json5
|
|
13
|
+
|
|
14
|
+
import edq.util.dirent
|
|
15
|
+
|
|
16
|
+
class DictConverter(abc.ABC):
|
|
17
|
+
"""
|
|
18
|
+
A base class for class that can represent (serialize) and reconstruct (deserialize) themselves as/from a dict.
|
|
19
|
+
The intention is that the dict can then be cleanly converted to/from JSON.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
@abc.abstractmethod
|
|
23
|
+
def to_dict(self) -> typing.Dict[str, typing.Any]:
|
|
24
|
+
"""
|
|
25
|
+
Return a dict that can be used to represent this object.
|
|
26
|
+
If the dict is passed to from_dict(), an identical object should be reconstructed.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
@abc.abstractmethod
|
|
31
|
+
# Note that `typing.Self` is returned, but that is introduced in Python 3.12.
|
|
32
|
+
def from_dict(cls, data: typing.Dict[str, typing.Any]) -> typing.Any:
|
|
33
|
+
"""
|
|
34
|
+
Return an instance of this subclass created using the given dict.
|
|
35
|
+
If the dict came from to_dict(), the returned object should be identical to the original.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __eq__(self, other: object) -> bool:
|
|
39
|
+
"""
|
|
40
|
+
Check for equality.
|
|
41
|
+
|
|
42
|
+
This check uses to_dict() and compares the results.
|
|
43
|
+
This may not be complete or efficient depending on the child class.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
# Note the hard type check (done so we can keep this method general).
|
|
47
|
+
if (type(self) != type(other)): # pylint: disable=unidiomatic-typecheck
|
|
48
|
+
return False
|
|
49
|
+
|
|
50
|
+
return self.to_dict() == other.to_dict() # type: ignore[attr-defined]
|
|
51
|
+
|
|
52
|
+
def __str__(self) -> str:
|
|
53
|
+
return dumps(self)
|
|
54
|
+
|
|
55
|
+
def __repr__(self) -> str:
|
|
56
|
+
return dumps(self)
|
|
57
|
+
|
|
58
|
+
def _custom_handle(value: typing.Any) -> typing.Union[typing.Dict[str, typing.Any], str]:
|
|
59
|
+
"""
|
|
60
|
+
Handle objects that are not JSON serializable by default,
|
|
61
|
+
e.g., calling vars() on an object.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
if (isinstance(value, DictConverter)):
|
|
65
|
+
return value.to_dict()
|
|
66
|
+
|
|
67
|
+
if (isinstance(value, enum.Enum)):
|
|
68
|
+
return str(value)
|
|
69
|
+
|
|
70
|
+
if (hasattr(value, '__dict__')):
|
|
71
|
+
return vars(value)
|
|
72
|
+
|
|
73
|
+
raise ValueError(f"Could not JSON serialize object: '{value}'.")
|
|
74
|
+
|
|
75
|
+
def load(file_obj: typing.TextIO, strict: bool = False, **kwargs) -> typing.Dict[str, typing.Any]:
|
|
76
|
+
"""
|
|
77
|
+
Load a file object/handler as JSON.
|
|
78
|
+
If strict is set, then use standard Python JSON,
|
|
79
|
+
otherwise use JSON5.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
if (strict):
|
|
83
|
+
return json.load(file_obj, **kwargs)
|
|
84
|
+
|
|
85
|
+
return json5.load(file_obj, **kwargs)
|
|
86
|
+
|
|
87
|
+
def loads(text: str, strict: bool = False, **kwargs) -> typing.Dict[str, typing.Any]:
|
|
88
|
+
"""
|
|
89
|
+
Load a string as JSON.
|
|
90
|
+
If strict is set, then use standard Python JSON,
|
|
91
|
+
otherwise use JSON5.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
if (strict):
|
|
95
|
+
return json.loads(text, **kwargs)
|
|
96
|
+
|
|
97
|
+
return json5.loads(text, **kwargs)
|
|
98
|
+
|
|
99
|
+
def load_path(
|
|
100
|
+
path: str,
|
|
101
|
+
strict: bool = False,
|
|
102
|
+
encoding: str = edq.util.dirent.DEFAULT_ENCODING,
|
|
103
|
+
**kwargs) -> typing.Dict[str, typing.Any]:
|
|
104
|
+
"""
|
|
105
|
+
Load a file path as JSON.
|
|
106
|
+
If strict is set, then use standard Python JSON,
|
|
107
|
+
otherwise use JSON5.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
try:
|
|
111
|
+
with open(path, 'r', encoding = encoding) as file:
|
|
112
|
+
return load(file, strict = strict, **kwargs)
|
|
113
|
+
except Exception as ex:
|
|
114
|
+
raise ValueError(f"Failed to read JSON file '{path}'.") from ex
|
|
115
|
+
|
|
116
|
+
def loads_object(text: str, cls: typing.Type[DictConverter], **kwargs) -> DictConverter:
|
|
117
|
+
""" Load a JSON string into an object (which is a subclass of DictConverter). """
|
|
118
|
+
|
|
119
|
+
data = loads(text, **kwargs)
|
|
120
|
+
if (not isinstance(data, dict)):
|
|
121
|
+
raise ValueError(f"JSON to load into an object is not a dict, found '{type(data)}'.")
|
|
122
|
+
|
|
123
|
+
return cls.from_dict(data)
|
|
124
|
+
|
|
125
|
+
def load_object_path(path: str, cls: typing.Type[DictConverter], **kwargs) -> DictConverter:
|
|
126
|
+
""" Load a JSON file into an object (which is a subclass of DictConverter). """
|
|
127
|
+
|
|
128
|
+
data = load_path(path, **kwargs)
|
|
129
|
+
if (not isinstance(data, dict)):
|
|
130
|
+
raise ValueError(f"JSON to load into an object is not a dict, found '{type(data)}'.")
|
|
131
|
+
|
|
132
|
+
return cls.from_dict(data)
|
|
133
|
+
|
|
134
|
+
def dump(
|
|
135
|
+
data: typing.Any,
|
|
136
|
+
file_obj: typing.TextIO,
|
|
137
|
+
default: typing.Union[typing.Callable, None] = _custom_handle,
|
|
138
|
+
sort_keys: bool = True,
|
|
139
|
+
**kwargs) -> None:
|
|
140
|
+
""" Dump an object as a JSON file object. """
|
|
141
|
+
|
|
142
|
+
json.dump(data, file_obj, default = default, sort_keys = sort_keys, **kwargs)
|
|
143
|
+
|
|
144
|
+
def dumps(
|
|
145
|
+
data: typing.Any,
|
|
146
|
+
default: typing.Union[typing.Callable, None] = _custom_handle,
|
|
147
|
+
sort_keys: bool = True,
|
|
148
|
+
**kwargs) -> str:
|
|
149
|
+
""" Dump an object as a JSON string. """
|
|
150
|
+
|
|
151
|
+
return json.dumps(data, default = default, sort_keys = sort_keys, **kwargs)
|
|
152
|
+
|
|
153
|
+
def dump_path(
|
|
154
|
+
data: typing.Any,
|
|
155
|
+
path: str,
|
|
156
|
+
default: typing.Union[typing.Callable, None] = _custom_handle,
|
|
157
|
+
sort_keys: bool = True,
|
|
158
|
+
encoding: str = edq.util.dirent.DEFAULT_ENCODING,
|
|
159
|
+
**kwargs) -> None:
|
|
160
|
+
""" Dump an object as a JSON file. """
|
|
161
|
+
|
|
162
|
+
with open(path, 'w', encoding = encoding) as file:
|
|
163
|
+
dump(data, file, default = default, sort_keys = sort_keys, **kwargs)
|
edq/util/json_test.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import typing
|
|
3
|
+
|
|
4
|
+
import edq.testing.unittest
|
|
5
|
+
import edq.util.dirent
|
|
6
|
+
import edq.util.json
|
|
7
|
+
import edq.util.reflection
|
|
8
|
+
|
|
9
|
+
class TestJSON(edq.testing.unittest.BaseTest):
|
|
10
|
+
""" Test JSON utils. """
|
|
11
|
+
|
|
12
|
+
def test_loading_dumping_base(self):
|
|
13
|
+
"""
|
|
14
|
+
Test the family of JSON loading and dumping functions.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
# [(string, dict, strict?, error_substring), ...]
|
|
18
|
+
test_cases = [
|
|
19
|
+
# Base
|
|
20
|
+
(
|
|
21
|
+
'{"a": 1}',
|
|
22
|
+
{"a": 1},
|
|
23
|
+
False,
|
|
24
|
+
None,
|
|
25
|
+
),
|
|
26
|
+
|
|
27
|
+
# Trivial - Strict
|
|
28
|
+
(
|
|
29
|
+
'{"a": 1}',
|
|
30
|
+
{"a": 1},
|
|
31
|
+
True,
|
|
32
|
+
None,
|
|
33
|
+
),
|
|
34
|
+
|
|
35
|
+
# JSON5
|
|
36
|
+
(
|
|
37
|
+
'{"a": 1,}',
|
|
38
|
+
{"a": 1},
|
|
39
|
+
False,
|
|
40
|
+
None,
|
|
41
|
+
),
|
|
42
|
+
|
|
43
|
+
# JSON5 - Strict
|
|
44
|
+
(
|
|
45
|
+
'{"a": 1,}',
|
|
46
|
+
{"a": 1},
|
|
47
|
+
True,
|
|
48
|
+
'JSONDecodeError',
|
|
49
|
+
),
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
# [(function, name), ...]
|
|
53
|
+
test_methods = [
|
|
54
|
+
(self._subtest_loads_dumps, 'subtest_loads_dumps'),
|
|
55
|
+
(self._subtest_load_dump, 'subtest_load_dump'),
|
|
56
|
+
(self._subtest_load_dump_path, 'subtest_load_dump_path'),
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
for (test_method, test_method_name) in test_methods:
|
|
60
|
+
for (i, test_case) in enumerate(test_cases):
|
|
61
|
+
(text_content, dict_content, strict, error_substring) = test_case
|
|
62
|
+
|
|
63
|
+
with self.subTest(msg = f"Subtest {test_method_name}, Case {i} ('{text_content}'):"):
|
|
64
|
+
try:
|
|
65
|
+
test_method(text_content, dict_content, strict)
|
|
66
|
+
except AssertionError:
|
|
67
|
+
# The subttest failed an assertion.
|
|
68
|
+
raise
|
|
69
|
+
except Exception as ex:
|
|
70
|
+
error_string = self.format_error_string(ex)
|
|
71
|
+
if (error_substring is None):
|
|
72
|
+
self.fail(f"Unexpected error: '{error_string}'.")
|
|
73
|
+
|
|
74
|
+
self.assertIn(error_substring, error_string, 'Error is not as expected.')
|
|
75
|
+
|
|
76
|
+
continue
|
|
77
|
+
|
|
78
|
+
if (error_substring is not None):
|
|
79
|
+
self.fail(f"Did not get expected error: '{error_substring}'.")
|
|
80
|
+
|
|
81
|
+
def _subtest_loads_dumps(self, text_content, dict_content, strict):
|
|
82
|
+
actual_dict = edq.util.json.loads(text_content, strict = strict)
|
|
83
|
+
actual_text = edq.util.json.dumps(dict_content)
|
|
84
|
+
double_conversion_text = edq.util.json.dumps(actual_dict)
|
|
85
|
+
|
|
86
|
+
self.assertDictEqual(dict_content, actual_dict)
|
|
87
|
+
self.assertEqual(actual_text, double_conversion_text)
|
|
88
|
+
|
|
89
|
+
def _subtest_load_dump(self, text_content, dict_content, strict):
|
|
90
|
+
temp_dir = edq.util.dirent.get_temp_dir(prefix = 'edq_test_json_')
|
|
91
|
+
|
|
92
|
+
path_text = os.path.join(temp_dir, 'test-text.json')
|
|
93
|
+
path_dict = os.path.join(temp_dir, 'test-dict.json')
|
|
94
|
+
|
|
95
|
+
edq.util.dirent.write_file(path_text, text_content)
|
|
96
|
+
|
|
97
|
+
with open(path_text, 'r', encoding = edq.util.dirent.DEFAULT_ENCODING) as file:
|
|
98
|
+
text_load = edq.util.json.load(file, strict = strict)
|
|
99
|
+
|
|
100
|
+
with open(path_dict, 'w', encoding = edq.util.dirent.DEFAULT_ENCODING) as file:
|
|
101
|
+
edq.util.json.dump(dict_content, file)
|
|
102
|
+
|
|
103
|
+
with open(path_dict, 'r', encoding = edq.util.dirent.DEFAULT_ENCODING) as file:
|
|
104
|
+
dict_load = edq.util.json.load(file, strict = strict)
|
|
105
|
+
|
|
106
|
+
self.assertDictEqual(dict_content, text_load)
|
|
107
|
+
self.assertDictEqual(dict_load, text_load)
|
|
108
|
+
|
|
109
|
+
def _subtest_load_dump_path(self, text_content, dict_content, strict):
|
|
110
|
+
temp_dir = edq.util.dirent.get_temp_dir(prefix = 'edq_test_json_path_')
|
|
111
|
+
|
|
112
|
+
path_text = os.path.join(temp_dir, 'test-text.json')
|
|
113
|
+
path_dict = os.path.join(temp_dir, 'test-dict.json')
|
|
114
|
+
|
|
115
|
+
edq.util.dirent.write_file(path_text, text_content)
|
|
116
|
+
text_load = edq.util.json.load_path(path_text, strict = strict)
|
|
117
|
+
|
|
118
|
+
edq.util.json.dump_path(dict_content, path_dict)
|
|
119
|
+
dict_load = edq.util.json.load_path(path_dict, strict = strict)
|
|
120
|
+
|
|
121
|
+
self.assertDictEqual(dict_content, text_load)
|
|
122
|
+
self.assertDictEqual(dict_load, text_load)
|
|
123
|
+
|
|
124
|
+
def test_object_base(self):
|
|
125
|
+
"""
|
|
126
|
+
Test loading and dumping JSON objects
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
# [(string, object, error_substring), ...]
|
|
130
|
+
test_cases = [
|
|
131
|
+
# Base
|
|
132
|
+
(
|
|
133
|
+
'{"a": 1, "b": "b"}',
|
|
134
|
+
_TestConverter(1, "b"),
|
|
135
|
+
None,
|
|
136
|
+
),
|
|
137
|
+
|
|
138
|
+
# Missing Key
|
|
139
|
+
(
|
|
140
|
+
'{"a": 1}',
|
|
141
|
+
_TestConverter(1, None),
|
|
142
|
+
None,
|
|
143
|
+
),
|
|
144
|
+
|
|
145
|
+
# Empty
|
|
146
|
+
(
|
|
147
|
+
'{}',
|
|
148
|
+
_TestConverter(None, None),
|
|
149
|
+
None,
|
|
150
|
+
),
|
|
151
|
+
|
|
152
|
+
# Extra Key
|
|
153
|
+
(
|
|
154
|
+
'{"a": 1, "b": "b", "c": 0}',
|
|
155
|
+
_TestConverter(1, "b"),
|
|
156
|
+
None,
|
|
157
|
+
),
|
|
158
|
+
|
|
159
|
+
# List
|
|
160
|
+
(
|
|
161
|
+
'[{"a": 1, "b": "b"}]',
|
|
162
|
+
_TestConverter(1, "b"),
|
|
163
|
+
'not a dict',
|
|
164
|
+
),
|
|
165
|
+
]
|
|
166
|
+
|
|
167
|
+
# [(function, name), ...]
|
|
168
|
+
test_methods = [
|
|
169
|
+
(self._subtest_loads_object, 'subtest_loads_object'),
|
|
170
|
+
(self._subtest_load_object_path, 'subtest_load_object_path'),
|
|
171
|
+
]
|
|
172
|
+
|
|
173
|
+
for (test_method, test_method_name) in test_methods:
|
|
174
|
+
for (i, test_case) in enumerate(test_cases):
|
|
175
|
+
(text_content, object_content, error_substring) = test_case
|
|
176
|
+
|
|
177
|
+
with self.subTest(msg = f"Subtest {test_method_name}, Case {i} ('{text_content}'):"):
|
|
178
|
+
try:
|
|
179
|
+
test_method(text_content, object_content)
|
|
180
|
+
except AssertionError:
|
|
181
|
+
# The subttest failed an assertion.
|
|
182
|
+
raise
|
|
183
|
+
except Exception as ex:
|
|
184
|
+
error_string = self.format_error_string(ex)
|
|
185
|
+
if (error_substring is None):
|
|
186
|
+
self.fail(f"Unexpected error: '{error_string}'.")
|
|
187
|
+
|
|
188
|
+
self.assertIn(error_substring, error_string, 'Error is not as expected.')
|
|
189
|
+
|
|
190
|
+
continue
|
|
191
|
+
|
|
192
|
+
if (error_substring is not None):
|
|
193
|
+
self.fail(f"Did not get expected error: '{error_substring}'.")
|
|
194
|
+
|
|
195
|
+
def _subtest_loads_object(self, text_content, object_content):
|
|
196
|
+
actual_object = edq.util.json.loads_object(text_content, _TestConverter)
|
|
197
|
+
actual_text = edq.util.json.dumps(object_content)
|
|
198
|
+
double_conversion_text = edq.util.json.dumps(actual_object)
|
|
199
|
+
|
|
200
|
+
self.assertEqual(object_content, actual_object)
|
|
201
|
+
self.assertEqual(actual_text, double_conversion_text)
|
|
202
|
+
|
|
203
|
+
def _subtest_load_object_path(self, text_content, object_content):
|
|
204
|
+
temp_dir = edq.util.dirent.get_temp_dir(prefix = 'edq_test_json_object_path_')
|
|
205
|
+
|
|
206
|
+
path_text = os.path.join(temp_dir, 'test-text.json')
|
|
207
|
+
path_object = os.path.join(temp_dir, 'test-object.json')
|
|
208
|
+
|
|
209
|
+
edq.util.dirent.write_file(path_text, text_content)
|
|
210
|
+
text_load = edq.util.json.load_object_path(path_text, _TestConverter)
|
|
211
|
+
|
|
212
|
+
edq.util.json.dump_path(object_content, path_object)
|
|
213
|
+
object_load = edq.util.json.load_object_path(path_object, _TestConverter)
|
|
214
|
+
|
|
215
|
+
self.assertEqual(object_content, text_load)
|
|
216
|
+
self.assertEqual(object_load, text_load)
|
|
217
|
+
|
|
218
|
+
class _TestConverter(edq.util.json.DictConverter):
|
|
219
|
+
def __init__(self, a: typing.Union[int, None] = None, b: typing.Union[str, None] = None, **kwargs) -> None:
|
|
220
|
+
self.a: typing.Union[int, None] = a
|
|
221
|
+
self.b: typing.Union[str, None] = b
|
|
222
|
+
|
|
223
|
+
def to_dict(self) -> typing.Dict[str, typing.Any]:
|
|
224
|
+
return vars(self)
|
|
225
|
+
|
|
226
|
+
@classmethod
|
|
227
|
+
def from_dict(cls, data: typing.Dict[str, typing.Any]) -> typing.Any:
|
|
228
|
+
return _TestConverter(**data)
|
edq/util/pyimport.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
import importlib.util
|
|
3
|
+
import os
|
|
4
|
+
import typing
|
|
5
|
+
import uuid
|
|
6
|
+
|
|
7
|
+
import edq.util.dirent
|
|
8
|
+
|
|
9
|
+
_import_cache: typing.Dict[str, typing.Any] = {}
|
|
10
|
+
""" A cache to help avoid importing a module multiple times. """
|
|
11
|
+
|
|
12
|
+
def import_path(raw_path: str, cache: bool = True, module_name: typing.Union[str, None] = None) -> typing.Any:
|
|
13
|
+
"""
|
|
14
|
+
Import a module from a file.
|
|
15
|
+
If cache is false, then the module will not be fetched or stored in this module's cache.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
path = os.path.abspath(raw_path)
|
|
19
|
+
cache_key = f"PATH::{path}"
|
|
20
|
+
|
|
21
|
+
# Check the cache before importing.
|
|
22
|
+
if (cache):
|
|
23
|
+
module = _import_cache.get(cache_key, None)
|
|
24
|
+
if (module is not None):
|
|
25
|
+
return module
|
|
26
|
+
|
|
27
|
+
if (not edq.util.dirent.exists(path)):
|
|
28
|
+
raise ValueError(f"Module path does not exist: '{raw_path}'.")
|
|
29
|
+
|
|
30
|
+
if (not os.path.isfile(path)):
|
|
31
|
+
raise ValueError(f"Module path is not a file: '{raw_path}'.")
|
|
32
|
+
|
|
33
|
+
if (module_name is None):
|
|
34
|
+
module_name = str(uuid.uuid4()).replace('-', '')
|
|
35
|
+
|
|
36
|
+
spec = importlib.util.spec_from_file_location(module_name, path)
|
|
37
|
+
if ((spec is None) or (spec.loader is None)):
|
|
38
|
+
raise ValueError(f"Failed to load module specification for path: '{raw_path}'.")
|
|
39
|
+
|
|
40
|
+
module = importlib.util.module_from_spec(spec)
|
|
41
|
+
spec.loader.exec_module(module)
|
|
42
|
+
|
|
43
|
+
# Store the module in the cache.
|
|
44
|
+
if (cache):
|
|
45
|
+
_import_cache[cache_key] = module
|
|
46
|
+
|
|
47
|
+
return module
|
|
48
|
+
|
|
49
|
+
def import_name(module_name: str, cache: bool = True) -> typing.Any:
|
|
50
|
+
"""
|
|
51
|
+
Import a module from a name.
|
|
52
|
+
The module must already be in the system's path (sys.path).
|
|
53
|
+
If cache is false, then the module will not be fetched or stored in this module's cache.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
cache_key = f"NAME::{module_name}"
|
|
57
|
+
|
|
58
|
+
# Check the cache before importing.
|
|
59
|
+
if (cache):
|
|
60
|
+
module = _import_cache.get(cache_key, None)
|
|
61
|
+
if (module is not None):
|
|
62
|
+
return module
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
module = importlib.import_module(module_name)
|
|
66
|
+
except ImportError as ex:
|
|
67
|
+
raise ValueError(f"Unable to locate module '{module_name}'.") from ex
|
|
68
|
+
|
|
69
|
+
# Store the module in the cache.
|
|
70
|
+
if (cache):
|
|
71
|
+
_import_cache[cache_key] = module
|
|
72
|
+
|
|
73
|
+
return module
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import edq.testing.unittest
|
|
4
|
+
import edq.util.pyimport
|
|
5
|
+
|
|
6
|
+
THIS_DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
|
|
7
|
+
PACKAGE_ROOT_DIR = os.path.join(THIS_DIR, '..')
|
|
8
|
+
|
|
9
|
+
class TestPyImport(edq.testing.unittest.BaseTest):
|
|
10
|
+
""" Test Python importing operations. """
|
|
11
|
+
|
|
12
|
+
def test_import_path_base(self):
|
|
13
|
+
""" Test importing a module from a path. """
|
|
14
|
+
|
|
15
|
+
# [(relative path, error substring), ...]
|
|
16
|
+
# All paths are relative to the package root.
|
|
17
|
+
test_cases = [
|
|
18
|
+
# Standard Module
|
|
19
|
+
(os.path.join('util', 'pyimport.py'), None),
|
|
20
|
+
|
|
21
|
+
# Errors
|
|
22
|
+
('ZZZ', 'Module path does not exist'),
|
|
23
|
+
('util', 'Module path is not a file'),
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
for (i, test_case) in enumerate(test_cases):
|
|
27
|
+
(relpath, error_substring) = test_case
|
|
28
|
+
|
|
29
|
+
with self.subTest(msg = f"Case {i} ('{relpath}'):"):
|
|
30
|
+
path = os.path.join(PACKAGE_ROOT_DIR, relpath)
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
module = edq.util.pyimport.import_path(path)
|
|
34
|
+
except Exception as ex:
|
|
35
|
+
error_string = self.format_error_string(ex)
|
|
36
|
+
if (error_substring is None):
|
|
37
|
+
self.fail(f"Unexpected error: '{error_string}'.")
|
|
38
|
+
|
|
39
|
+
self.assertIn(error_substring, error_string, 'Error is not as expected.')
|
|
40
|
+
|
|
41
|
+
continue
|
|
42
|
+
|
|
43
|
+
if (error_substring is not None):
|
|
44
|
+
self.fail(f"Did not get expected error: '{error_substring}'.")
|
|
45
|
+
|
|
46
|
+
self.assertIsNotNone(module)
|
|
47
|
+
|
|
48
|
+
def test_import_name_base(self):
|
|
49
|
+
""" Test importing a module from a name. """
|
|
50
|
+
|
|
51
|
+
# [(name, error substring), ...]
|
|
52
|
+
test_cases = [
|
|
53
|
+
# Standard Module
|
|
54
|
+
('edq.util.pyimport', None),
|
|
55
|
+
|
|
56
|
+
# Package (__init__.py)
|
|
57
|
+
('edq.util', None),
|
|
58
|
+
|
|
59
|
+
# Errors
|
|
60
|
+
('', 'Empty module name'),
|
|
61
|
+
('edq.util.ZZZ', 'Unable to locate module'),
|
|
62
|
+
('edq.util.pyimport.ZZZ', 'Unable to locate module'),
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
for (i, test_case) in enumerate(test_cases):
|
|
66
|
+
(name, error_substring) = test_case
|
|
67
|
+
|
|
68
|
+
with self.subTest(msg = f"Case {i} ('{name}'):"):
|
|
69
|
+
try:
|
|
70
|
+
module = edq.util.pyimport.import_name(name)
|
|
71
|
+
except Exception as ex:
|
|
72
|
+
error_string = self.format_error_string(ex)
|
|
73
|
+
if (error_substring is None):
|
|
74
|
+
self.fail(f"Unexpected error: '{error_string}'.")
|
|
75
|
+
|
|
76
|
+
self.assertIn(error_substring, error_string, 'Error is not as expected.')
|
|
77
|
+
|
|
78
|
+
continue
|
|
79
|
+
|
|
80
|
+
if (error_substring is not None):
|
|
81
|
+
self.fail(f"Did not get expected error: '{error_substring}'.")
|
|
82
|
+
|
|
83
|
+
self.assertIsNotNone(module)
|
edq/util/reflection.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import typing
|
|
2
|
+
|
|
3
|
+
def get_qualified_name(target: typing.Union[type, object, str]) -> str:
|
|
4
|
+
"""
|
|
5
|
+
Try to get a qualified name for a type (or for the type of an object).
|
|
6
|
+
Names will not always come out clean.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
# Get the type for this target.
|
|
10
|
+
if (isinstance(target, type)):
|
|
11
|
+
target_class = target
|
|
12
|
+
elif (callable(target)):
|
|
13
|
+
target_class = typing.cast(type, target)
|
|
14
|
+
else:
|
|
15
|
+
target_class = type(target)
|
|
16
|
+
|
|
17
|
+
# Check for various name components.
|
|
18
|
+
parts = []
|
|
19
|
+
|
|
20
|
+
if (hasattr(target_class, '__module__')):
|
|
21
|
+
parts.append(str(getattr(target_class, '__module__')))
|
|
22
|
+
|
|
23
|
+
if (hasattr(target_class, '__qualname__')):
|
|
24
|
+
parts.append(str(getattr(target_class, '__qualname__')))
|
|
25
|
+
elif (hasattr(target_class, '__name__')):
|
|
26
|
+
parts.append(str(getattr(target_class, '__name__')))
|
|
27
|
+
|
|
28
|
+
# Fall back to just the string reprsentation.
|
|
29
|
+
if (len(parts) == 0):
|
|
30
|
+
return str(target_class)
|
|
31
|
+
|
|
32
|
+
return '.'.join(parts)
|
|
File without changes
|
edq/util/time.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
PRETTY_SHORT_FORMAT: str = '%Y-%m-%d %H:%M'
|
|
5
|
+
|
|
6
|
+
class Duration(int):
|
|
7
|
+
"""
|
|
8
|
+
A Duration represents some length in time in milliseconds.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
def to_secs(self) -> float:
|
|
12
|
+
""" Convert the duration to float seconds. """
|
|
13
|
+
|
|
14
|
+
return self / 1000.0
|
|
15
|
+
|
|
16
|
+
def to_msecs(self) -> int:
|
|
17
|
+
""" Convert the duration to integer milliseconds. """
|
|
18
|
+
|
|
19
|
+
return self
|
|
20
|
+
|
|
21
|
+
class Timestamp(int):
|
|
22
|
+
"""
|
|
23
|
+
A Timestamp represent a moment in time (sometimes called "datetimes").
|
|
24
|
+
Timestamps are internally represented by the number of milliseconds since the
|
|
25
|
+
(Unix Epoch)[https://en.wikipedia.org/wiki/Unix_time].
|
|
26
|
+
This is sometimes referred to as "Unix Time".
|
|
27
|
+
Since Unix Time is in UTC, timestamps do not need to carry timestamp information with them.
|
|
28
|
+
|
|
29
|
+
Note that timestamps are just integers with some decoration,
|
|
30
|
+
so they respond to all normal int functionality.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def sub(self, other: 'Timestamp') -> Duration:
|
|
34
|
+
""" Return a new duration that is the difference of this and the given duration. """
|
|
35
|
+
|
|
36
|
+
return Duration(self - other)
|
|
37
|
+
|
|
38
|
+
def to_pytime(self, timezone: datetime.timezone = datetime.timezone.utc) -> datetime.datetime:
|
|
39
|
+
""" Convert this timestamp to a Python datetime in the given timezone (UTC by default). """
|
|
40
|
+
|
|
41
|
+
return datetime.datetime.fromtimestamp(self / 1000, timezone)
|
|
42
|
+
|
|
43
|
+
def to_local_pytime(self) -> datetime.datetime:
|
|
44
|
+
""" Convert this timestamp to a Python datetime in the system timezone. """
|
|
45
|
+
|
|
46
|
+
local_timezone = datetime.datetime.now().astimezone().tzinfo
|
|
47
|
+
if ((local_timezone is None) or (not isinstance(local_timezone, datetime.timezone))):
|
|
48
|
+
raise ValueError("Could not discover local timezone.")
|
|
49
|
+
|
|
50
|
+
return self.to_pytime(timezone = local_timezone)
|
|
51
|
+
|
|
52
|
+
def pretty(self, short: bool = False, timezone: datetime.timezone = datetime.timezone.utc) -> str:
|
|
53
|
+
"""
|
|
54
|
+
Get a "pretty" string representation of this timestamp.
|
|
55
|
+
There is no guarantee that this representation can be parsed back to its original form.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
pytime = self.to_pytime(timezone = timezone)
|
|
59
|
+
|
|
60
|
+
if (short):
|
|
61
|
+
return pytime.strftime(PRETTY_SHORT_FORMAT)
|
|
62
|
+
|
|
63
|
+
return pytime.isoformat(timespec = 'milliseconds')
|
|
64
|
+
|
|
65
|
+
@staticmethod
|
|
66
|
+
def from_pytime(pytime: datetime.datetime) -> 'Timestamp':
|
|
67
|
+
""" Convert a Python datetime to a timestamp. """
|
|
68
|
+
|
|
69
|
+
return Timestamp(int(pytime.timestamp() * 1000))
|
|
70
|
+
|
|
71
|
+
@staticmethod
|
|
72
|
+
def now() -> 'Timestamp':
|
|
73
|
+
""" Get a Timestamp that represents the current moment. """
|
|
74
|
+
|
|
75
|
+
return Timestamp(time.time() * 1000)
|