def test_normal(self): logging.debug('') logging.debug('test_normal') dummy = 'dummy_output' if os.path.exists(dummy): os.remove(dummy) extcode = set_as_top(ExternalCode()) extcode.timeout = 5 extcode.command = 'python sleep.py 1 %s' % dummy extcode.env_vars = {'SLEEP_DATA': 'Hello world!'} extcode.external_files.extend(( FileMetadata(path='sleep.py', input=True), FileMetadata(path=dummy, output=True) )) extcode.run() self.assertEqual(extcode.return_code, 0) self.assertEqual(extcode.timed_out, False) self.assertEqual(os.path.exists(dummy), True) with open(dummy, 'r') as inp: data = inp.readline().rstrip() self.assertEqual(data, extcode.env_vars['SLEEP_DATA']) # Now show that existing outputs are removed before execution. extcode.command = 'python sleep.py 1' extcode.run() msg = "[Errno 2] No such file or directory: 'dummy_output'" assert_raises(self, "open(dummy, 'r')", globals(), locals(), IOError, msg)
def test_constrained_optimization(self): # Test DakotaCONMIN driver. logging.debug('') logging.debug('test_constrained_optimization') top = set_as_top(ConstrainedOptimization()) top.run() # Current state isn't optimium, # probably left over from CONMIN line search. assert_rel_error(self, top.textbook.x1, 0.5, 0.0004) assert_rel_error(self, top.textbook.x2, 0.43167254, 0.0004) assert_rel_error(self, top.textbook.f, 0.16682649, 0.0007) with open('dakota_tabular.dat', 'rb') as inp: reader = csv.reader(inp, delimiter=' ', skipinitialspace=True) count = 0 for row in reader: # print >>sys.stderr, row count += 1 self.assertEqual(count, 31) self.assertEqual(row[0], '30') assert_rel_error(self, float(row[1]), 0.5, 0.0004) assert_rel_error(self, float(row[2]), 0.43167254, 0.0004) assert_rel_error(self, float(row[3]), 0.16682649, 0.0007) top.driver.clear_objectives() assert_raises(self, 'top.run()', globals(), locals(), ValueError, 'driver: No objectives, run aborted') top.driver.clear_parameters() assert_raises(self, 'top.run()', globals(), locals(), ValueError, 'driver: No parameters, run aborted')
def test_copy(self): logging.debug('') logging.debug('test_copy') extcode = set_as_top(ExternalCode()) assert_raises(self, "extcode.copy_inputs('Inputs', '*.inp')", globals(), locals(), RuntimeError, ": inputs_dir 'Inputs' does not exist") os.mkdir('Inputs') try: shutil.copy('sleep.py', os.path.join('Inputs', 'junk.inp')) extcode.copy_inputs('Inputs', '*.inp') self.assertEqual(os.path.exists('junk.inp'), True) finally: shutil.rmtree('Inputs', onerror=onerror) if os.path.exists('junk.inp'): os.remove('junk.inp') assert_raises(self, "extcode.copy_results('Outputs', '*.dat')", globals(), locals(), RuntimeError, ": results_dir 'Outputs' does not exist") os.mkdir('Outputs') try: shutil.copy('sleep.py', os.path.join('Outputs', 'junk.dat')) extcode.copy_results('Outputs', '*.dat') self.assertEqual(os.path.exists('junk.dat'), True) finally: shutil.rmtree('Outputs', onerror=onerror) if os.path.exists('junk.dat'): os.remove('junk.dat')
def test_request(self): logging.debug('') logging.debug('test_request') assembly = Assembly() comp1 = assembly.add('comp1', ExtCode()) comp2 = assembly.add('comp2', ExtCode()) sub = assembly.add('sub', Assembly()) comp3 = sub.add('comp3', ExtCode()) comp1.resources = dict(min_cpus=10, max_cpus=10, resource_limits=dict(virtual_memory=100, cpu_time=120), rerunnable=True, accounting_id='frobozz', queue_name='debug', job_category='MPI') comp2.resources = dict(max_cpus=2, resource_limits=dict(wallclock_time=1000000)) comp3.resources = dict(min_cpus=200, resource_limits=dict(virtual_memory=20, cpu_time=1000, wallclock_time=500), rerunnable=True, accounting_id='frobozz', queue_name='debug', job_category='MPI') req = RAM.max_request(assembly) expected = dict(min_cpus=200, max_cpus=200, resource_limits=dict(virtual_memory=100, cpu_time=1000, wallclock_time=1000000)) logging.debug('req: %r', req) logging.debug('exp: %r', expected) self.assertEqual(req, expected) req = RAM.total_request(assembly) expected = dict(min_cpus=200, max_cpus=200, resource_limits=dict(virtual_memory=100, cpu_time=1120, wallclock_time=1000500), rerunnable=True, accounting_id='frobozz', queue_name='debug', job_category='MPI') logging.debug('req: %r', req) logging.debug('exp: %r', expected) self.assertEqual(req, expected) comp3.resources['accounting_id'] = 'xyzzy' assert_raises(self, 'RAM.total_request(assembly)', globals(), locals(), ValueError, "Incompatible settings for 'accounting_id':" " 'xyzzy' vs. 'frobozz'")
def test_quickstart(self): # All options. argv = ['quickstart', 'foobar', '-c', 'FooBar', '-g', 'component', '-v', '1.1', '-d', self.tdir] parser = _get_plugin_parser() options, args = parser.parse_known_args(argv) retval = plugin_quickstart(parser, options, args) self.assertEqual(retval, 0) fandd = find_files(self.tdir, showdirs=True) self.assertEqual(set([os.path.basename(f) for f in fandd]), set(['foobar', 'src', 'docs', 'setup.cfg', 'setup.py', 'MANIFEST.in', '__init__.py', 'conf.py', 'usage.rst', 'index.rst', 'srcdocs.rst', 'pkgdocs.rst', 'foobar.py', 'README.txt', 'test','test_foobar.py'])) # Errors. code = 'plugin_quickstart(parser, options, args)' assert_raises(self, code, globals(), locals(), OSError, "Can't create directory '%s' because it already exists." % os.path.join(self.tdir, 'foobar')) argv = ['quickstart', 'foobar', 'stuff'] parser = _get_plugin_parser() options, args = parser.parse_known_args(argv) retval = plugin_quickstart(parser, options, args) self.assertEqual(retval, -1)
def test_base(self): logging.debug('') logging.debug('test_base') assert_raises(self, "ResourceAllocator('invalid-name')", globals(), locals(), NameError, "name 'invalid-name' is not alphanumeric") allocator = ResourceAllocator('dummy') self.assertEqual(allocator.name, 'dummy') # Just show they can be called. allocator.invalidate() allocator.configure('') retcode, info = \ allocator.check_compatibility({'remote_command': 'echo', 'no-such-key': True}) self.assertEqual(retcode, 0) self.assertEqual(info, ['no-such-key']) assert_raises(self, "allocator.max_servers(dict())", globals(), locals(), NotImplementedError, 'max_servers') assert_raises(self, "allocator.time_estimate(dict())", globals(), locals(), NotImplementedError, 'time_estimate') assert_raises(self, "allocator.deploy('xyzzy', dict(), dict())", globals(), locals(), NotImplementedError, 'deploy') assert_raises(self, "allocator.release(None)", globals(), locals(), NotImplementedError, 'release')
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_decorator(self): logging.debug('') logging.debug('test_decorator') # Decorated methods. obj = Object() methods = [name for name in dir(obj) if inspect.ismethod(getattr(obj, name))] methods.remove('no_rbac') self.assertEqual(sorted(rbac_methods(obj)), sorted(methods)) # Result proxying. normal_value = object() proxy_value = ProxyRequired() dummy = AccessController() self.assertFalse(need_proxy(obj.no_rbac, proxy_value, dummy)) self.assertFalse(need_proxy(obj.single_role, normal_value, dummy)) self.assertFalse(need_proxy(obj.proxy_result, normal_value, dummy)) self.assertTrue(need_proxy(obj.proxy_result, proxy_value, dummy)) # Access checking. assert_raises(self, "check_role('owner', obj.no_rbac)", globals(), locals(), RoleError, 'No RBAC for function!') assert_raises(self, "check_role('xyzzy', obj.single_role)", globals(), locals(), RoleError, "No access for role 'xyzzy'") check_role('owner', obj.multi_role) check_role('user', obj.multi_role) check_role('xyzzy', obj.role_pattern)
def test_close(self): # :memory: can be used after close. recorder = DBCaseRecorder() case = Case( inputs=[("str", "Normal String"), ("unicode", u"Unicode String"), ("list", ["Hello", "world"])] ) # Check pickling. recorder.record(case) recorder.close() recorder.record(case) # File-based DB recorder can not be used after close. tmpdir = tempfile.mkdtemp() try: dfile = os.path.join(tmpdir, "junk.db") recorder = DBCaseRecorder(dfile) recorder.record(case) recorder.close() assert_raises( self, "recorder.record(case)", globals(), locals(), RuntimeError, "Attempt to record on closed recorder" ) finally: try: shutil.rmtree(tmpdir) except OSError: logging.error("problem removing directory %s" % tmpdir)
def test_invalid_reconfig(self): # Test invalid reconfiguration of ArrayParameter. class MyComp(Component): x = Array([0, 0], iotype="in", dtype=float) y = Array([0, 0], iotype="out", dtype=float) def execute(self): self.y = self.x ** 2 class MyAssembly(Assembly): def configure(self): self.add("comp1", MyComp()) self.add("comp2", MyComp()) driver = self.add("driver", SLSQPdriver()) driver.add_parameter("comp1.x", low=-10, high=[10, 10]) driver.add_parameter("comp2.x", low=-10, high=10) driver.add_objective("comp1.y[0] + comp2.y[1]") asm = set_as_top(MyAssembly()) asm.comp1.x = [1, 2, 3] asm.comp2.x = [2.781828, 3.14159] assert_raises( self, "asm.run()", globals(), locals(), RuntimeError, "Parameter comp1.x can't be reconfigured," " 'high' was not specified as a scalar", )
def test_normal(self): logging.debug("") logging.debug("test_normal") dummy = "dummy_output" if os.path.exists(dummy): os.remove(dummy) extcode = set_as_top(ExternalCode()) extcode.timeout = 5 extcode.command = ["python", "sleep.py", "1", dummy] extcode.env_vars = {"SLEEP_DATA": "Hello world!"} extcode.external_files.extend( (FileMetadata(path="sleep.py", input=True), FileMetadata(path=dummy, output=True)) ) extcode.run() self.assertEqual(extcode.return_code, 0) self.assertEqual(extcode.timed_out, False) self.assertEqual(os.path.exists(dummy), True) with open(dummy, "r") as inp: data = inp.readline().rstrip() self.assertEqual(data, extcode.env_vars["SLEEP_DATA"]) # Now show that existing outputs are removed before execution. extcode.command = ["python", "sleep.py", "1"] extcode.run() msg = "[Errno 2] No such file or directory: 'dummy_output'" assert_raises(self, "open(dummy, 'r')", globals(), locals(), IOError, msg)
def test_close(self): self.top.driver.recorders = [CSVCaseRecorder(filename=self.filename)] self.top.run() case = Case(inputs=[('comp2.a_slot', None)]) assert_raises(self, 'self.top.driver.recorders[0].record(case)', globals(), locals(), RuntimeError, 'Attempt to record on closed recorder')
def test_badval(self): sout = StringIO() self.top.recorders = [JSONCaseRecorder(sout)] self.top.comp1.data = self.test_badval.__func__.__code__ assert_raises(self, 'self.top.run()', globals(), locals(), RuntimeError, "JSON write failed for simulation_info.constants:" " keys ['comp1.data']: <code object test_badval at")
def test_close(self): # :memory: can be used after close. recorder = DBCaseRecorder() case = Case(inputs=[('str', 'Normal String'), ('unicode', u'Unicode String'), ('list', ['Hello', 'world'])]) # Check pickling. recorder.record(case) recorder.close() recorder.record(case) # File-based DB recorder can not be used after close. tmpdir = tempfile.mkdtemp() try: dfile = os.path.join(tmpdir, 'junk.db') recorder = DBCaseRecorder(dfile) recorder.record(case) recorder.close() assert_raises(self, 'recorder.record(case)', globals(), locals(), RuntimeError, 'Attempt to record on closed recorder') finally: try: shutil.rmtree(tmpdir) except OSError: logging.error("problem removing directory %s" % tmpdir)
def test_close(self): # :memory: can be used after close. recorder = DBCaseRecorder() inps = ['str', 'unicode', 'list'] recorder.register(self, inps, []) inputs = ['Normal String', u'Unicode String', ['Hello', 'world']] recorder.record(self, inputs, [], None, '', '') recorder.close() recorder.record(self, inputs, [], None, '', '') # File-based DB recorder can not be used after close. tmpdir = tempfile.mkdtemp() try: dfile = os.path.join(tmpdir, 'junk.db') recorder = DBCaseRecorder(dfile) recorder.register(self, inps, []) recorder.record(self, inputs, [], None, '', '') recorder.close() code = "recorder.record(self, inputs, [], None, '', '')" assert_raises(self, code, globals(), locals(), RuntimeError, 'Attempt to record on closed recorder') finally: try: shutil.rmtree(tmpdir, onerror=onerror) except OSError: logging.error("problem removing directory %s", tmpdir)
def test_config(self): logging.debug('') logging.debug('test_config') # Try to read config from non-existent file. assert_raises(self, "read_server_config('no-such-file')", globals(), locals(), IOError, "No such file 'no-such-file'")
def test_badval(self): sout = StringIO() self.top.recorders = [JSONCaseRecorder(sout)] self.top.comp1.data = self.test_badval.__func__.__code__ assert_raises( self, 'self.top.run()', globals(), locals(), RuntimeError, "JSON write failed for simulation_info.constants:" " keys ['comp1.data']: <code object test_badval at")
def test_load_nofile(self): logging.debug('') logging.debug('test_load_nofile') # Try to load from nonexistant egg file. assert_raises(self, "Component.load_from_eggfile('no-such-egg')", globals(), locals(), ValueError, "'no-such-egg' not found.")
def test_load_badfile(self): logging.debug('') logging.debug('test_load_badfile') # Try to load from non-egg. assert_raises(self, "Component.load_from_eggfile('.')", globals(), locals(), ValueError, "'.' is not an egg/zipfile.")
def test_load_nopackage(self): logging.debug('') logging.debug('test_load_nopackage') # Try to load from nonexistant egg package. assert_raises(self, "Component.load_from_eggpkg('no-such-egg')", globals(), locals(), pkg_resources.DistributionNotFound, 'no-such-egg')
def test_close(self): self.top.driver.recorders = [CSVCaseRecorder(filename=self.filename)] self.top.driver.recorders[0].num_backups = 0 self.top.run() case = Case(inputs=[('comp2.a_slot', None)]) assert_raises(self, 'self.top.driver.recorders[0].record(case)', globals(), locals(), RuntimeError, 'Attempt to record on closed recorder')
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_shell(self): logging.debug('') logging.debug('test_shell') testdir = 'test_shell' if os.path.exists(testdir): shutil.rmtree(testdir, onerror=onerror) os.mkdir(testdir) os.chdir(testdir) try: # Create a server. server = ObjServer(allow_shell=True) # Execute a command. if sys.platform == 'win32': cmd = 'cmd' args = ['/c', 'dir'] else: cmd = 'ls' args = [] rdesc = { 'remote_command': cmd, 'args': args, 'output_path': 'cmd.out' } return_code, error_msg = server.execute_command(rdesc) self.assertEqual(return_code, 0) # Bad command, specify lots of resources. with open('stdin1', 'w') as out: out.write('z') rdesc = { 'remote_command': 'no-such-command', 'args': ['a', 'b', 'c'], 'input_path': 'stdin1', 'error_path': 'stderr1', 'wallclock_time': 10 } if sys.platform == 'win32': msg = '[Error 2] The system cannot find the file specified' else: msg = '[Errno 2] No such file or directory' assert_raises(self, 'server.execute_command(rdesc)', globals(), locals(), OSError, msg) # Load a model. exec_comp = server.create('openmdao.test.execcomp.ExecComp') exec_comp.run() egg_info = exec_comp.save_to_egg('exec_comp', '0') obj = server.load_model(egg_info[0]) obj.run() assert_raises(self, "server.load_model('no-such-egg')", globals(), locals(), ValueError, "'no-such-egg' not found.") finally: SimulationRoot.chroot('..') shutil.rmtree(testdir, onerror=onerror)
def test_save_bad_method(self): logging.debug('') logging.debug('test_save_bad_method') # Set reference to unpickleable static method. self.model.Oddball.method_socket = self.model.Oddball.static_method code = 'self.model.save_to_egg(self.model.name, next_egg(), py_dir=PY_DIR)' assert_raises(self, code, globals(), locals(), RuntimeError, "Egg_TestModel: Can't save, 1 object cannot be pickled.")
def test_expr(self): cases = ( Case(inputs=(('comp1.a', 4),), outputs=(('comp2.b', 3),), msg=None), Case(inputs=(('comp1.a', 6),), outputs=(('comp2.b', 3),), msg='failed'), Case(inputs=(('comp1.a', 4),), outputs=(('comp2.b', 2),), msg=None), ) # By sequence number. filter = ExprCaseFilter('seqno > 1') accepted = [] for seqno, case in enumerate(cases): if filter.select(seqno, case): accepted.append(seqno) self.assertEqual(accepted, [2]) # Simple variable test. filter = ExprCaseFilter("case['comp1.a'] < 5") accepted = [] for seqno, case in enumerate(cases): if filter.select(seqno, case): accepted.append(seqno) self.assertEqual(accepted, [0, 2]) # Two variable test. filter = ExprCaseFilter("case['comp1.a'] < 5 and case['comp2.b'] > 2") accepted = [] for seqno, case in enumerate(cases): if filter.select(seqno, case): accepted.append(seqno) self.assertEqual(accepted, [0]) # Failed evaluations. filter = ExprCaseFilter('case.msg') accepted = [] for seqno, case in enumerate(cases): if filter.select(seqno, case): accepted.append(seqno) self.assertEqual(accepted, [1]) # Missing variable. filter = ExprCaseFilter("case['comp1.z'] < 5") assert_raises(self, 'filter.select(0, cases[0])', globals(), locals(), KeyError, '\'Can\\\'t evaluate expression "case[\\\'comp1.z\\\'] < 5":' ' \\\'comp1.z\\\'') # Bad expression. assert_raises(self, """ExprCaseFilter("case['comp1.z] < 5")""", globals(), locals(), SyntaxError, 'Can\'t compile expression "case[\'comp1.z] < 5":' ' EOL while scanning ')
def test_save_bad_filevar(self): logging.debug('') logging.debug('test_save_bad_filevar') # Set file trait path outside model root. self.model.Source.text_file = FileRef('/illegal') code = 'self.model.save_to_egg(self.model.name, next_egg(), py_dir=PY_DIR)' msg = "Egg_TestModel: Can't save, Egg_TestModel.Source.text_file path" assert_raises(self, code, globals(), locals(), ValueError, msg)
def test_4_authkey(self): logging.debug('') logging.debug('test_authkey') factory = self.start_factory() # Start server in non-public-key mode. # Connections must have matching authkey, # but data is sent in the clear!? # This is standard multiprocessing behaviour. authkey = 'password' server_dir = 'Factory_authkey' if os.path.exists(server_dir): shutil.rmtree(server_dir) os.mkdir(server_dir) os.chdir(server_dir) self.server_dirs.append(server_dir) try: logging.debug('starting server (authkey %s)...', authkey) allowed_types = ['openmdao.main.test.test_distsim.Box'] server = start_server(authkey=authkey, allowed_types=allowed_types, timeout=30) address, port, key = read_server_config('server.cfg') logging.debug('server address: %s', address) logging.debug('server port: %s', port) logging.debug('server key: %s', key) finally: os.chdir('..') factory = None try: assert_raises(self, 'connect(address, port, pubkey=key)', globals(), locals(), AuthenticationError, 'digest sent was rejected') factory = connect(address, port, authkey=authkey) logging.debug('factory: %r', factory) # Create model and run it. box = factory.create(_MODULE+'.Box') model = set_as_top(Model(box)) model.run() # Check results. for width in range(1, 2): for height in range(1, 3): for depth in range(1, 4): case = model.driver.recorder.cases.pop(0) self.assertEqual(case.outputs[0][2], width*height*depth) finally: if factory is not None: factory.cleanup() logging.debug('terminating server (authkey %s) pid %s', authkey, server.pid) server.terminate(timeout=10) server = None
def test_save_bad_directory(self): logging.debug('') logging.debug('test_save_bad_directory') # Set subcomponent directory outside model root. self.model.Oddball.directory = os.getcwd() code = 'self.model.save_to_egg(self.model.name, next_egg(), py_dir=PY_DIR)' msg = "Egg_TestModel: Can't save, Egg_TestModel.Oddball.oddcomp" \ " directory" assert_raises(self, code, globals(), locals(), ValueError, msg)
def test_illegal_src(self): logging.debug('') logging.debug('test_illegal_src') # Set illegal path (during execution of sink), verify error message. self.model.sink.bogus_path = '/illegal' code = 'self.model.run()' msg = "middle.passthrough (1-2.1-1): Illegal path '/illegal'," \ " not a descendant of" assert_raises(self, code, globals(), locals(), ValueError, msg)
def test_variabletree(self): # Ensure VariableTree is rejected. msg = 'Slotting of VariableTrees is not supported,' \ ' please use VarTree instead' code = 'Slot(VariableTree)' assert_raises(self, code, globals(), locals(), TypeError, msg) code = 'Slot(VariableTree())' assert_raises(self, code, globals(), locals(), TypeError, msg)
def test_bad_value(self): logging.debug('') logging.debug('test_bad_value') code = 'self.model.source.text_file = 42' msg = "The 'text_file' trait of a Source instance must be" \ " a legal value, but a value of 42 <type 'int'> was" \ " specified." assert_raises(self, code, globals(), locals(), TraitError, msg, use_exec=True)
def test_load_nopackage(self): raise nose.SkipTest("Test needs to be re-evaluated, understood by someone other than setowns1.") logging.debug('') logging.debug('test_load_nopackage') # Try to load from nonexistant egg package. assert_raises(self, "Component.load_from_eggpkg('no-such-egg')", globals(), locals(), pkg_resources.DistributionNotFound, 'no-such-egg')
def test_bad_alloc(self): logging.debug('') logging.debug('test_bad_alloc') extcode = set_as_top(ExternalCode()) extcode.command = ['python', 'sleep.py'] extcode.resources = {'allocator': 'LocalHost', 'localhost': False} assert_raises(self, 'extcode.run()', globals(), locals(), RuntimeError, ': Server allocation failed')
def test_transform_bad_wolf(self): code = "self.top.driver.add_parameter('comp.a', low=8.6, high=9.4, scaler='bad', adder=1.0)" assert_raises(self, code, globals(), locals(), ValueError, "driver: Bad value given for parameter's 'scaler'" " attribute.") code = "self.top.driver.add_parameter('comp.a', low=8.6, high=9.4, scaler=1.0, adder='wolf')" assert_raises(self, code, globals(), locals(), ValueError, "driver: Bad value given for parameter's 'adder'" " attribute.")
def test_build_docs(self): logging.debug('') logging.debug('test_build_docs') argv = ['quickstart', 'foobar', '-v', '1.1', '-d', self.tdir] parser = _get_plugin_parser() options, args = parser.parse_known_args(argv) plugin_quickstart(parser, options, args) orig_dir = os.getcwd() os.chdir(os.path.join(self.tdir, 'foobar')) orig_stdout = sys.stdout orig_stderr = sys.stderr sys.stdout = cStringIO.StringIO() sys.stderr = cStringIO.StringIO() try: argv = ['build_docs', 'foobar'] parser = _get_plugin_parser() options, args = parser.parse_known_args(argv) retval = plugin_build_docs(parser, options, args) self.assertEqual(retval, 0) finally: captured_stdout = sys.stdout.getvalue() captured_stderr = sys.stderr.getvalue() sys.stdout = orig_stdout sys.stderr = orig_stderr os.chdir(orig_dir) logging.debug('captured stdout:') logging.debug(captured_stdout) logging.debug('captured stderr:') logging.debug(captured_stderr) # Errors. argv = ['build_docs', 'foobar', 'no-such-directory', 'stuff'] parser = _get_plugin_parser() options, args = parser.parse_known_args(argv) retval = plugin_build_docs(parser, options, args) self.assertEqual(retval, -1) argv = ['build_docs', 'foobar', 'no-such-directory'] parser = _get_plugin_parser() options, args = parser.parse_known_args(argv) code = 'plugin_build_docs(parser, options, args)' distdir = os.path.join(os.getcwd(), 'no-such-directory') assert_raises(self, code, globals(), locals(), IOError, "directory '%s' does not exist" % distdir) distdir = os.path.join(self.tdir, 'foobar') os.remove(os.path.join(distdir, 'setup.py')) argv = ['build_docs', 'foobar', distdir] parser = _get_plugin_parser() options, args = parser.parse_known_args(argv) code = 'plugin_build_docs(parser, options, args)' assert_raises(self, code, globals(), locals(), IOError, "directory '%s' does not contain 'setup.py'" % distdir)
def test_noresource(self): logging.debug('') logging.debug('test_noresource') # Check response to unsupported resource. self.model.driver.extra_reqs = {'no-such-resource': 0} self.model.driver.sequential = False self.model.driver.iterator = ListCaseIterator([]) assert_raises(self, 'self.model.run()', globals(), locals(), RuntimeError, 'driver: No servers supporting required resources')
def test_collision(self): logging.debug('') logging.debug('test_collision') vsp = set_as_top(VSP('hwb.xml')) vsp.generate_cfd_mesh = True vsp.write_nascart = True msg = ': CFD meshing and NASCART output use the same output filenames' assert_raises(self, 'vsp.run()', globals(), locals(), RuntimeError, msg)
def test_basic(self): comp = TestComponent() code = "VarTree(InputTree)" msg = "default_value must be an instance of VariableTree or subclass" assert_raises(self, code, globals(), locals(), TypeError, msg) code = "comp.input = OutputTree()" msg = ": 'input' must be an instance of %s.%s" \ % (InputTree.__module__, InputTree.__name__) assert_raises(self, code, globals(), locals(), TypeError, msg, use_exec=True)
def test_transform_bad_wolf(self): code = "self.top.driver.add_parameter('comp.a', low=8.6, high=9.4, scaler='bad', adder=1.0)" assert_raises( self, code, globals(), locals(), ValueError, "driver: Bad value given for parameter's 'scaler'" " attribute.") code = "self.top.driver.add_parameter('comp.a', low=8.6, high=9.4, scaler=1.0, adder='wolf')" assert_raises( self, code, globals(), locals(), ValueError, "driver: Bad value given for parameter's 'adder'" " attribute.")
def test_noresource(self): logging.debug('') logging.debug('test_noresource') # Check response to unsupported resource. self.model.driver.extra_resources = { 'allocator': 'LocalHost', 'localhost': False } self.model.driver.sequential = False assert_raises(self, 'self.model.run()', globals(), locals(), RuntimeError, 'driver: No servers supporting required resources')
def test_add_broadcast_params(self): driver = self.top.driver driver.add_parameter(('comp.x', 'comp.y'), low=0., high=1e99) code = "driver.add_parameter(('comp.x', 'comp.y'), low=0., high=1e99)" assert_raises( self, code, globals(), locals(), ValueError, "driver: ['comp.x', 'comp.y'] are already" " Parameter targets") targets = driver.list_param_targets() self.assertEqual(frozenset(targets), frozenset(['comp.x', 'comp.y'])) code = "driver.remove_parameter('comp.foo')" assert_raises( self, code, globals(), locals(), AttributeError, "driver: Trying to remove parameter 'comp.foo'" " that is not in this driver.") code = "driver.remove_parameter(('comp.x', 'comp.foo'))" assert_raises( self, code, globals(), locals(), AttributeError, "driver: Trying to remove parameter '('comp.x'," " 'comp.foo')' that is not in this driver.") driver.remove_parameter(('comp.x', 'comp.y')) self.assertEqual([], driver.list_param_targets()) code = "driver.add_parameter(('comp.x+comp.y', 'comp.x'), low=0, high=1.e99)" assert_raises( self, code, globals(), locals(), ValueError, "driver: Can't add parameter: 'comp.x+comp.y' is" " not a valid parameter expression")
def test_nesting(self): # Check direct nesting in class definition. code = 'vt2 = BadVT2()' msg = 'Nested VariableTrees are not supported,' \ ' please wrap BadVT2.vt3 in a VarTree' assert_raises(self, code, globals(), locals(), TypeError, msg, use_exec=True) # Check direct nesting via add(). vt3 = DumbVT3() vt3.add('ok', VarTree(DumbVT3())) code = "vt3.add('bad', DumbVT3())" msg = ': a VariableTree may only contain Variables or VarTrees' assert_raises(self, code, globals(), locals(), TypeError, msg)
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 test_collision(self): logging.debug('') logging.debug('test_collision') g = set_as_top(GeomComponent()) g.add("parametric_geometry", VSPParametricGeometry()) g.parametric_geometry.model_file = os.path.join(TESTDIR, 'hwb.xml') g.vsp_path = VSP_PATH g.generate_cfd_mesh = True g.write_nascart = True msg = ': CFD meshing and NASCART output use the same output filenames' assert_raises(self, 'g.run()', globals(), locals(), Exception, msg)
def test_single_bogus(self): code = "self.top.driver.add_parameter('comp.bogus', 0., 1.e99)" assert_raises( self, code, globals(), locals(), AttributeError, "driver: Can't add parameter 'comp.bogus' because" " it doesn't exist.") code = "self.top.driver.add_parameter('zr()', 0., 1.e99)" assert_raises( self, code, globals(), locals(), ValueError, "driver: Can't add parameter: 'zr()' is not a" " valid parameter expression") code = "self.top.driver.add_parameter('comp.x', 0., 1.e99, scope='bogus')" assert_raises( self, code, globals(), locals(), TypeError, "driver: Can't add parameter: cannot create weak" " reference to 'str' object") self.top.comp.add_trait('vstr', Str('Hey', iotype='in')) code = "self.top.driver.add_parameter('comp.vstr', 0., 1.e99)" assert_raises( self, code, globals(), locals(), ValueError, "driver: The value of parameter 'comp.vstr' must" " be a real or integral type, but its type is 'str'.")
def test_errors(self): # Test base error responses. logging.debug('') logging.debug('test_errors') top = set_as_top(SensitivityStudy()) top.driver.clear_objectives() assert_raises(self, 'top.run()', globals(), locals(), ValueError, 'driver: No objectives, run aborted') top.driver.clear_parameters() assert_raises(self, 'top.run()', globals(), locals(), ValueError, 'driver: No parameters, run aborted')
def test_vector(self): # Test DakotaVectorStudy driver. logging.debug('') logging.debug('test_vector') top = VectorStudy() top.run() assert_rel_error(self, top.rosenbrock.x[0], 1.1, 0.00001) assert_rel_error(self, top.rosenbrock.x[1], 1.3, 0.00001) assert_rel_error(self, top.rosenbrock.f, 0.82, 0.00001) top.driver.final_point = [1.1, 1.3, 999] assert_raises(self, 'top.run()', globals(), locals(), ValueError, 'driver: #final_point (3) != #parameters (2)')
def test_multidim(self): # Test DakotaMultidimStudy driver. logging.debug('') logging.debug('test_multidim') top = ParameterStudy() top.run() self.assertEqual(top.rosenbrock.x[0], 2) self.assertEqual(top.rosenbrock.x[1], 2) self.assertEqual(top.rosenbrock.f, 401) top.driver.partitions = [8, 8, 999] assert_raises(self, 'top.run()', globals(), locals(), ValueError, 'driver: #partitions (3) != #parameters (2)')