| 1 |
import numpy as np |
| 2 |
from uuid import uuid4, UUID |
| 3 |
import os |
| 4 |
|
| 5 |
from hdmf.container import AbstractContainer, Container, Data, HERDManager |
| 6 |
from hdmf.common.resources import HERD |
| 7 |
from hdmf.testing import TestCase |
| 8 |
from hdmf.utils import docval |
| 9 |
from hdmf.common import DynamicTable, VectorData, DynamicTableRegion |
| 10 |
from hdmf.backends.hdf5.h5tools import HDF5IO |
| 11 |
|
| 12 |
|
| 13 |
class Subcontainer(Container): |
| 14 |
pass |
| 15 |
|
| 16 |
|
| 17 |
class ContainerWithChild(Container): |
| 18 |
__fields__ = ({'name': 'field1', 'child': True}, ) |
| 19 |
|
| 20 |
@docval({'name': 'field1', 'doc': 'field1 doc', 'type': None, 'default': None}) |
| 21 |
def __init__(self, **kwargs): |
| 22 |
super().__init__('test name') |
| 23 |
self.field1 = kwargs['field1'] |
| 24 |
|
| 25 |
|
| 26 |
class TestHERDManager(TestCase): |
| 27 |
def test_link_and_get_resources(self): |
| 28 |
em = HERDManager() |
| 29 |
er = HERD() |
| 30 |
|
| 31 |
em.link_resources(er) |
| 32 |
er_get = em.get_linked_resources() |
| 33 |
self.assertEqual(er, er_get) |
| 34 |
|
| 35 |
|
| 36 |
class TestContainer(TestCase): |
| 37 |
|
| 38 |
def setUp(self): |
| 39 |
self.path = "test_container.h5" |
| 40 |
self.path2 = "test_container2.h5" |
| 41 |
|
| 42 |
def tearDown(self): |
| 43 |
if os.path.exists(self.path): |
| 44 |
os.remove(self.path) |
| 45 |
if os.path.exists(self.path2): |
| 46 |
os.remove(self.path2) |
| 47 |
|
| 48 |
def test_new(self): |
| 49 |
"""Test that __new__ properly sets parent and other fields. |
| 50 |
""" |
| 51 |
parent_obj = Container('obj1') |
| 52 |
child_object_id = str(uuid4()) |
| 53 |
child_obj = Container.__new__(Container, parent=parent_obj, object_id=child_object_id, |
| 54 |
container_source="test_source") |
| 55 |
self.assertIs(child_obj.parent, parent_obj) |
| 56 |
self.assertIs(parent_obj.children[0], child_obj) |
| 57 |
self.assertEqual(child_obj.object_id, child_object_id) |
| 58 |
self.assertFalse(child_obj._in_construct_mode) |
| 59 |
self.assertTrue(child_obj.modified) |
| 60 |
|
| 61 |
def test_get_data_type(self): |
| 62 |
obj = Container('obj1') |
| 63 |
dt = obj.data_type |
| 64 |
self.assertEqual(dt, 'Container') |
| 65 |
|
| 66 |
def test_new_object_id_none(self): |
| 67 |
"""Test that passing object_id=None to __new__ is OK and results in a non-None object ID being assigned. |
| 68 |
""" |
| 69 |
parent_obj = Container('obj1') |
| 70 |
child_obj = Container.__new__(Container, parent=parent_obj, object_id=None) |
| 71 |
self.assertIsNotNone(child_obj.object_id) |
| 72 |
UUID(child_obj.object_id, version=4) # raises ValueError if invalid |
| 73 |
|
| 74 |
def test_new_construct_mode(self): |
| 75 |
"""Test that passing in_construct_mode to __new__ sets _in_construct_mode and _in_construct_mode can be reset. |
| 76 |
""" |
| 77 |
parent_obj = Container('obj1') |
| 78 |
child_obj = Container.__new__(Container, parent=parent_obj, object_id=None, in_construct_mode=True) |
| 79 |
self.assertTrue(child_obj._in_construct_mode) |
| 80 |
child_obj._in_construct_mode = False |
| 81 |
self.assertFalse(child_obj._in_construct_mode) |
| 82 |
|
| 83 |
def test_init(self): |
| 84 |
"""Test that __init__ properly sets object ID and other fields. |
| 85 |
""" |
| 86 |
obj = Container('obj1') |
| 87 |
self.assertIsNotNone(obj.object_id) |
| 88 |
UUID(obj.object_id, version=4) # raises ValueError if invalid |
| 89 |
self.assertFalse(obj._in_construct_mode) |
| 90 |
self.assertTrue(obj.modified) |
| 91 |
self.assertEqual(obj.children, tuple()) |
| 92 |
self.assertIsNone(obj.parent) |
| 93 |
self.assertEqual(obj.name, 'obj1') |
| 94 |
self.assertIsNone(obj.read_io) |
| 95 |
|
| 96 |
def test_read_io_none(self): |
| 97 |
"""Test that __init__ properly sets read_io to None""" |
| 98 |
obj = Container('obj1') |
| 99 |
self.assertIsNone(obj.read_io) |
| 100 |
|
| 101 |
def test_read_io_setter(self): |
| 102 |
"""Test setting the read IO property""" |
| 103 |
obj = Container('obj1') |
| 104 |
# Bad value for read_io |
| 105 |
with self.assertRaises(TypeError): |
| 106 |
obj.read_io = "test" |
| 107 |
# Set read_io |
| 108 |
with HDF5IO(self.path, mode='w') as temp_io: |
| 109 |
obj.read_io = temp_io |
| 110 |
self.assertIs(obj.read_io, temp_io) |
| 111 |
# test that setting the read_io object to the same io object is OK |
| 112 |
obj.read_io = temp_io |
| 113 |
# Check that setting read_io to another io object fails |
| 114 |
with HDF5IO(self.path2, mode='w') as temp_io2: |
| 115 |
with self.assertRaises(ValueError): |
| 116 |
obj.read_io = temp_io2 |
| 117 |
|
| 118 |
def test_get_read_io_on_self(self): |
| 119 |
"""Test that get_read_io works when the container is set on the container""" |
| 120 |
obj = Container('obj1') |
| 121 |
self.assertIsNone(obj.get_read_io()) |
| 122 |
with HDF5IO(self.path, mode='w') as temp_io: |
| 123 |
obj.read_io = temp_io |
| 124 |
re_io = obj.get_read_io() |
| 125 |
self.assertIs(re_io, temp_io) |
| 126 |
|
| 127 |
def test_get_read_io_on_parent(self): |
| 128 |
"""Test that get_read_io works when the container is set on the parent""" |
| 129 |
parent_obj = Container('obj1') |
| 130 |
child_obj = Container('obj2') |
| 131 |
child_obj.parent = parent_obj |
| 132 |
with HDF5IO(self.path, mode='w') as temp_io: |
| 133 |
parent_obj.read_io = temp_io |
| 134 |
self.assertIsNone(child_obj.read_io) |
| 135 |
self.assertIs(child_obj.get_read_io(), temp_io) |
| 136 |
|
| 137 |
def test_del_read_io(self): |
| 138 |
class TestContainer(AbstractContainer): |
| 139 |
def __init__(self): |
| 140 |
raise ValueError("Error") |
| 141 |
with self.assertRaises(ValueError): |
| 142 |
TestContainer() |
| 143 |
|
| 144 |
def test_set_parent(self): |
| 145 |
"""Test that parent setter properly sets parent |
| 146 |
""" |
| 147 |
parent_obj = Container('obj1') |
| 148 |
child_obj = Container('obj2') |
| 149 |
child_obj.parent = parent_obj |
| 150 |
self.assertIs(child_obj.parent, parent_obj) |
| 151 |
self.assertIs(parent_obj.children[0], child_obj) |
| 152 |
|
| 153 |
def test_set_parent_overwrite(self): |
| 154 |
"""Test that parent setter properly blocks overwriting |
| 155 |
""" |
| 156 |
parent_obj = Container('obj1') |
| 157 |
child_obj = Container('obj2') |
| 158 |
child_obj.parent = parent_obj |
| 159 |
self.assertIs(parent_obj.children[0], child_obj) |
| 160 |
|
| 161 |
another_obj = Container('obj3') |
| 162 |
with self.assertRaisesWith(ValueError, |
| 163 |
'Cannot reassign parent to Container: %s. Parent is already: %s.' |
| 164 |
% (repr(child_obj), repr(child_obj.parent))): |
| 165 |
child_obj.parent = another_obj |
| 166 |
self.assertIs(child_obj.parent, parent_obj) |
| 167 |
self.assertIs(parent_obj.children[0], child_obj) |
| 168 |
|
| 169 |
def test_set_parent_overwrite_proxy(self): |
| 170 |
"""Test that parent setter properly blocks overwriting with proxy/object |
| 171 |
""" |
| 172 |
child_obj = Container('obj2') |
| 173 |
child_obj.parent = object() |
| 174 |
|
| 175 |
with self.assertRaisesRegex(ValueError, |
| 176 |
r"Got None for parent of '[^/]+' - cannot overwrite Proxy with NoneType"): |
| 177 |
child_obj.parent = None |
| 178 |
|
| 179 |
def test_slash_restriction(self): |
| 180 |
self.assertRaises(ValueError, Container, 'bad/name') |
| 181 |
|
| 182 |
def test_set_modified_parent(self): |
| 183 |
"""Test that set modified properly sets parent modified |
| 184 |
""" |
| 185 |
parent_obj = Container('obj1') |
| 186 |
child_obj = Container('obj2') |
| 187 |
child_obj.parent = parent_obj |
| 188 |
parent_obj.set_modified(False) |
| 189 |
child_obj.set_modified(False) |
| 190 |
self.assertFalse(child_obj.parent.modified) |
| 191 |
child_obj.set_modified() |
| 192 |
self.assertTrue(child_obj.parent.modified) |
| 193 |
|
| 194 |
def test_all_children(self): |
| 195 |
col1 = VectorData( |
| 196 |
name='Species_1', |
| 197 |
description='...', |
| 198 |
data=['Homo sapiens'], |
| 199 |
) |
| 200 |
species = DynamicTable(name='species', description='My species', columns=[col1]) |
| 201 |
obj = species.all_objects |
| 202 |
self.assertEqual(sorted(list(obj.keys())), sorted([species.object_id, species.id.object_id, col1.object_id])) |
| 203 |
|
| 204 |
def test_add_child(self): |
| 205 |
"""Test that add child creates deprecation warning and also properly sets child's parent and modified |
| 206 |
""" |
| 207 |
parent_obj = Container('obj1') |
| 208 |
child_obj = Container('obj2') |
| 209 |
parent_obj.set_modified(False) |
| 210 |
with self.assertWarnsWith(DeprecationWarning, 'add_child is deprecated. Set the parent attribute instead.'): |
| 211 |
parent_obj.add_child(child_obj) |
| 212 |
self.assertIs(child_obj.parent, parent_obj) |
| 213 |
self.assertTrue(parent_obj.modified) |
| 214 |
self.assertIs(parent_obj.children[0], child_obj) |
| 215 |
|
| 216 |
def test_parent_set_link_warning(self): |
| 217 |
col1 = VectorData( |
| 218 |
name='col1', |
| 219 |
description='column #1', |
| 220 |
data=[1, 2], |
| 221 |
) |
| 222 |
col2 = VectorData( |
| 223 |
name='col2', |
| 224 |
description='column #2', |
| 225 |
data=['a', 'b'], |
| 226 |
) |
| 227 |
|
| 228 |
# this table will have two rows with ids 0 and 1 |
| 229 |
table = DynamicTable( |
| 230 |
name='my table', |
| 231 |
description='an example table', |
| 232 |
columns=[col1, col2], |
| 233 |
) |
| 234 |
|
| 235 |
dtr_col = DynamicTableRegion( |
| 236 |
name='table1_ref', |
| 237 |
description='references rows of earlier table', |
| 238 |
data=[0, 1, 0, 0], # refers to row indices of the 'table' variable |
| 239 |
table=table |
| 240 |
) |
| 241 |
|
| 242 |
data_col = VectorData( |
| 243 |
name='col2', |
| 244 |
description='column #2', |
| 245 |
data=['a', 'a', 'a', 'b'], |
| 246 |
) |
| 247 |
|
| 248 |
table2 = DynamicTable( |
| 249 |
name='my_table', |
| 250 |
description='an example table', |
| 251 |
columns=[dtr_col, data_col], |
| 252 |
) |
| 253 |
|
| 254 |
with self.assertWarns(Warning): |
| 255 |
table2.parent=ContainerWithChild() |
| 256 |
|
| 257 |
def test_set_parent_exists(self): |
| 258 |
"""Test that setting a parent a second time does nothing |
| 259 |
""" |
| 260 |
parent_obj = Container('obj1') |
| 261 |
child_obj = Container('obj2') |
| 262 |
child_obj3 = Container('obj3') |
| 263 |
child_obj.parent = parent_obj |
| 264 |
child_obj.parent = parent_obj |
| 265 |
child_obj3.parent = parent_obj |
| 266 |
self.assertEqual(len(parent_obj.children), 2) |
| 267 |
self.assertIs(parent_obj.children[0], child_obj) |
| 268 |
self.assertIs(parent_obj.children[1], child_obj3) |
| 269 |
|
| 270 |
def test_reassign_container_source(self): |
| 271 |
"""Test that reassign container source throws error |
| 272 |
""" |
| 273 |
parent_obj = Container('obj1') |
| 274 |
parent_obj.container_source = 'a source' |
| 275 |
with self.assertRaisesWith(Exception, 'cannot reassign container_source'): |
| 276 |
parent_obj.container_source = 'some other source' |
| 277 |
|
| 278 |
def test_repr(self): |
| 279 |
parent_obj = Container('obj1') |
| 280 |
self.assertRegex(str(parent_obj), r"obj1 hdmf.container.Container at 0x\d+") |
| 281 |
|
| 282 |
def test_type_hierarchy(self): |
| 283 |
self.assertEqual(Container.type_hierarchy(), (Container, AbstractContainer, object)) |
| 284 |
self.assertEqual(Subcontainer.type_hierarchy(), (Subcontainer, Container, AbstractContainer, object)) |
| 285 |
|
| 286 |
def test_generate_new_id_parent(self): |
| 287 |
"""Test that generate_new_id sets a new ID on the container and its children and sets modified on all.""" |
| 288 |
parent_obj = Container('obj1') |
| 289 |
child_obj = Container('obj2') |
| 290 |
child_obj.parent = parent_obj |
| 291 |
old_parent_id = parent_obj.object_id |
| 292 |
old_child_id = child_obj.object_id |
| 293 |
|
| 294 |
parent_obj.set_modified(False) |
| 295 |
child_obj.set_modified(False) |
| 296 |
parent_obj.generate_new_id() |
| 297 |
self.assertNotEqual(old_parent_id, parent_obj.object_id) |
| 298 |
self.assertNotEqual(old_child_id, child_obj.object_id) |
| 299 |
self.assertTrue(parent_obj.modified) |
| 300 |
self.assertTrue(child_obj.modified) |
| 301 |
|
| 302 |
def test_generate_new_id_child(self): |
| 303 |
"""Test that generate_new_id sets a new ID on the container and not its parent and sets modified on both.""" |
| 304 |
parent_obj = Container('obj1') |
| 305 |
child_obj = Container('obj2') |
| 306 |
child_obj.parent = parent_obj |
| 307 |
old_parent_id = parent_obj.object_id |
| 308 |
old_child_id = child_obj.object_id |
| 309 |
|
| 310 |
parent_obj.set_modified(False) |
| 311 |
child_obj.set_modified(False) |
| 312 |
child_obj.generate_new_id() |
| 313 |
self.assertEqual(old_parent_id, parent_obj.object_id) |
| 314 |
self.assertNotEqual(old_child_id, child_obj.object_id) |
| 315 |
self.assertTrue(parent_obj.modified) |
| 316 |
self.assertTrue(child_obj.modified) |
| 317 |
|
| 318 |
def test_generate_new_id_parent_no_recurse(self): |
| 319 |
"""Test that generate_new_id(recurse=False) sets a new ID on the container and not its children.""" |
| 320 |
parent_obj = Container('obj1') |
| 321 |
child_obj = Container('obj2') |
| 322 |
child_obj.parent = parent_obj |
| 323 |
old_parent_id = parent_obj.object_id |
| 324 |
old_child_id = child_obj.object_id |
| 325 |
|
| 326 |
parent_obj.set_modified(False) |
| 327 |
child_obj.set_modified(False) |
| 328 |
parent_obj.generate_new_id(recurse=False) |
| 329 |
self.assertNotEqual(old_parent_id, parent_obj.object_id) |
| 330 |
self.assertEqual(old_child_id, child_obj.object_id) |
| 331 |
self.assertTrue(parent_obj.modified) |
| 332 |
self.assertFalse(child_obj.modified) |
| 333 |
|
| 334 |
def test_remove_child(self): |
| 335 |
"""Test that removing a child removes only the child. |
| 336 |
""" |
| 337 |
parent_obj = Container('obj1') |
| 338 |
child_obj = Container('obj2') |
| 339 |
child_obj3 = Container('obj3') |
| 340 |
child_obj.parent = parent_obj |
| 341 |
child_obj3.parent = parent_obj |
| 342 |
parent_obj._remove_child(child_obj) |
| 343 |
self.assertIsNone(child_obj.parent) |
| 344 |
self.assertTupleEqual(parent_obj.children, (child_obj3, )) |
| 345 |
self.assertTrue(parent_obj.modified) |
| 346 |
self.assertTrue(child_obj.modified) |
| 347 |
|
| 348 |
def test_remove_child_noncontainer(self): |
| 349 |
"""Test that removing a non-Container child raises an error. |
| 350 |
""" |
| 351 |
msg = "Cannot remove non-AbstractContainer object from children." |
| 352 |
with self.assertRaisesWith(ValueError, msg): |
| 353 |
Container('obj1')._remove_child(object()) |
| 354 |
|
| 355 |
def test_remove_child_nonchild(self): |
| 356 |
"""Test that removing a non-Container child raises an error. |
| 357 |
""" |
| 358 |
msg = "Container 'dummy' is not a child of Container 'obj1'." |
| 359 |
with self.assertRaisesWith(ValueError, msg): |
| 360 |
Container('obj1')._remove_child(Container('dummy')) |
| 361 |
|
| 362 |
def test_reset_parent(self): |
| 363 |
"""Test that removing a child removes only the child. |
| 364 |
""" |
| 365 |
parent_obj = Container('obj1') |
| 366 |
child_obj = Container('obj2') |
| 367 |
child_obj3 = Container('obj3') |
| 368 |
child_obj.parent = parent_obj |
| 369 |
child_obj3.parent = parent_obj |
| 370 |
child_obj.reset_parent() |
| 371 |
self.assertIsNone(child_obj.parent) |
| 372 |
self.assertTupleEqual(parent_obj.children, (child_obj3, )) |
| 373 |
self.assertTrue(parent_obj.modified) |
| 374 |
self.assertTrue(child_obj.modified) |
| 375 |
|
| 376 |
def test_reset_parent_parent_noncontainer(self): |
| 377 |
"""Test that resetting a parent that is not a container raises an error. |
| 378 |
""" |
| 379 |
obj = Container('obj1') |
| 380 |
obj.parent = object() |
| 381 |
msg = "Cannot reset parent when parent is not an AbstractContainer: %s" % repr(obj.parent) |
| 382 |
with self.assertRaisesWith(ValueError, msg): |
| 383 |
obj.reset_parent() |
| 384 |
|
| 385 |
def test_reset_parent_no_parent(self): |
| 386 |
"""Test that resetting a non-existent parent has no effect. |
| 387 |
""" |
| 388 |
obj = Container('obj1') |
| 389 |
obj.reset_parent() |
| 390 |
self.assertIsNone(obj.parent) |
| 391 |
|
| 392 |
def test_get_ancestors(self): |
| 393 |
"""Test that get_ancestors returns the correct ancestors. |
| 394 |
""" |
| 395 |
grandparent_obj = Container('obj1') |
| 396 |
parent_obj = Container('obj2') |
| 397 |
child_obj = Container('obj3') |
| 398 |
parent_obj.parent = grandparent_obj |
| 399 |
child_obj.parent = parent_obj |
| 400 |
self.assertTupleEqual(grandparent_obj.get_ancestors(), tuple()) |
| 401 |
self.assertTupleEqual(parent_obj.get_ancestors(), (grandparent_obj, )) |
| 402 |
self.assertTupleEqual(child_obj.get_ancestors(), (parent_obj, grandparent_obj)) |
| 403 |
|
| 404 |
|
| 405 |
class TestHTMLRepr(TestCase): |
| 406 |
|
| 407 |
class ContainerWithChildAndData(Container): |
| 408 |
__fields__ = ( |
| 409 |
{'name': 'child', 'child': True}, |
| 410 |
"data", |
| 411 |
"str" |
| 412 |
) |
| 413 |
|
| 414 |
@docval( |
| 415 |
{'name': 'child', 'doc': 'field1 doc', 'type': Container}, |
| 416 |
{'name': "data", "doc": 'data', 'type': list, "default": None}, |
| 417 |
{'name': "str", "doc": 'str', 'type': str, "default": None}, |
| 418 |
|
| 419 |
) |
| 420 |
def __init__(self, **kwargs): |
| 421 |
super().__init__('test name') |
| 422 |
self.child = kwargs['child'] |
| 423 |
self.data = kwargs['data'] |
| 424 |
self.str = kwargs['str'] |
| 425 |
|
| 426 |
def test_repr_html_(self): |
| 427 |
child_obj1 = Container('test child 1') |
| 428 |
obj1 = self.ContainerWithChildAndData(child=child_obj1, data=[1, 2, 3], str="hello") |
| 429 |
assert obj1._repr_html_() == ( |
| 430 |
'\n <style>\n .container-fields {\n font-family: "Open Sans", Arial, ' |
| 431 |
'sans-serif;\n }\n .container-fields .field-value {\n color: ' |
| 432 |
'#00788E;\n }\n .container-fields details > summary {\n cursor: ' |
| 433 |
'pointer;\n display: list-item;\n }\n .container-fields details > ' |
| 434 |
'summary:hover {\n color: #0A6EAA;\n }\n </style>\n \n ' |
| 435 |
'<script>\n function copyToClipboard(text) {\n navigator.clipboard.writeText(' |
| 436 |
'text).then(function() {\n console.log(\'Copied to clipboard: \' + text);\n ' |
| 437 |
' }, function(err) {\n console.error(\'Could not copy text: \', err);\n ' |
| 438 |
' });\n }\n\n document.addEventListener(\'DOMContentLoaded\', function() {\n ' |
| 439 |
' let fieldKeys = document.querySelectorAll(\'.container-fields .field-key\');\n ' |
| 440 |
'fieldKeys.forEach(function(fieldKey) {\n fieldKey.addEventListener(\'click\', ' |
| 441 |
'function() {\n let accessCode = fieldKey.getAttribute(\'title\').replace(\'Access ' |
| 442 |
'code: \', \'\');\n copyToClipboard(accessCode);\n });\n ' |
| 443 |
' });\n });\n </script>\n <div class=\'container-wrap\'><div ' |
| 444 |
'class=\'container-header\'><div class=\'xr-obj-type\'><h3>test name (' |
| 445 |
'ContainerWithChildAndData)</h3></div></div><details><summary style="display: list-item; margin-left: ' |
| 446 |
'0px;" class="container-fields field-key" ' |
| 447 |
'title=".child"><b>child</b></summary></details><details><summary style="display: list-item; margin-left: ' |
| 448 |
'0px;" class="container-fields field-key" title=".data"><b>data</b></summary><div style="margin-left: ' |
| 449 |
'20px;" class="container-fields"><span class="field-key" title=".data[0]">0: </span><span ' |
| 450 |
'class="field-value">1</span></div><div style="margin-left: 20px;" class="container-fields"><span ' |
| 451 |
'class="field-key" title=".data[0][1]">1: </span><span class="field-value">2</span></div><div ' |
| 452 |
'style="margin-left: 20px;" class="container-fields"><span class="field-key" title=".data[0][1][2]">2: ' |
| 453 |
'</span><span class="field-value">3</span></div></details><div style="margin-left: 0px;" ' |
| 454 |
'class="container-fields"><span class="field-key" title=".str">str: </span><span ' |
| 455 |
'class="field-value">hello</span></div></div>' |
| 456 |
) |
| 457 |
|
| 458 |
|
| 459 |
class TestData(TestCase): |
| 460 |
|
| 461 |
def test_constructor_scalar(self): |
| 462 |
"""Test that constructor works correctly on scalar data |
| 463 |
""" |
| 464 |
data_obj = Data('my_data', 'foobar') |
| 465 |
self.assertEqual(data_obj.data, 'foobar') |
| 466 |
|
| 467 |
def test_bool_true(self): |
| 468 |
"""Test that __bool__ method works correctly on data with len |
| 469 |
""" |
| 470 |
data_obj = Data('my_data', [1, 2, 3, 4, 5]) |
| 471 |
self.assertTrue(data_obj) |
| 472 |
|
| 473 |
def test_bool_false(self): |
| 474 |
"""Test that __bool__ method works correctly on empty data |
| 475 |
""" |
| 476 |
data_obj = Data('my_data', []) |
| 477 |
self.assertFalse(data_obj) |
| 478 |
|
| 479 |
def test_shape_nparray(self): |
| 480 |
""" |
| 481 |
Test that shape works for np.array |
| 482 |
""" |
| 483 |
data_obj = Data('my_data', np.arange(10).reshape(2, 5)) |
| 484 |
self.assertTupleEqual(data_obj.shape, (2, 5)) |
| 485 |
|
| 486 |
def test_shape_list(self): |
| 487 |
""" |
| 488 |
Test that shape works for np.array |
| 489 |
""" |
| 490 |
data_obj = Data('my_data', [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]) |
| 491 |
self.assertTupleEqual(data_obj.shape, (2, 5)) |
| 492 |
|
| 493 |
|
| 494 |
class TestAbstractContainerFieldsConf(TestCase): |
| 495 |
|
| 496 |
def test_bad_fields_type(self): |
| 497 |
msg = "'__fields__' must be of type tuple" |
| 498 |
with self.assertRaisesWith(TypeError, msg): |
| 499 |
class BadFieldsType(AbstractContainer): |
| 500 |
__fields__ = {'name': 'field1'} |
| 501 |
|
| 502 |
def test_bad_field_conf_key(self): |
| 503 |
msg = "Unrecognized key 'child' in __fields__ config 'field1' on BadFieldConfKey" |
| 504 |
with self.assertRaisesWith(ValueError, msg): |
| 505 |
class BadFieldConfKey(AbstractContainer): |
| 506 |
__fields__ = ({'name': 'field1', 'child': True}, ) |
| 507 |
|
| 508 |
def test_bad_field_missing_name(self): |
| 509 |
msg = "must specify 'name' if using dict in __fields__" |
| 510 |
with self.assertRaisesWith(ValueError, msg): |
| 511 |
class BadFieldConfKey(AbstractContainer): |
| 512 |
__fields__ = ({'child': True}, ) |
| 513 |
|
| 514 |
@staticmethod |
| 515 |
def find_all_properties(klass): |
| 516 |
return [attr for attr in dir(klass) if isinstance(getattr(klass, attr, None), property)] |
| 517 |
|
| 518 |
def test_empty_fields(self): |
| 519 |
class EmptyFields(AbstractContainer): |
| 520 |
__fields__ = tuple() |
| 521 |
|
| 522 |
self.assertTupleEqual(EmptyFields.__fields__, tuple()) |
| 523 |
self.assertTupleEqual(EmptyFields._get_fields(), tuple()) |
| 524 |
self.assertTupleEqual(EmptyFields.get_fields_conf(), tuple()) |
| 525 |
|
| 526 |
props = TestAbstractContainerFieldsConf.find_all_properties(EmptyFields) |
| 527 |
expected = ['all_objects', 'children', 'container_source', 'data_type', 'fields', 'modified', |
| 528 |
'name', 'object_id', 'parent', 'read_io'] |
| 529 |
self.assertListEqual(props, expected) |
| 530 |
|
| 531 |
def test_named_fields(self): |
| 532 |
class NamedFields(AbstractContainer): |
| 533 |
__fields__ = ('field1', 'field2') |
| 534 |
|
| 535 |
@docval({'name': 'field2', 'doc': 'field2 doc', 'type': str}) |
| 536 |
def __init__(self, **kwargs): |
| 537 |
super().__init__('test name') |
| 538 |
self.field2 = kwargs['field2'] |
| 539 |
|
| 540 |
self.assertTupleEqual(NamedFields.__fields__, ('field1', 'field2')) |
| 541 |
self.assertIs(NamedFields._get_fields(), NamedFields.__fields__) |
| 542 |
|
| 543 |
expected = ({'doc': None, 'name': 'field1'}, |
| 544 |
{'doc': 'field2 doc', 'name': 'field2'}) |
| 545 |
self.assertTupleEqual(NamedFields.get_fields_conf(), expected) |
| 546 |
|
| 547 |
props = TestAbstractContainerFieldsConf.find_all_properties(NamedFields) |
| 548 |
expected = ['all_objects', 'children', 'container_source', 'data_type', |
| 549 |
'field1', 'field2', 'fields', 'modified', 'name', 'object_id', |
| 550 |
'parent', 'read_io'] |
| 551 |
self.assertListEqual(props, expected) |
| 552 |
|
| 553 |
f1_doc = getattr(NamedFields, 'field1').__doc__ |
| 554 |
self.assertIsNone(f1_doc) |
| 555 |
|
| 556 |
f2_doc = getattr(NamedFields, 'field2').__doc__ |
| 557 |
self.assertEqual(f2_doc, 'field2 doc') |
| 558 |
|
| 559 |
obj = NamedFields('field2 value') |
| 560 |
self.assertIsNone(obj.field1) |
| 561 |
self.assertEqual(obj.field2, 'field2 value') |
| 562 |
|
| 563 |
obj.field1 = 'field1 value' |
| 564 |
msg = "can't set attribute 'field2' -- already set" |
| 565 |
with self.assertRaisesWith(AttributeError, msg): |
| 566 |
obj.field2 = 'field2 value' |
| 567 |
obj.field2 = None # None value does nothing |
| 568 |
self.assertEqual(obj.field2, 'field2 value') |
| 569 |
|
| 570 |
def test_with_doc(self): |
| 571 |
"""Test that __fields__ related attributes are set correctly. |
| 572 |
|
| 573 |
Also test that the docstring for fields are not overridden by the docstring in the docval of __init__ if a doc |
| 574 |
is provided in cls.__fields__. |
| 575 |
""" |
| 576 |
class NamedFieldsWithDoc(AbstractContainer): |
| 577 |
__fields__ = ({'name': 'field1', 'doc': 'field1 orig doc'}, |
| 578 |
{'name': 'field2', 'doc': 'field2 orig doc'}) |
| 579 |
|
| 580 |
@docval({'name': 'field2', 'doc': 'field2 doc', 'type': str}) |
| 581 |
def __init__(self, **kwargs): |
| 582 |
super().__init__('test name') |
| 583 |
self.field2 = kwargs['field2'] |
| 584 |
|
| 585 |
expected = ({'doc': 'field1 orig doc', 'name': 'field1'}, |
| 586 |
{'doc': 'field2 orig doc', 'name': 'field2'}) |
| 587 |
self.assertTupleEqual(NamedFieldsWithDoc.get_fields_conf(), expected) |
| 588 |
|
| 589 |
f1_doc = getattr(NamedFieldsWithDoc, 'field1').__doc__ |
| 590 |
self.assertEqual(f1_doc, 'field1 orig doc') |
| 591 |
|
| 592 |
f2_doc = getattr(NamedFieldsWithDoc, 'field2').__doc__ |
| 593 |
self.assertEqual(f2_doc, 'field2 orig doc') |
| 594 |
|
| 595 |
def test_not_settable(self): |
| 596 |
"""Test that __fields__ related attributes are set correctly. |
| 597 |
|
| 598 |
Also test that the docstring for fields are not overridden by the docstring in the docval of __init__ if a doc |
| 599 |
is provided in cls.__fields__. |
| 600 |
""" |
| 601 |
class NamedFieldsNotSettable(AbstractContainer): |
| 602 |
__fields__ = ({'name': 'field1', 'settable': True}, |
| 603 |
{'name': 'field2', 'settable': False}) |
| 604 |
|
| 605 |
expected = ({'doc': None, 'name': 'field1', 'settable': True}, |
| 606 |
{'doc': None, 'name': 'field2', 'settable': False}) |
| 607 |
self.assertTupleEqual(NamedFieldsNotSettable.get_fields_conf(), expected) |
| 608 |
|
| 609 |
obj = NamedFieldsNotSettable('test name') |
| 610 |
|
| 611 |
obj.field1 = 'field1 value' |
| 612 |
with self.assertRaises(AttributeError): |
| 613 |
obj.field2 = 'field2 value' |
| 614 |
|
| 615 |
def test_inheritance(self): |
| 616 |
class NamedFields(AbstractContainer): |
| 617 |
__fields__ = ({'name': 'field1', 'doc': 'field1 doc', 'settable': False}, ) |
| 618 |
|
| 619 |
class NamedFieldsChild(NamedFields): |
| 620 |
__fields__ = ({'name': 'field2'}, ) |
| 621 |
|
| 622 |
self.assertTupleEqual(NamedFieldsChild.__fields__, ('field1', 'field2')) |
| 623 |
self.assertIs(NamedFieldsChild._get_fields(), NamedFieldsChild.__fields__) |
| 624 |
|
| 625 |
expected = ({'doc': 'field1 doc', 'name': 'field1', 'settable': False}, |
| 626 |
{'doc': None, 'name': 'field2'}) |
| 627 |
self.assertTupleEqual(NamedFieldsChild.get_fields_conf(), expected) |
| 628 |
|
| 629 |
props = TestAbstractContainerFieldsConf.find_all_properties(NamedFieldsChild) |
| 630 |
expected = ['all_objects', 'children', 'container_source', 'data_type', |
| 631 |
'field1', 'field2', 'fields', 'modified', 'name', 'object_id', |
| 632 |
'parent', 'read_io'] |
| 633 |
self.assertListEqual(props, expected) |
| 634 |
|
| 635 |
def test_inheritance_override(self): |
| 636 |
class NamedFields(AbstractContainer): |
| 637 |
__fields__ = ({'name': 'field1'}, ) |
| 638 |
|
| 639 |
class NamedFieldsChild(NamedFields): |
| 640 |
__fields__ = ({'name': 'field1', 'doc': 'overridden field', 'settable': False}, ) |
| 641 |
|
| 642 |
self.assertEqual(NamedFieldsChild._get_fields(), ('field1', )) |
| 643 |
ret = NamedFieldsChild.get_fields_conf() |
| 644 |
self.assertEqual(ret[0], {'name': 'field1', 'doc': 'overridden field', 'settable': False}) |
| 645 |
|
| 646 |
# obj = NamedFieldsChild('test name') |
| 647 |
# with self.assertRaises(AttributeError): |
| 648 |
# obj.field1 = 'field1 value' |
| 649 |
|
| 650 |
def test_mult_inheritance_base_mixin(self): |
| 651 |
class NamedFields(AbstractContainer): |
| 652 |
__fields__ = ({'name': 'field1', 'doc': 'field1 doc', 'settable': False}, ) |
| 653 |
|
| 654 |
class BlankMixin: |
| 655 |
pass |
| 656 |
|
| 657 |
class NamedFieldsChild(NamedFields, BlankMixin): |
| 658 |
__fields__ = ({'name': 'field2'}, ) |
| 659 |
|
| 660 |
self.assertTupleEqual(NamedFieldsChild.__fields__, ('field1', 'field2')) |
| 661 |
self.assertIs(NamedFieldsChild._get_fields(), NamedFieldsChild.__fields__) |
| 662 |
|
| 663 |
def test_mult_inheritance_base_container(self): |
| 664 |
class NamedFields(AbstractContainer): |
| 665 |
__fields__ = ({'name': 'field1', 'doc': 'field1 doc', 'settable': False}, ) |
| 666 |
|
| 667 |
class BlankMixin: |
| 668 |
pass |
| 669 |
|
| 670 |
class NamedFieldsChild(BlankMixin, NamedFields): |
| 671 |
__fields__ = ({'name': 'field2'}, ) |
| 672 |
|
| 673 |
self.assertTupleEqual(NamedFieldsChild.__fields__, ('field1', 'field2')) |
| 674 |
self.assertIs(NamedFieldsChild._get_fields(), NamedFieldsChild.__fields__) |
| 675 |
|
| 676 |
|
| 677 |
class TestContainerFieldsConf(TestCase): |
| 678 |
|
| 679 |
def test_required_name(self): |
| 680 |
class ContainerRequiredName(Container): |
| 681 |
__fields__ = ({'name': 'field1', 'required_name': 'field1 value'}, ) |
| 682 |
|
| 683 |
@docval({'name': 'field1', 'doc': 'field1 doc', 'type': None, 'default': None}) |
| 684 |
def __init__(self, **kwargs): |
| 685 |
super().__init__('test name') |
| 686 |
self.field1 = kwargs['field1'] |
| 687 |
|
| 688 |
msg = ("Field 'field1' on ContainerRequiredName has a required name and must be a subclass of " |
| 689 |
"AbstractContainer.") |
| 690 |
with self.assertRaisesWith(ValueError, msg): |
| 691 |
ContainerRequiredName('field1 value') |
| 692 |
|
| 693 |
obj1 = Container('test container') |
| 694 |
msg = "Field 'field1' on ContainerRequiredName must be named 'field1 value'." |
| 695 |
with self.assertRaisesWith(ValueError, msg): |
| 696 |
ContainerRequiredName(obj1) |
| 697 |
|
| 698 |
obj2 = Container('field1 value') |
| 699 |
obj3 = ContainerRequiredName(obj2) |
| 700 |
self.assertIs(obj3.field1, obj2) |
| 701 |
|
| 702 |
obj4 = ContainerRequiredName() |
| 703 |
self.assertIsNone(obj4.field1) |
| 704 |
|
| 705 |
def test_child(self): |
| 706 |
child_obj1 = Container('test child 1') |
| 707 |
obj1 = ContainerWithChild(child_obj1) |
| 708 |
self.assertIs(child_obj1.parent, obj1) |
| 709 |
|
| 710 |
child_obj2 = Container('test child 2') |
| 711 |
obj3 = ContainerWithChild((child_obj1, child_obj2)) |
| 712 |
self.assertIs(child_obj1.parent, obj1) # child1 parent is already set |
| 713 |
self.assertIs(child_obj2.parent, obj3) # child1 parent is already set |
| 714 |
|
| 715 |
child_obj3 = Container('test child 3') |
| 716 |
obj4 = ContainerWithChild({'test child 3': child_obj3}) |
| 717 |
self.assertIs(child_obj3.parent, obj4) |
| 718 |
|
| 719 |
obj2 = ContainerWithChild() |
| 720 |
self.assertIsNone(obj2.field1) |
| 721 |
|
| 722 |
def test_setter_set_modified(self): |
| 723 |
|
| 724 |
child_obj1 = Container('test child 1') |
| 725 |
obj1 = ContainerWithChild() |
| 726 |
obj1.set_modified(False) # set to False so that we can test that it is set to True next |
| 727 |
obj1.field1 = child_obj1 |
| 728 |
self.assertTrue(obj1.modified) |
| 729 |
self.assertIs(obj1.field1, child_obj1) |
| 730 |
|
| 731 |
obj3 = ContainerWithChild() |
| 732 |
obj3.set_modified(False) # set to False so that we can test that it is set to True next |
| 733 |
obj3.field1 = child_obj1 # child_obj1 already has a parent |
| 734 |
self.assertTrue(obj3.modified) |
| 735 |
self.assertIs(obj3.field1, child_obj1) |
| 736 |
|
| 737 |
|
| 738 |
class TestChangeFieldsName(TestCase): |
| 739 |
|
| 740 |
def test_fields(self): |
| 741 |
class ContainerNewFields(Container): |
| 742 |
_fieldsname = '__newfields__' |
| 743 |
__newfields__ = ({'name': 'field1', 'doc': 'field1 doc'}, ) |
| 744 |
|
| 745 |
@docval({'name': 'field1', 'doc': 'field1 doc', 'type': None, 'default': None}) |
| 746 |
def __init__(self, **kwargs): |
| 747 |
super().__init__('test name') |
| 748 |
self.field1 = kwargs['field1'] |
| 749 |
|
| 750 |
self.assertTupleEqual(ContainerNewFields.__newfields__, ('field1', )) |
| 751 |
self.assertIs(ContainerNewFields._get_fields(), ContainerNewFields.__newfields__) |
| 752 |
|
| 753 |
expected = ({'doc': 'field1 doc', 'name': 'field1'}, ) |
| 754 |
self.assertTupleEqual(ContainerNewFields.get_fields_conf(), expected) |
| 755 |
|
| 756 |
def test_fields_inheritance(self): |
| 757 |
class ContainerOldFields(Container): |
| 758 |
__fields__ = ({'name': 'field1', 'doc': 'field1 doc'}, ) |
| 759 |
|
| 760 |
@docval({'name': 'field1', 'doc': 'field1 doc', 'type': None, 'default': None}) |
| 761 |
def __init__(self, **kwargs): |
| 762 |
super().__init__('test name') |
| 763 |
self.field1 = kwargs['field1'] |
| 764 |
|
| 765 |
class ContainerNewFields(ContainerOldFields): |
| 766 |
_fieldsname = '__newfields__' |
| 767 |
__newfields__ = ({'name': 'field2', 'doc': 'field2 doc'}, ) |
| 768 |
|
| 769 |
@docval({'name': 'field1', 'doc': 'field1 doc', 'type': None, 'default': None}, |
| 770 |
{'name': 'field2', 'doc': 'field2 doc', 'type': None, 'default': None}) |
| 771 |
def __init__(self, **kwargs): |
| 772 |
super().__init__(kwargs['field1']) |
| 773 |
self.field2 = kwargs['field2'] |
| 774 |
|
| 775 |
self.assertTupleEqual(ContainerNewFields.__newfields__, ('field1', 'field2')) |
| 776 |
self.assertIs(ContainerNewFields._get_fields(), ContainerNewFields.__newfields__) |
| 777 |
|
| 778 |
expected = ({'doc': 'field1 doc', 'name': 'field1'}, |
| 779 |
{'doc': 'field2 doc', 'name': 'field2'}, ) |
| 780 |
self.assertTupleEqual(ContainerNewFields.get_fields_conf(), expected) |