我目前正在 python 2.7 中使用 pytest 进行一组集成测试,执行以下操作:
1) 在我的本地计算机后台运行服务器二进制文件
2)向服务器发送请求并验证结果
3)终止后台服务器进程
一切似乎都工作正常,除了我无法终止计算机上运行的服务器进程。尽管它继续在我的计算机上运行,但 Python 似乎已经忘记了它;我的 Popen
对象是 None
。
AttributeError:“NoneType”对象没有属性“terminate”
对于造成这种情况的原因有什么想法吗?我是否遗漏了一些明显的东西?
import time
import subprocess
server_background_process_pipe = None
def setup_module():
# Start the test server in the background
cmd = 'bin/my_server --key1='+value1+' --key2='+value2+' &' # The '&' tells my bin to run in the background
server_background_process_pipe = subprocess.Popen(cmd, shell=True,stderr=subprocess.STDOUT)
print(server_background_process_pipe) # prints '<subprocess.Popen object at 0x10aabd250>'
time.sleep(1) # Wait for the server to be ready
def test_basic_get_request():
print(server_background_process_pipe) # prints 'None'
response = send_request_to_server()
fail_if_not_as_expected(response) # Response is exactly as expected
def teardown_module():
# kill the server that was launched in setup_module to serve requests in the tests
# AttributeError: 'NoneType' object has no attribute 'terminate'
server_background_process_pipe.terminate()
额外信息:
即使服务器进程仍在运行,它也是None
。测试运行时它是None
。它在测试套件完成后运行很长时间。如果我重新运行测试,我会在控制台中收到一条消息,指出我的服务器无法部署,因为它已经在运行。测试仍然通过,因为它们从之前的执行中向服务器发送了请求。
由于服务器需要在后台运行,因此我直接使用 subprocess.Popen 构造函数,而不是像 check_output
这样的便捷方法之一。
最佳答案
在
def setup_module():
…
server_background_process_pipe = subprocess.Popen(…)
server_background_process_pipe
是一个局部变量。它从未分配给全局 server_background_process_pipe
,因此全局 server_background_process_pipe
始终为 None
并且代码
def teardown_module():
server_background_process_pipe.terminate()
尝试从 None 获取属性terminate
。
您想要的是对全局变量进行初始赋值:
def setup_module():
…
global server_background_process_pipe
server_background_process_pipe = subprocess.Popen(…)
关于Python 2.7 子进程 Popen 返回 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50690606/