def setUp(self):
     """ Called before each test in this class. """
     
     if not find_in_path(VSP_PATH):
         raise nose.SkipTest('VSP must be installed to run this test.')
     os.chdir(TestCase.directory)
     SimulationRoot.chroot(os.getcwd())
Exemple #2
0
    def setUp(self):
        """ Called before each test in this class. """

        if not find_in_path(VSP_PATH):
            raise nose.SkipTest('VSP must be installed to run this test.')
        os.chdir(TestCase.directory)
        SimulationRoot.chroot(os.getcwd())
    def __init__(self, name='', allow_shell=False, allowed_types=None):
        self._allow_shell = allow_shell
        if allowed_types is None:
            allowed_types = [typname for typname, version
                                      in get_available_types()]
        self._allowed_types = allowed_types

        self.host = platform.node()
        self.pid = os.getpid()
        self.name = name or ('sim-%d' % self.pid)
        self.version = __version__

        self._root_dir = os.getcwd()
        self._logger = logging.getLogger(self.name)
        self._logger.info('PID: %d, allow_shell %s',
                          os.getpid(), self._allow_shell)
        print '%s %r PID: %d, allow_shell %s' \
              % (self.__class__.__name__, self.name, os.getpid(),
                 self._allow_shell)
        sys.stdout.flush()

        SimulationRoot.chroot(self._root_dir)
        self.tlo = None

        # Ensure Traits Array support is initialized. The code contains
        # globals for numpy symbols that are initialized within
        # AbstractArray.__init__() which won't be executed if we simply
        # load up egg state (or don't do a real fork, like Windows).
        try:
            import numpy
        except ImportError:
            pass
        else:
            from traits.trait_numeric import AbstractArray
            dummy = AbstractArray()
    def __init__(self, name='', allow_shell=False, allowed_types=None):
        self._allow_shell = allow_shell
        if allowed_types is None:
            allowed_types = [typname for typname, version
                                      in get_available_types()]
        self._allowed_types = allowed_types

        self.host = platform.node()
        self.pid = os.getpid()
        self.name = name or ('sim-%d' % self.pid)
        self.version = __version__

        self._root_dir = os.getcwd()
        self._logger = logging.getLogger(self.name)
        self._logger.info('PID: %d, allow_shell %s',
                          os.getpid(), self._allow_shell)
        print '%s %r PID: %d, allow_shell %s' \
              % (self.__class__.__name__, self.name, os.getpid(),
                 self._allow_shell)
        sys.stdout.flush()

        SimulationRoot.chroot(self._root_dir)
        self.tlo = None

        # Ensure Traits Array support is initialized. The code contains
        # globals for numpy symbols that are initialized within
        # AbstractArray.__init__() which won't be executed if we simply
        # load up egg state (or don't do a real fork, like Windows).
        try:
            import numpy
        except ImportError:
            pass
        else:
            from enthought.traits.trait_numeric import AbstractArray
            dummy = AbstractArray()
 def tearDown(self):
     try:
         shutil.rmtree(self.tdir, onerror=onerror)
     except:
         pass
     finally:
         os.chdir(self.startdir)
         SimulationRoot.chroot(os.getcwd())
Exemple #6
0
    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_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 tearDown(self):
     """ Remove output files. """
     try:
         for pattern in ('*.3dm', '*.bac', '*.bsf', '*.fel', '*.hrm', '*.log',
                        '*.new', '*.stl',
                        'bodyin.*', 'cfdmesh.*', 'comp_geom.*'):
             for name in glob.glob(pattern):
                 os.remove(name)
     finally:
         os.chdir(ORIG_DIR)
         SimulationRoot.chroot(os.getcwd())
 def activate(self):
     """Make this project active by putting its directory on sys.path and
     executing its macro.
     """
     # set SimulationRoot and put our path on sys.path
     SimulationRoot.chroot(self.path)
     add_proj_to_path(self.path)
         
     # set up the model
     self._init_globals()
     self._initialize()
Exemple #10
0
    def activate(self):
        """Make this project active by putting its directory on sys.path and
        executing its macro.
        """
        # set SimulationRoot and put our path on sys.path
        SimulationRoot.chroot(self.path)
        add_proj_to_path(self.path)

        # set up the model
        self._init_globals()
        self._initialize()
