简体   繁体   English

如何对python进程进行单元测试

[英]how to unit test a python process

I am trying to write a unit test for a python process.我正在尝试为 python 进程编写单元测试。 I want to run the process for a few seconds and then do an assert to make sure that an instance variable of that process equals to the expected value.我想运行该过程几秒钟,然后执行断言以确保该过程的实例变量等于预期值。

class MyProcess(multiprocessing.Process):
    def run():
       ......

class TestMultiProcess(unittest.TestCase):

    def testStuff(self):
        process = MyProcess()
        process.start()
        time.sleep(20)
        process.exit.set()
        process.join()

        assert(process.ivar == 42)

The problem is in the last line.问题出在最后一行。 Because it is a process not a thread, I can't get the value of ivar directly (always equals to 0).因为是进程而不是线程,所以无法直接得到ivar的值(总是等于0)。 I am wondering what is the preferred way to get that ivar?我想知道获得该 ivar 的首选方法是什么?

The preferred way to unit test a code that is run using multiprocessing is to test individual functions directly if possible.如果可能,对使用multiprocessing运行的代码进行单元测试的首选方法是直接测试单个函数。

To get a value from another process, you could send it: mp.Pipe() , mp.Queue() or you could use a shared value: mp.Value() .要从另一个进程获取值,您可以发送它: mp.Pipe()mp.Queue()或者您可以使用共享值: mp.Value()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM