-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathtools.py
More file actions
248 lines (199 loc) · 6.99 KB
/
tools.py
File metadata and controls
248 lines (199 loc) · 6.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
"""
Tools for testing XBlocks
"""
from contextlib import contextmanager
from opaque_keys.edx.keys import UsageKeyV2, LearningContextKey, DefinitionKey
from functools import partial
from xblock.fields import ScopeIds
import warnings
from xblock.runtime import Runtime, MemoryIdManager
def make_scope_ids_for_testing(
user_id=99,
context_slug="myContext",
block_type="myType",
block_id="myId",
):
"""
Make an instance of ScopeIds suitable for testing XBlock.
Any or all parameters can be omitted.
"""
return ScopeIds(
user_id=user_id,
block_type=block_type,
def_id=TestDefinitionKey(block_type, block_id),
usage_id=TestUsageKey(TestContextKey(context_slug), block_type, block_id),
)
class TestDefinitionKey(DefinitionKey):
"""
A simple definition key type for testing XBlock
When serialized, these keys look like:
td:myType.myId
"""
CANONICAL_NAMESPACE = 'td' # "Test Definition"
KEY_FIELDS = ('block_type', 'block_id')
block_type: str
block_id: str
__slots__ = KEY_FIELDS
CHECKED_INIT = False
def __init__(self, block_type: str, block_id: str):
super().__init__(block_type=block_type, block_id=block_id)
def _to_string(self) -> str:
"""
Serialize this key as a string
"""
return f"{self.block_type}.{self.block_id}"
@classmethod
def _from_string(cls, serialized: str):
"""
Instantiate this key from a serialized string
"""
(block_type, block_id) = serialized.split('.')
return cls(block_type, block_id)
class TestContextKey(LearningContextKey):
"""
A simple context key type for testing XBlock
When serialized, these keys look like:
tc:myContext
"""
CANONICAL_NAMESPACE = 'tc' # "Test Context"
KEY_FIELDS = ('slug',)
slug: str
__slots__ = KEY_FIELDS
CHECKED_INIT = False
def __init__(self, slug: str):
super().__init__(slug=slug)
def _to_string(self) -> str:
"""
Serialize this key as a string
"""
return self.slug
@classmethod
def _from_string(cls, serialized: str):
"""
Instantiate this key from a serialized string
"""
return cls(serialized)
class TestUsageKey(UsageKeyV2):
"""
A simple usage key type for testing XBlock
When serialized, these keys look like:
tu:myContext.myType.myId
"""
CANONICAL_NAMESPACE = 'tu' # "Test Usage"
KEY_FIELDS = ('context_key', 'block_type', 'block_id')
context_key: TestContextKey
block_type: str
block_id: str
__slots__ = KEY_FIELDS
CHECKED_INIT = False
def __init__(self, context_key: TestContextKey, block_type: str, block_id: str):
super().__init__(context_key=context_key, block_type=block_type, block_id=block_id)
def _to_string(self) -> str:
"""
Serialize this key as a string
"""
return ".".join((self.context_key.slug, self.block_type, self.block_id))
@classmethod
def _from_string(cls, serialized: str):
"""
Instantiate this key from a serialized string
"""
(context_slug, block_type, block_id) = serialized.split('.')
return cls(TestContextKey(context_slug), block_type, block_id)
def blocks_are_equivalent(block1, block2):
"""Compare two blocks for equivalence.
"""
# The two blocks have to be the same class.
if block1.__class__ != block2.__class__:
return False
# They have to have the same fields.
if set(block1.fields) != set(block2.fields):
return False
# The data fields have to have the same values.
for field_name in block1.fields:
if field_name in ('parent', 'children'):
continue
if getattr(block1, field_name) != getattr(block2, field_name):
return False
# The children need to be equal.
if block1.has_children != block2.has_children:
return False
if block1.has_children:
if len(block1.children) != len(block2.children):
return False
for child_id1, child_id2 in zip(block1.children, block2.children):
if child_id1 == child_id2:
# Equal ids mean they must be equal, check the next child.
continue
# Load up the actual children to see if they are equal.
child1 = block1.runtime.get_block(child_id1)
child2 = block2.runtime.get_block(child_id2)
if not blocks_are_equivalent(child1, child2):
return False
return True
def _unabc(cls, msg="{} isn't implemented"):
"""Helper method to implement `unabc`"""
def make_dummy_method(ab_name):
"""A function to make the dummy method, to close over ab_name."""
def dummy_method(self, *args, **kwargs):
"""The method provided for all missing abstract methods."""
raise NotImplementedError(msg.format(ab_name))
return dummy_method
for ab_name in cls.__abstractmethods__:
print(cls, ab_name)
setattr(cls, ab_name, make_dummy_method(ab_name))
cls.__abstractmethods__ = ()
return cls
def unabc(msg):
"""
Add dummy methods to a class to satisfy abstract base class constraints.
Usage::
@unabc
class NotAbstract(SomeAbstractClass):
pass
@unabc('Fake {}')
class NotAbstract(SomeAbstractClass):
pass
"""
# Handle the possibility that unabc is called without a custom message
if isinstance(msg, type):
return _unabc(msg)
else:
return partial(_unabc, msg=msg)
class WarningTestMixin:
"""
Add the ability to assert on warnings raised by a chunk of code.
"""
@contextmanager
def assertWarns(self, warning_class):
"""
Assert that at least one warning of class `warning_class` is
logged during the surrounded context.
"""
with warnings.catch_warnings(record=True) as warns:
warnings.simplefilter("always")
yield
self.assertGreaterEqual(len(warns), 1)
self.assertTrue(any(issubclass(warning.category, warning_class) for warning in warns))
@unabc("{} shouldn't be used in tests")
class TestRuntime(Runtime):
"""
An empty runtime to be used in tests
"""
__test__ = False
# unabc doesn't squash pylint errors
def __init__(self, *args, **kwargs):
memory_id_manager = MemoryIdManager()
# Provide an IdReader if one isn't already passed to the runtime.
if not args:
kwargs.setdefault('id_reader', memory_id_manager)
kwargs.setdefault('id_generator', memory_id_manager)
super().__init__(*args, **kwargs)
def handler_url(self, *args, **kwargs):
raise NotImplementedError
def local_resource_url(self, *args, **kwargs):
raise NotImplementedError
def publish(self, *args, **kwargs):
raise NotImplementedError
def resource_url(self, *args, **kwargs):
raise NotImplementedError