Exemple #11
0
 def tearDown(self):
     """ Remove output files. """
     try:
         for pattern in ('*.3dm', '*.bac', '*.bsf', '*.fel', '*.hrm',
                         '*.log', '*.new', '*.stl', 'bodyin.*', 'cfdmesh.*',
                         'comp_geom.*'):
             for name in glob.glob(pattern):
                 os.remove(name)
     finally:
         os.chdir(ORIG_DIR)
         SimulationRoot.chroot(os.getcwd())
    def test_factory(self):
        logging.debug("")
        logging.debug("test_factory")

        testdir = "test_factory"
        if os.path.exists(testdir):
            shutil.rmtree(testdir)
        os.mkdir(testdir)
        os.chdir(testdir)

        factory = None
        try:
            # Create a factory.
            factory = ObjServerFactory()

            # Echo some arguments.
            args = factory.echo("Hello", "world!")
            self.assertEqual(args[0], "Hello")
            self.assertEqual(args[1], "world!")

            # List types.
            types = factory.get_available_types()
            names = [name for name, version in types]
            self.assertTrue("openmdao.test.execcomp.ExecComp" in names)

            # Create a component.
            exec_comp = factory.create("openmdao.test.execcomp.ExecComp")
            exec_comp.run()

            # Force failed factory server startup via invalid port.
            assert_raises(
                self, "start_server(port='xyzzy')", globals(), locals(), RuntimeError, "Server startup failed"
            )

            # Try to release a server that doesn't exist (release takes an
            # OpenMDAO_Proxy as argument, string here is easier).
            assert_raises(
                self,
                "factory.release('xyzzy')",
                globals(),
                locals(),
                ValueError,
                "can't identify server at 'not-a-proxy'",
            )
        finally:
            if factory is not None:
                factory.cleanup()
            SimulationRoot.chroot("..")
            if sys.platform == "win32":
                time.sleep(2)  # Wait for process shutdown.
            keep_dirs = int(os.environ.get("OPENMDAO_KEEPDIRS", "0"))
            if not keep_dirs:
                shutil.rmtree(testdir)
    def test_factory(self):
        logging.debug('')
        logging.debug('test_factory')

        testdir = 'test_factory'
        if os.path.exists(testdir):
            shutil.rmtree(testdir)
        os.mkdir(testdir)
        os.chdir(testdir)

        factory = None
        try:
            # Create a factory.
            factory = ObjServerFactory()

            # Echo some arguments.
            args = factory.echo('Hello', 'world!')
            self.assertEqual(args[0], 'Hello')
            self.assertEqual(args[1], 'world!')

            # List types.
            types = factory.get_available_types()
            names = [name for name, version in types]
            self.assertTrue('openmdao.test.execcomp.ExecComp' in names)

            # Create a component.
            exec_comp = factory.create('openmdao.test.execcomp.ExecComp')
            exec_comp.run()

            # Force failed factory server startup via invalid port.
            assert_raises(self, "start_server(port='xyzzy')", globals(),
                          locals(), RuntimeError, 'Server startup failed')

            # Try to release a server that doesn't exist (release takes an
            # OpenMDAO_Proxy as argument, string here is easier).
            assert_raises(self, "factory.release('xyzzy')", globals(),
                          locals(), ValueError,
                          "can't identify server at 'not-a-proxy'")
        finally:
            if factory is not None:
                factory.cleanup()
            SimulationRoot.chroot('..')
            if sys.platform == 'win32':
                time.sleep(2)  # Wait for process shutdown.
            keep_dirs = int(os.environ.get('OPENMDAO_KEEPDIRS', '0'))
            if not keep_dirs:
                shutil.rmtree(testdir)
    def test_shell(self):
        logging.debug('')
        logging.debug('test_shell')

        testdir = 'test_shell'
        if os.path.exists(testdir):
            shutil.rmtree(testdir)
        os.mkdir(testdir)
        os.chdir(testdir)

        try:
            # Create a server.
            server = ObjServer(allow_shell=True)

            # Execute a command.
            cmd = 'dir' if sys.platform == 'win32' else 'ls'
            rdesc = {
                'remote_command': cmd,
                'output_path': 'cmd.out',
                'hard_runtime_limit': 10
            }
            return_code, error_msg = server.execute_command(rdesc)
            self.assertEqual(return_code, 0)

            # Non-zero return code.
            rdesc = {
                'remote_command': 'no-such-command',
                'output_path': 'stdout1',
                'error_path': 'stderr1',
                'hard_runtime_limit': 10
            }
            return_code, error_msg = server.execute_command(rdesc)
            self.assertNotEqual(return_code, 0)

            # 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)
    def test_shell(self):
        logging.debug("")
        logging.debug("test_shell")

        testdir = "test_shell"
        if os.path.exists(testdir):
            shutil.rmtree(testdir)
        os.mkdir(testdir)
        os.chdir(testdir)

        try:
            # Create a server.
            server = ObjServer(allow_shell=True)

            # Execute a command.
            cmd = "dir" if sys.platform == "win32" else "ls"
            rdesc = {"remote_command": cmd, "output_path": "cmd.out", "hard_runtime_limit": 10}
            return_code, error_msg = server.execute_command(rdesc)
            self.assertEqual(return_code, 0)

            # Non-zero return code.
            rdesc = {
                "remote_command": "no-such-command",
                "output_path": "stdout1",
                "error_path": "stderr1",
                "hard_runtime_limit": 10,
            }
            return_code, error_msg = server.execute_command(rdesc)
            self.assertNotEqual(return_code, 0)

            # 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)
    def __init__(self, name='', allow_shell=False, allowed_types=None):
        self._allow_shell = allow_shell
        if allowed_types is None:
            allowed_types = [typname for typname, version
                                      in get_available_types()]
        self._allowed_types = allowed_types

        self.host = platform.node()
        self.pid = os.getpid()
        self.name = name or ('sim-%d' % self.pid)

        self._root_dir = os.getcwd()
        self._logger = logging.getLogger(self.name)
        self._logger.info('PID: %d, allow_shell %s',
                          os.getpid(), self._allow_shell)
        print 'ObjServer %r PID: %d, allow_shell %s' \
              % (self.name, os.getpid(), self._allow_shell)
        sys.stdout.flush()

        SimulationRoot.chroot(self._root_dir)
        self.tlo = None
