def test_recursion(self): a = Container() # No ancestors. assert_raises(self, "a.add('a', a)", globals(), locals(), ValueError, ": add would cause container recursion") b = a.add('b', Container()) # Have ancestors. assert_raises(self, "b.add('a', a)", globals(), locals(), ValueError, "b: add would cause container recursion")
def test_save_load_pickle(self): output = StringIO.StringIO() c1 = Container() c1.add('c2', Container()) c1.save(output, constants.SAVE_PICKLE) inp = StringIO.StringIO(output.getvalue()) newc1 = Container.load(inp, constants.SAVE_PICKLE)
def test_find_trait_and_value(self): class MyClass(object): pass class MyHT(HasTraits): pass obj = MyClass() obj.sub = MyClass() obj.sub.sub = MyHT() obj.sub.csub = Container() obj.a = 1 obj.sub.b = 2 obj.sub.sub.c = 3 obj.sub.csub.add('d', Float(4, iotype='in')) result = find_trait_and_value(obj, 'sub.sub.c') self.assertEqual(result[0].type, 'python') self.assertEqual(result[1], 3) result = find_trait_and_value(obj, 'sub.csub.d') self.assertEqual(result[0].type, 'trait') self.assertEqual(result[1], 4) try: result = find_trait_and_value(obj, 'sub.foo') except AttributeError as err: self.assertEqual(str(err), "'MyClass' object has no attribute 'foo'") else: self.fail("expected AttributeError")
def test_set_output(self): c = Container() c.add_trait('inp', Float(iotype='in')) c.add_trait('out', Float(iotype='out')) c.set('inp', 42) assert_raises(self, "c.set('out', 666)", globals(), locals(), RuntimeError, ": Cannot set output 'out'")
def test_save_bad_format(self): output = StringIO.StringIO() c1 = Container() try: c1.save(output, 'no-such-format') except RuntimeError, exc: msg = ": Can't save object using format 'no-such-format'" self.assertEqual(str(exc), msg)
def test_add_bad_child(self): foo = Container() try: foo.add('non_container', 'some string') except TypeError, err: self.assertEqual( str(err), ": '<type 'str'>' " + "object is not an instance of Container.")
def test_save_load_cpickle(self): output = StringIO.StringIO() c1 = Container() c1.add('c2', Container()) c1.save(output) inp = StringIO.StringIO(output.getvalue()) newc1 = Container.load(inp)
def test_save_load_libyaml(self): output = StringIO.StringIO() c1 = Container() c1.add('c2', Container()) c1.save(output, constants.SAVE_LIBYAML) inp = StringIO.StringIO(output.getvalue()) newc1 = Container.load(inp, constants.SAVE_LIBYAML)
def test_add_bad_name(self): bad_names = ['parent', 'self', 'for', 'if', 'while', 'sin', 'cos', 'tan'] for bad in bad_names: try: self.root.add(bad, Container()) except Exception as err: self.assertEqual(str(err), ": '%s' is a reserved or invalid name" % bad) else: self.fail("name '%s' should be illegal" % bad)
def test_save_load_cpickle(self): output = StringIO.StringIO() c1 = Container() c1.add('c2', Container()) c1.add('list_in', List(Float, iotype='in')) c1.list_in = [1., 2., 3.] self.assertEqual(c1.list_in, [1., 2., 3.]) c1.save(output) inp = StringIO.StringIO(output.getvalue()) newc1 = Container.load(inp) self.assertEqual(newc1.list_in, [1., 2., 3.]) # The List fixup issue occurs on the second save/load. output = StringIO.StringIO() newc1.save(output) inp = StringIO.StringIO(output.getvalue()) newerc1 = Container.load(inp) self.assertEqual(newerc1.list_in, [1., 2., 3.])
def test_get_attributes(self): c = Container() c.add_trait('inp', Float(desc='Stuff', low=-200, high=200)) c.set('inp', 42) attrs = c.get_attributes() self.assertTrue("Inputs" in attrs.keys()) check = {'name': 'inp', 'value': 42.0, 'high': 200.0, 'connected': '', 'low': -200.0, 'type': 'float', 'desc': 'Stuff'} for key in check.keys(): self.assertEqual(check[key], attrs["Inputs"][0][key])
def test_save_bad_filename(self): # TODO: get make_protected_dir() to work on Windows. if sys.platform == 'win32': raise nose.SkipTest() c1 = Container() directory = make_protected_dir() path = os.path.join(directory, 'illegal') try: c1.save(path) except IOError, exc: msg = ": Can't save to '%s': Permission denied" % path self.assertEqual(str(exc), msg)
def test_save_bad_method(self): # This test exercises handling references to unbound methods defined # in __main__. Because of this, it only does it's job if this is the # main module (not run as part of a larger suite in the buildout dir). output = StringIO.StringIO() c1 = Container() c1.unbound_thing = ContainerTestCase.test_save_bad_method try: c1.save(output) except RuntimeError, exc: msg = ": _pickle_method: <unbound method ContainerTestCase" \ ".test_save_bad_method> with module __main__ (None)" self.assertEqual(str(exc), msg)
def test_iteration2(self): # Had been skipping some traits of multiple instances. class Ext(Container): resources = Dict(iotype='in') top = Ext() top.add('ext2', Ext()) sub = top.add('sub', Container()) sub.add('ext3', Ext()) names = [n for n, x in top.items(recurse=True)] expected = ['ext2', 'ext2.resources', 'resources', 'sub', 'sub.ext3', 'sub.ext3.resources'] self.assertEqual(sorted(names), expected)
def test_set_metadata(self): c = Container() c.add_trait('inp', List(range(1000), ddcomp_start=0, ddcomp_end=-1)) self.assertEqual(c.get_metadata('inp', 'ddcomp_start'), 0) self.assertEqual(c.get_metadata('inp', 'ddcomp_end'), -1) c.set_metadata('inp', 'ddcomp_start', 10) c.set_metadata('inp', 'ddcomp_end', 20) self.assertEqual(c.get_metadata('inp', 'ddcomp_start'), 10) self.assertEqual(c.get_metadata('inp', 'ddcomp_end'), 20) assert_raises(self, "c.set_metadata('inp', 'iotype', 'out')", globals(), locals(), TypeError, ": Can't set iotype on inp, read-only")
def load_model(self, egg_filename): """ Load model from egg and return top-level object if this server's `allow_shell` attribute is True. egg_filename: string Filename of egg to be loaded. """ self._logger.debug('load_model %r', egg_filename) if not self._allow_shell: self._logger.error('attempt to load %r by %r', egg_filename, get_credentials().user) raise RuntimeError('shell access is not allowed by this server') self._check_path(egg_filename, 'load_model') if self.tlo: self.tlo.pre_delete() self.tlo = Container.load_from_eggfile(egg_filename, log=self._logger) return self.tlo
def test_build_trait(self): mbc = MyBuilderContainer() obj_info = [ 'f_in', ('f_out_internal', 'f_out', 'out'), 'i_in', 'i_out', ('b_out_internal', 'b_out', 'out', Bool()), ('i_has_metadata', '', dict(iotype='in', low=-1, high=9)) ] create_io_traits(mbc, obj_info) create_io_traits(mbc, 'foobar') self.assertTrue(mbc.get_trait('b_out').is_trait_type(Bool)) self.assertTrue(mbc.get_trait('f_out').is_trait_type(Float)) self.assertEqual(mbc.get_trait('f_out').iotype, 'out') self.assertTrue(mbc.get_trait('i_in').is_trait_type(Int)) self.assertEqual(mbc.get_trait('f_in').iotype, 'in') self.assertTrue(mbc.get_trait('foobar').is_trait_type(Float)) self.assertEqual(mbc.get_trait('foobar').iotype, 'in') self.assertTrue(mbc.get_trait('i_has_metadata').is_trait_type(Int)) self.assertEqual(mbc.get_trait('i_has_metadata').iotype, 'in') self.assertEqual(mbc.get_trait('i_has_metadata').low, -1) self.assertEqual(mbc.get_trait('i_has_metadata').high, 9) code = "create_io_traits(mbc, [{}])" msg = ": create_io_traits cannot add trait {}" assert_raises(self, code, globals(), locals(), RuntimeError, msg) code = "create_io_traits(mbc, ('f_in', 'f.in'))" msg = ": Can't create 'f.in' because it's a dotted pathname" assert_raises(self, code, globals(), locals(), NameError, msg) code = "create_io_traits(mbc, ('f2_in', 'f_in'))" msg = ": Can't create 'f_in' because it already exists" assert_raises(self, code, globals(), locals(), RuntimeError, msg) code = "create_io_traits(mbc, 'does_not_exist')" msg = ": Can't create trait for 'does_not_exist' because it wasn't found" assert_raises(self, code, globals(), locals(), AttributeError, msg) cont = Container() cont.contains = lambda name: True code = "create_io_traits(cont, 'xyzzy')" msg = ": build_trait()" assert_raises(self, code, globals(), locals(), NotImplementedError, msg)
def setUp(self): """This sets up the following hierarchy of Containers: root / \ c1 c2 / \ c21 c22 / c221 / number """ self.root = Container() self.root.add('c1', Container()) self.root.add('c2', Container()) self.root.c2.add('c21', Container()) self.root.c2.add('c22', Container()) self.root.c2.c22.add('c221', Container()) self.root.c2.c22.c221.add('number', Float(3.14, iotype='in'))
def test_add_non_container(self): foo = Container() foo.add('non_container', 'some string') self.assertEqual(foo.non_container, 'some string')
def test_load_bad_format(self): try: Container.load(StringIO.StringIO(''), 'no-such-format') except RuntimeError, exc: msg = "Can't load object using format 'no-such-format'" self.assertEqual(str(exc), msg)
def test_load_nofile(self): try: Container.load('no-such-file') except ValueError, exc: msg = "Bad state filename 'no-such-file'." self.assertEqual(str(exc), msg)
def test_get_entry_group(self): class MyClass(object): pass self.assertEqual(_get_entry_group(MyClass()), None) self.assertEqual(_get_entry_group(Container()), 'openmdao.container')
def test_pathname(self): self.root.add('foo', Container()) self.root.foo.add('foochild', Container()) self.assertEqual(self.root.foo.foochild.get_pathname(), 'foo.foochild')
def test_add_trait_w_subtrait(self): obj = Container() obj.add('lst', List([1, 2, 3], iotype='in')) obj.add('dct', Dict({}, iotype='in'))
def test_default_naming(self): cont = Container() cont.add('container1', Container()) cont.add('container2', Container()) self.assertEqual(get_default_name(Container(), cont), 'container3') self.assertEqual(get_default_name(Container(), None), 'container1')