我目前正在使用python 2.7中的pytest进行一组集成测试,该测试执行以下操作:
1)在我的本地计算机上在后台运行服务器二进制文件
2)将请求发送到服务器并验证结果
3)终止后台服务器进程
除了无法终止计算机上运行的服务器进程之外,其他所有东西似乎都工作正常。尽管它继续在我的计算机上运行,但是Python似乎已经忘记了它。我的Popen
对象是None
。
AttributeError: 'NoneType' object has no attribute '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()
尝试terminate
从None获取属性。
您想要对全局变量进行初始分配:
def setup_module():
…
global server_background_process_pipe
server_background_process_pipe = subprocess.Popen(…)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句