我正在为执行 RethinkDB 数据库的 Python 脚本构建测试器。作为 setUp() 方法的一部分,我试图让测试人员在端口 28016 上的 localhost 上启动 RethinkDB 服务器,以防万一这还没有完成。
我正在使用 subprocess 来启动服务器。问题是,根据 https://docs.python.org/2/library/subprocess.html , subprocess 等待命令完成。在这种情况下,似乎只要服务器启动并运行,过程就不会完成,测试不会继续超出 setUp() 阶段。
这是我正在尝试的脚本:
import unittest
import rethinkdb as r
import subprocess
class TestController(unittest.TestCase):
HOST = "localhost"
PORT_OFFSET = 1
PORT = 28015 + PORT_OFFSET
DB = "ipercron"
TABLE = "sensor_data"
def setUp(self):
try:
self.conn = r.connect(self.HOST, self.PORT)
except r.ReqlDriverError:
print("The RethinkDB server is not yet ready. Starting it up...")
subprocess.call(["rethinkdb", "--port-offset", str(TestController.PORT_OFFSET)])
self.conn = r.connect(self.HOST, self.PORT)
if TestController.DB not in r.db_list().run(self.conn):
r.db_create(TestController.DB).run(self.conn)
self.conn.use(TestController.DB)
if TestController.TABLE not in r.table_list().run(self.conn):
r.table_create(TestController.TABLE).run(self.conn) # Create the table if it does not yet exist
r.table(TestController.TABLE).delete().run(self.conn) # Empty the table to start with a clean slate
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
suite = unittest.TestLoader().loadTestsFromTestCase(TestController)
unittest.TextTestRunner(verbosity=2).run(suite)
subprocess 用于在命令行执行 rethinkdb --port-offset 1 命令,然后继续执行脚本。但是,当我运行脚本时,我收到服务器已准备就绪的常规消息:
kurt@kurt-ThinkPad:~/dev/clones/ipercron-compose/controller$ python unittest_controller.py
test_upper (__main__.TestController) ... The RethinkDB server is not yet ready. Starting it up...
Running rethinkdb 2.3.5~0xenial (GCC 5.3.1)...
Running on Linux 4.4.0-42-generic x86_64
Loading data from directory /home/kurt/dev/clones/ipercron-compose/controller/rethinkdb_data
Listening for intracluster connections on port 29016
Listening for client driver connections on port 28016
Listening for administrative HTTP connections on port 8081
Listening on cluster addresses: 127.0.0.1, 127.0.1.1, ::1
Listening on driver addresses: 127.0.0.1, 127.0.1.1, ::1
Listening on http addresses: 127.0.0.1, 127.0.1.1, ::1
To fully expose RethinkDB on the network, bind to all addresses by running rethinkdb with the `--bind all` command line option.
Server ready, "kurt_ThinkPad_a0k" 07bb35f6-3a33-4e8b-9e9c-a78504457969
没有任何进一步的行动。如何让单元测试继续测试?
请您参考如下方法:
问题如你所说,subprocess.call is blocking并将等待命令完成。对于需要在不等待子进程完成的情况下生成子进程的情况,可以使用 subprocess.Popen :
process = subprocess.Popen(["rethinkdb", "--port-offset", str(TestController.PORT_OFFSET)])
这会返回一个 Popen object它提供了一大堆非常有用的方法来与子进程进行通信。例如,您可能希望在单元测试的 tearDown() 函数中使用 process.kill() 来关闭数据库。
