我正在尝试使用Flask来使用子进程运行命令。在高层次上,我要做的是创建一种方法,用户可以点击URL并传入' test_name' [对于PoC我正在使用烟雾]。 然后该测试名称将传递给flask_test_runner()。 在flask_test_runner中,我试图运行以下pytest命令
pytest -m test_name -html=report.html --self-contained-html
使用子流程
command = subprocess.Popen(["pytest", "-m", test_name, "-html=report.html", "--self-contained-html"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
所有这些都在docker容器中运行。我已尽力验证docker不是根本原因。有一次,我在dockerfile的末尾包含了一个RUN pytest,它启动了测试。
我的服务器按预期启动:
* Serving Flask app "webserver" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 282-250-075
当我点击网址http://localhost:5000/apitesting/smoke时,我在响应中得到以下内容:
Content-Type: text/html; charset=utf-8
Content-Length: 0
Server: Werkzeug/0.14.1 Python/3.6.4
Date: Wed, 30 May 2018 20:20:39 GMT
我的控制台出现此错误:
File "/usr/local/lib/python3.6/site-packages/pytest_cloud/plugin.py", line 77, in pytest_addoption
os.path.basename(os.environ['PWD'])
File "/usr/local/lib/python3.6/os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'PWD'
我不明白为什么会这样,所以任何帮助都表示赞赏。感谢您的时间。
作为参考,我的应用程序路线如下:
@app.route('/apitesting/<test_name>', methods=['GET', 'POST'])
def runsmoketests(test_name):
'''
:param test_name: test type passed in by the user
'''
flask_app_cmd = api_flask_test_runner.flask_test_runner(test_name)
print(flask_app_cmd[0])
print(flask_app_cmd[1])
return flask_app_cmd
我打电话的flask_test_runner是:
import subprocess
def flask_test_runner(test_name):
'''
:param test_name: is passed along from the route /apitesting/<test_name>
:return:
'''
command = subprocess.Popen(["pytest", "-m", test_name, "-html=report.html", "--self-contained-html"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = command.communicate()
return (out, err)
答案 0 :(得分:1)
你的建议是
由于缺少PWD密钥,您可以尝试os.environ ['PWD'] = os.getcwd()。希望这将设置变量,您的脚本可以继续。
我将方法更新为:
def flask_test_runner(test_name):
# force PWD
os.environ['PWD'] = os.getcwd()
command = subprocess.Popen(["pytest", "-m", test_name, "-html=report.html", "--self-contained-html"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return command.communicate()
我现在可以毫无错误地点击endpount!
$ docker run -p 5000:5000 command_test_cont-1
* Serving Flask app "webserver" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 282-250-075
172.17.0.1 - - [31/May/2018 13:46:57] "GET /apitesting/smoke HTTP/1.1" 0 -
172.17.0.1 - - [31/May/2018 13:46:59] "GET /favicon.ico HTTP/1.1" 200 -