Exemple #17
0
                except Exception, e:
                    print 'Unable to restore project state:', e
                    self.top = Assembly()
            else:
                self.top = set_as_top(Assembly())

            self.path = expand_path(
                projpath)  # set again in case loading project state changed it
        else:  # new project
            os.makedirs(projpath)
            os.mkdir(modeldir)
            self.top = set_as_top(Assembly())

        self.save()

        SimulationRoot.chroot(self.path)

    @property
    def name(self):
        return os.path.basename(self.path)

    def activate(self):
        """Puts this project's directory on sys.path."""
        if self.path not in sys.path:
            sys.path = [self.path] + sys.path

    def deactivate(self):
        """Removes this project's directory from sys.path."""
        try:
            sys.path.remove(self.path)
        except:
 def setUp(self):
     self.startdir = os.getcwd()
     self.tdir = tempfile.mkdtemp()
     os.chdir(self.tdir)
     SimulationRoot.chroot(self.tdir)
    def test_server(self):
        logging.debug('')
        logging.debug('test_server')

        testdir = 'test_server'
        if os.path.exists(testdir):
            shutil.rmtree(testdir)
        os.mkdir(testdir)
        os.chdir(testdir)

        try:
            # Create a server.
            server = ObjServer()

            # Create a component.
            exec_comp = server.create('openmdao.test.execcomp.ExecComp')
            exec_comp.run()
            egg_info = exec_comp.save_to_egg('exec_comp', '0')

            # Echo some arguments.
            args = server.echo('Hello', 'world!')
            self.assertEqual(args[0], 'Hello')
            self.assertEqual(args[1], 'world!')

            # Try to execute a command.
            cmd = 'dir' if sys.platform == 'win32' else 'ls'
            rdesc = {
                'remote_command': cmd,
                'output_path': 'cmd.out',
                'hard_runtime_limit': 10
            }
            code = 'server.execute_command(rdesc)'
            assert_raises(self, code, globals(), locals(), RuntimeError,
                          'shell access is not allowed by this server')

            # Try to load a model.
            assert_raises(self, 'server.load_model(egg_info[0])', globals(),
                          locals(), RuntimeError,
                          'shell access is not allowed by this server')

            # Bogus file accesses.
            assert_raises(self, "server.open('../xyzzy', 'r')", globals(),
                          locals(), RuntimeError,
                          "Can't open '../xyzzy', not within root ")
            assert_raises(self, "server.open('xyzzy', 'r')", globals(),
                          locals(), IOError,
                          "[Errno 2] No such file or directory: 'xyzzy'")

            # Create a file using context.
            with server.open('xyzzy', 'w') as out:
                out.write('Hello world!\n')

            # Create another file using file proxy.
            out = server.open('fred', 'w')
            out.write('Hello fred!\n')
            out.flush()  # Not really necessary, just for coverage.
            out.close()

            # Zip it.
            server.pack_zipfile(['xyzzy', 'fred'], 'zipped')

            # Make it read-only.
            server.chmod('zipped', 0400)

            if sys.platform == 'win32':
                msg = '[Error 2] The system cannot find the file specified'
            else:
                msg = "[Errno 2] No such file or directory: 'no-such-file'"
            assert_raises(self, "server.chmod('no-such-file', 0400)",
                          globals(), locals(), OSError, msg)

            # Get stats.
            info = server.stat('zipped')

            assert_raises(self, "server.stat('no-such-file')", globals(),
                          locals(), OSError, msg)

            # Remove zipped contents.
            server.remove('xyzzy')
            server.remove('fred')

            if sys.platform == 'win32':
                msg = '[Error 2] The system cannot find the file specified'
            else:
                msg = "[Errno 2] No such file or directory: 'xyzzy'"
            assert_raises(self, "server.remove('xyzzy')", globals(), locals(),
                          OSError, msg)

            # Unpack.
            server.unpack_zipfile('zipped')
            server.chmod('zipped', 0600)  # Ensure we can remove under Windows.

            # Verify contents.
            with server.open('xyzzy', 'r') as inp:
                data = inp.read()
                self.assertEqual(data, 'Hello world!\n')

            inp = server.open('fred', 'r')
            try:
                data = inp.read(1000)
                self.assertEqual(data, 'Hello fred!\n')
            finally:
                inp.close()

            # Try to create a process.
            args = 'dir' if sys.platform == 'win32' else 'ls'
            try:
                proc = server.create('subprocess.Popen', args=args, shell=True)
                proc.wait()
            except TypeError as exc:
                msg = "'subprocess.Popen' is not an allowed type"
                self.assertEqual(str(exc), msg)
            else:
                self.fail('Expected TypeError')

        finally:
            SimulationRoot.chroot('..')
            shutil.rmtree(testdir)
                        self.__dict__ = pickle.load(f)
                except Exception, e:
                    print 'Unable to restore project state:',e
                    self.top = Assembly()
            else:
                self.top = set_as_top(Assembly())
            
            self.path = expand_path(projpath) # set again in case loading project state changed it
        else:  # new project
            os.makedirs(projpath)
            os.mkdir(modeldir)
            self.top = set_as_top(Assembly())
            
        self.save()

        SimulationRoot.chroot(self.path)

    @property
    def name(self):
        return os.path.basename(self.path)
    
    def activate(self):
        """Puts this project's directory on sys.path."""
        if self.path not in sys.path:
            sys.path = [self.path]+sys.path
        
    def deactivate(self):
        """Removes this project's directory from sys.path."""
        try:
            sys.path.remove(self.path)
        except:
    def test_server(self):
        logging.debug("")
        logging.debug("test_server")

        testdir = "test_server"
        if os.path.exists(testdir):
            shutil.rmtree(testdir)
        os.mkdir(testdir)
        os.chdir(testdir)

        try:
            # Create a server.
            server = ObjServer()

            # Create a component.
            exec_comp = server.create("openmdao.test.execcomp.ExecComp")
            exec_comp.run()
            egg_info = exec_comp.save_to_egg("exec_comp", "0")

            # Echo some arguments.
            args = server.echo("Hello", "world!")
            self.assertEqual(args[0], "Hello")
            self.assertEqual(args[1], "world!")

            # Try to execute a command.
            cmd = "dir" if sys.platform == "win32" else "ls"
            rdesc = {"remote_command": cmd, "output_path": "cmd.out", "hard_runtime_limit": 10}
            code = "server.execute_command(rdesc)"
            assert_raises(self, code, globals(), locals(), RuntimeError, "shell access is not allowed by this server")

            # Try to load a model.
            assert_raises(
                self,
                "server.load_model(egg_info[0])",
                globals(),
                locals(),
                RuntimeError,
                "shell access is not allowed by this server",
            )

            # Bogus file accesses.
            assert_raises(
                self,
                "server.open('../xyzzy', 'r')",
                globals(),
                locals(),
                RuntimeError,
                "Can't open '../xyzzy', not within root ",
            )
            assert_raises(
                self,
                "server.open('xyzzy', 'r')",
                globals(),
                locals(),
                IOError,
                "[Errno 2] No such file or directory: 'xyzzy'",
            )

            # Create a file using context.
            with server.open("xyzzy", "w") as out:
                out.write("Hello world!\n")

            # Create another file using file proxy.
            out = server.open("fred", "w")
            out.write("Hello fred!\n")
            out.flush()  # Not really necessary, just for coverage.
            out.close()

            # Zip it.
            server.pack_zipfile(["xyzzy", "fred"], "zipped")

            # Make it read-only.
            server.chmod("zipped", 0400)

            if sys.platform == "win32":
                msg = "[Error 2] The system cannot find the file specified"
            else:
                msg = "[Errno 2] No such file or directory: 'no-such-file'"
            assert_raises(self, "server.chmod('no-such-file', 0400)", globals(), locals(), OSError, msg)

            # Get stats.
            info = server.stat("zipped")

            assert_raises(self, "server.stat('no-such-file')", globals(), locals(), OSError, msg)

            # Remove zipped contents.
            server.remove("xyzzy")
            server.remove("fred")

            if sys.platform == "win32":
                msg = "[Error 2] The system cannot find the file specified"
            else:
                msg = "[Errno 2] No such file or directory: 'xyzzy'"
            assert_raises(self, "server.remove('xyzzy')", globals(), locals(), OSError, msg)

            # Unpack.
            server.unpack_zipfile("zipped")
            server.chmod("zipped", 0600)  # Ensure we can remove under Windows.

            # Verify contents.
            with server.open("xyzzy", "r") as inp:
                data = inp.read()
                self.assertEqual(data, "Hello world!\n")

            inp = server.open("fred", "r")
            try:
                data = inp.read(1000)
                self.assertEqual(data, "Hello fred!\n")
            finally:
                inp.close()

            # Try to create a process.
            args = "dir" if sys.platform == "win32" else "ls"
            try:
                proc = server.create("subprocess.Popen", args=args, shell=True)
                proc.wait()
            except TypeError as exc:
                msg = "'subprocess.Popen' is not an allowed type"
                self.assertEqual(str(exc), msg)
            else:
                self.fail("Expected TypeError")

        finally:
            SimulationRoot.chroot("..")
            shutil.rmtree(testdir)
