2014-11-20 45 views
4

我正在编写针对需要作为另一个进程运行的REST API进行测试的python单元测试。在python中,我如何运行命令行程序,直到我发送Ctrl + D时才返回

其余服务器是tomcat的应用程序,我从壳呼吁在发展模式下运行,所以我在寻找什么用Python测试做的是:

  1. 启动服务器,返回时服务器已经到了。
  2. 运行单元测试
  3. 发送服务器Ctrl + D因此它优雅地关闭。

有没有办法为python使用单一入口点,以便服务器启动并且单元测试可以从一个python脚本调用中运行所有入口?

我环顾了python的子进程和多线程,但我还是不太明白怎么从这里到达那里。

对于那些熟悉的人来说,这是我们正在开发的Atlassian JIRA插件,因此实际的shell命令是“atlas-run”。

+1

1.)如何从命令行调用服务器?你可以使用'pexpect'模块吗? 2.)服务器启动后,只需运行'unittest.main()'。 3.)你可以使用'signal'模块来将'SIGQUIT'和'pexpect'发送到服务器吗? – wflynny 2014-11-20 21:14:15

+0

我没有意识到这一点,我现在正在研究这一点,谢谢!通过CD向服务器调用插件项目的根目录并从命令行运行“atlas-run”。 – MStudley 2014-11-21 18:44:24

回答

3

由于没有人提供任何代码来帮助解决这个问题,我会做类似以下的事情。原来pexpect功能非常强大,你不需要signal模块。

import os 
import sys 
import pexpect 

def run_server(): 
    server_dir = '/path/to/server/root' 
    current_dir = os.path.abspath(os.curdir) 

    os.chdir(server_dir) 
    server_call = pexpect.spawn('atlas-run') 
    server_response = server_call.expect(['Server Error!', 'Sever is running!']) 
    os.chdir(current_dir) 
    if server_response: 
     return server_call #return server spawn object so we can shutdown later 
    else: 
     print 'Error starting the server: %s'%server_response.after 
     sys.exit(1) 

def run_unittests(): 
    # several ways to do this. either make a unittest.TestSuite or run command line 
    # here is the second option 
    unittest_dir = '/path/to/tests' 
    pexpect.spawn('python -m unittest discover -s %s -p "*test.py"'%unittest_dir) 
    test_response = pexpect.expect('Ran [0-9]+ tests in [0-9\.]+s') #catch end 
    print test_response.before #print output of unittests before ending. 
    return 

def main(): 
    server = run_sever() 
    run_unittests() 
    server.sendcontrol('d') #shutdown server 

if __name__ == "__main__": 
    main() 
+1

这个工程!我正在使用TestSuite路线,而不是在另一个流程中运行单元测试,但仍然 - 非常棒的答案。谢谢! – MStudley 2014-11-21 22:57:08

相关问题