def test_exception():   
    global PORT
    class MyManager_Client(jobmanager.BaseManager):
        pass
        
    def autoproxy_server(which_python, port, authkey, outfile):
        libpath = os.path.dirname(os.__file__)
        python_env = os.environ.copy()
        envpath = "{LIB}:{LIB}/site-packages".format(LIB=libpath)
        envpath += ":{LIB}/lib-old".format(LIB=libpath)
        envpath += ":{LIB}/lib-tk".format(LIB=libpath)
        envpath += ":{LIB}/lib-dynload".format(LIB=libpath)
        envpath += ":{LIB}/plat-linux2".format(LIB=libpath)
        # env will be
        # "/usr/lib/python2.7" for python 2
        # "/usr/lib/python3.4" for python 3
        if which_python == 2:
            python_interpreter = "python2.7"
            envpath = envpath.replace("3.4", "2.7")
        elif which_python == 3:
            python_interpreter = "python3.4"
            envpath = envpath.replace("2.7", "3.4")
        else:
            raise ValueError("'which_python' must be 2 or 3")
            
        python_env["PYTHONPATH"] = envpath
        path = dirname(abspath(__file__))
        cmd = [python_interpreter,
        
               "{}/start_autoproxy_server.py".format(path),
               str(port), 
               authkey]

        print("+"*40)
        print("start an autoproxy server with command")
        print(cmd)
        print("and environment")
        print(python_env)
        print("+"*40)
        return subprocess.Popen(cmd, env=python_env, stdout=outfile, stderr=subprocess.STDOUT)

    def autoproxy_connect(server, port, authkey):
        MyManager_Client.register('get_q')
        
        m = MyManager_Client(address = (server, port),                              
                             authkey = bytearray(authkey, encoding='utf8'))
        
        jobmanager.call_connect(m.connect, dest = jobmanager.address_authkey_from_manager(m), verbose=2)
        
        return m
        
    for p_version_server in [2, 3]:
        PORT += 2 # plus two because we also check for wrong port
        port = PORT
        authkey = 'q'
        with open("ap_server.out", 'w') as outfile:
            p_server = autoproxy_server(p_version_server, port, authkey, outfile)
            print("autoproxy server running with PID {}".format(p_server.pid))
            time.sleep(1)
            try:
                print("running tests with python {} ...".format(sys.version_info[0]))
                print()

                if sys.version_info[0] == 3:
                    print("we are using python 3 ... try to connect ...")
                    try:
                        autoproxy_connect(server=SERVER, port=port, authkey=authkey)
                    except jobmanager.RemoteValueError as e:
                        if p_version_server == 2:
                            print("that is ok, because the server is running on python2")      # the occurrence of this Exception is normal
                            print()
                        else:
                            print("RemoteValueError error")
                            raise                    # reraise exception
                    except Exception as e:
                        print("unexpected error {}".format(e))
                        raise
                
                elif sys.version_info[0] == 2:
                    print("we are using python 2 ... try to connect ...")
                    try:
                        autoproxy_connect(server=SERVER, port=port, authkey=authkey)
                    except __HOLE__ as e:
                        if p_version_server == 3:
                            print("that is ok, because the server is running on python3")      # the occurrence of this Exception is normal
                            print()
                        else:                
                            print("JMConnectionRefusedError error")
                            raise                    # reraise exception
                    except Exception as e:
                        print("unexpected error {}".format(e))
                        raise

                # all the following only for the same python versions
                if (sys.version_info[0] != p_version_server):
                    continue
                    
                try:
                    print("try to connect to server, use wrong port")
                    autoproxy_connect(server=SERVER, port=port+1, authkey=authkey)
                except jobmanager.JMConnectionRefusedError:
                    print("that is ok")
                    print()
                except:
                    raise
                
                try:
                    print("try to connect to server, use wrong authkey")
                    autoproxy_connect(server=SERVER, port=port, authkey=authkey+'_')
                except jobmanager.AuthenticationError:
                    print("that is ok")
                    print()
                except:
                    raise
                
                m = autoproxy_connect(server=SERVER, port=port, authkey=authkey)
                
                print("try pass some data forth and back ...")
                
                q = m.get_q()
                
                q_get = jobmanager.proxy_operation_decorator_python3(q, 'get')
                q_put = jobmanager.proxy_operation_decorator_python3(q, 'put')
                
                s1 = 'hallo welt'
                q_put(s1)
                s2 = q_get()
                
                assert s1 == s2                
                                
            finally:
                print()
                print("tests done! terminate server ...".format())
                
                p_server.send_signal(signal.SIGTERM)
                
                t = time.time()
                timeout = 10
                r = None
                while r is None:
                    r = p_server.poll()
                    time.sleep(1)
                    print("will kill server in {:.1f}s".format(timeout - (time.time() - t)))
                    if (time.time() - t) > timeout:
                        print("timeout exceeded, kill p_server")
                        print("the managers subprocess will still be running, and needs to be killed by hand")
                        p_server.send_signal(signal.SIGKILL)
                        break
                
                print("server terminated with exitcode {}".format(r))
        
                with open("ap_server.out", 'r') as outfile:
                    print("+"*40)
                    print("this is the server output:")
                    for l in outfile:
                        print("    {}".format(l[:-1]))
                    print("+"*40)
dataset/ETHPy150Open cimatosa/jobmanager/tests/test_jobmanager.py/test_exception