Exemple #22
0
    def test_factory(self):
        logging.debug('')
        logging.debug('test_factory')

        testdir = 'test_factory'
        if os.path.exists(testdir):
            shutil.rmtree(testdir, onerror=onerror)
        os.mkdir(testdir)
        os.chdir(testdir)

        factory = None
        try:
            # Create a factory.
            factory = ObjServerFactory()

            # Echo some arguments.
            args = factory.echo('Hello', 'world!')
            self.assertEqual(args[0], 'Hello')
            self.assertEqual(args[1], 'world!')

            # List types.
            types = factory.get_available_types()
            names = [name for name, version in types]
            self.assertTrue('openmdao.test.execcomp.ExecComp' in names)

            # Create a component.
            exec_comp = factory.create('openmdao.test.execcomp.ExecComp')
            exec_comp.run()
            directory = 'Server_1' + os.sep
            if sys.platform == 'win32':
                directory = directory.lower()
            self.assertTrue(exec_comp.get_abs_directory().endswith(directory))

            # Create another in specified directory.
            exec_comp = factory.create('openmdao.test.execcomp.ExecComp',
                                       res_desc={'working_directory': 'floyd'})
            exec_comp.run()
            directory = 'floyd' + os.sep
            if sys.platform == 'win32':
                directory = directory.lower()
            self.assertTrue(exec_comp.get_abs_directory().endswith(directory))

            # Start server, connect, stop.
            server, cfg = start_server()
            proxy = connect_to_server(cfg)
            shutil.copy(cfg, 'saved_cfg')
            stop_server(server, cfg)

            _PROXIES.clear()
            assert_raises(self, "connect_to_server('saved_cfg')", globals(),
                          locals(), RuntimeError,
                          "Can't connect to server at ")

            # Force failed factory server startup via invalid port.
            address = socket.gethostbyname(socket.gethostname())
            code = "start_server(address=address, port='xyzzy'," \
                   " allow_shell=True, tunnel=True, resources='')"
            assert_raises(self, code, globals(), locals(), RuntimeError,
                          'Server startup failed')

            # Try to release a server that doesn't exist (release takes an
            # OpenMDAO_Proxy as argument, string here is easier).
            assert_raises(self, "factory.release('xyzzy')", globals(),
                          locals(), ValueError,
                          "can't identify server at 'not-a-proxy'")

            # get_ram() is used by RAM.add_remotes().
            ram = factory.get_ram()
            self.assertTrue(ram is RAM._get_instance())

        finally:
            if factory is not None:
                factory.cleanup()
            SimulationRoot.chroot('..')
            if sys.platform == 'win32':
                time.sleep(2)  # Wait for process shutdown.
            keep_dirs = int(os.environ.get('OPENMDAO_KEEPDIRS', '0'))
            if not keep_dirs:
                shutil.rmtree(testdir, onerror=onerror)
    def test_factory(self):
        logging.debug('')
        logging.debug('test_factory')

        testdir = 'test_factory'
        if os.path.exists(testdir):
            shutil.rmtree(testdir, onerror=onerror)
        os.mkdir(testdir)
        os.chdir(testdir)

        factory = None
        try:
            # Create a factory.
            factory = ObjServerFactory()

            # Echo some arguments.
            args = factory.echo('Hello', 'world!')
            self.assertEqual(args[0], 'Hello')
            self.assertEqual(args[1], 'world!')

            # List types.
            types = factory.get_available_types()
            names = [name for name, version in types]
            self.assertTrue('openmdao.test.execcomp.ExecComp' in names)

            # Create a component.
            exec_comp = factory.create('openmdao.test.execcomp.ExecComp')
            exec_comp.run()

            # Start server, connect, stop.
            server, cfg = start_server()
            proxy = connect_to_server(cfg)
            shutil.copy(cfg, 'saved_cfg')
            stop_server(server, cfg)

            _PROXIES.clear()
            assert_raises(self, "connect_to_server('saved_cfg')",
                          globals(), locals(), RuntimeError,
                          "Can't connect to server at ")

            # Force failed factory server startup via invalid port.
            address = socket.gethostbyname(socket.gethostname())
            code = "start_server(address=address, port='xyzzy'," \
                                 " allow_shell=True, tunnel=True, resources='')"
            assert_raises(self, code, globals(), locals(), RuntimeError,
                          'Server startup failed')

            # Try to release a server that doesn't exist (release takes an
            # OpenMDAO_Proxy as argument, string here is easier).
            assert_raises(self, "factory.release('xyzzy')",
                          globals(), locals(), ValueError,
                          "can't identify server at 'not-a-proxy'")

            # get_ram() is used by RAM.add_remotes().
            ram = factory.get_ram()
            self.assertTrue(ram is RAM._get_instance())

        finally:
            if factory is not None:
                factory.cleanup()
            SimulationRoot.chroot('..')
            if sys.platform == 'win32':
                time.sleep(2)  # Wait for process shutdown.
            keep_dirs = int(os.environ.get('OPENMDAO_KEEPDIRS', '0'))
            if not keep_dirs:
                shutil.rmtree(testdir, onerror=onerror)
    def test_server(self):
        logging.debug('')
        logging.debug('test_server')

        testdir = 'test_server'
        if os.path.exists(testdir):
            shutil.rmtree(testdir, onerror=onerror)
        os.mkdir(testdir)
        os.chdir(testdir)

        try:
            # Create a server.
            server = ObjServer()

            # Create a component.
            exec_comp = server.create('openmdao.test.execcomp.ExecComp')
            exec_comp.run()
            egg_info = exec_comp.save_to_egg('exec_comp', '0')

            # Echo some arguments.
            args = server.echo('Hello', 'world!')
            self.assertEqual(args[0], 'Hello')
            self.assertEqual(args[1], 'world!')

            # Try to execute a command.
            cmd = 'dir' if sys.platform == 'win32' else 'ls'
            rdesc = {'remote_command': cmd,
                     'output_path': 'cmd.out',
                     'hard_runtime_limit': 10}
            code = 'server.execute_command(rdesc)'
            assert_raises(self, code, globals(), locals(), RuntimeError,
                          'shell access is not allowed by this server')

            # Try to load a model.
            assert_raises(self, 'server.load_model(egg_info[0])',
                          globals(), locals(), RuntimeError,
                          'shell access is not allowed by this server')

            # Bogus file accesses.
            assert_raises(self, "server.open('../xyzzy', 'r')", globals(), locals(),
                          RuntimeError, "Can't open '../xyzzy', not within root ")
            assert_raises(self, "server.open('xyzzy', 'r')", globals(), locals(),
                          IOError, "[Errno 2] No such file or directory: 'xyzzy'")

            # Create a file using context.
            with server.open('xyzzy', 'w') as out:
                out.write('Hello world!\n')

            # Create another file using file proxy.
            out = server.open('fred', 'w')
            out.write('Hello fred!\n')
            out.flush()  # Not really necessary, just for coverage.
            out.close()

            # Zip it.
            server.pack_zipfile(['xyzzy', 'fred'], 'zipped')

            # Make it read-only.
            server.chmod('zipped', 0400)

            if sys.platform == 'win32':
                msg = '[Error 2] The system cannot find the file specified'
            else:
                msg = "[Errno 2] No such file or directory: 'no-such-file'"
            assert_raises(self, "server.chmod('no-such-file', 0400)",
                          globals(), locals(), OSError, msg)

            # Get stats.
            info = server.stat('zipped')

            assert_raises(self, "server.stat('no-such-file')",
                          globals(), locals(), OSError, msg)

            # Remove zipped contents.
            server.remove('xyzzy')
            server.remove('fred')

            if sys.platform == 'win32':
                msg = '[Error 2] The system cannot find the file specified'
            else:
                msg = "[Errno 2] No such file or directory: 'xyzzy'"
            assert_raises(self, "server.remove('xyzzy')",
                          globals(), locals(), OSError, msg)

            # Unpack.
            server.unpack_zipfile('zipped')
            server.chmod('zipped', 0600)  # Ensure we can remove under Windows.

            # Verify contents.
            with server.open('xyzzy', 'r') as inp:
                data = inp.read()
                self.assertEqual(data, 'Hello world!\n')

            inp = server.open('fred', 'r')
            try:
                data = inp.read(1000)
                self.assertEqual(data, 'Hello fred!\n')
            finally:
                inp.close()

            # Try to create a process.
            args = 'dir' if sys.platform == 'win32' else 'ls'
            try:
                proc = server.create('subprocess.Popen', args=args, shell=True)
                proc.wait()
            except TypeError as exc:
                msg = "'subprocess.Popen' is not an allowed type"
                self.assertEqual(str(exc), msg)
            else:
                self.fail('Expected TypeError')

            # isdir().
            self.assertTrue(server.isdir('.'))

            # listdir().
            self.assertEqual(sorted(server.listdir('.')),
                             [egg_info[0], 'fred', 'xyzzy', 'zipped'])
            if sys.platform == 'win32':
                msg = "[Error 3] The system cannot find the path specified: '42/*.*'"
            else:
                msg = "[Errno 2] No such file or directory: '42'"
            assert_raises(self, "server.listdir('42')",
                          globals(), locals(), OSError, msg)
        finally:
            SimulationRoot.chroot('..')
            shutil.rmtree(testdir, onerror=onerror)