我有以下代码,当以python unittest运行时可以正常工作,但是如果使用带有以下错误消息的鼻子测试或py.test则失败:
NoseTest错误: PicklingError:无法腌制:找不到为teamcity.nose_report.newCaptureBeforeTest
py.test错误: PicklingError:无法腌制:找不到它是__builtin __。module
代码:
import unittest
import multiprocessing as mp
import time
TIME_LIMIT = 1
class TestCases(unittest.TestCase):
def setUp(self):
self.a = 0
def my_func(self):
time.sleep(2)
self.q.put(self.a + 1)
def run_case(self, func):
self.q = mp.Queue()
test_process = mp.Process(target=func)
test_process.start()
test_process.join(TIME_LIMIT)
self.assertFalse(test_process.is_alive(), 'timeout exceeded')
def test_case1(self):
self.run_case(self.my_func)
self.assertEquals(self.a + 1, self.q.get())
答案 0 :(得分:0)
如果被测函数不在同一测试类中,则可以避免该问题。不知道为什么,但是我相信py.test / nose调用父类以便派生进程的方式陷入了无限循环。
import unittest
import multiprocessing as mp
TIME_LIMIT = 1
class Submission():
def __init__(self):
self.score = mp.Queue(1)
def reset(self):
while not self.score.empty():
self.score.get()
def run(self):
self.score.put(0)
class TestCases(unittest.TestCase):
def setUp(self):
self.func = Submission()
self.a = 0
def run_case(self):
self.submission.reset()
test_process = mp.Process(target=self.submission.run)
test_process.start()
test_process.join(TIME_LIMIT)
self.assertFalse(test_process.is_alive(), 'timeout exceeded')
self.assertTrue(True)
def test_case1(self):
self.run_case()
score = self.submission.score.get()
self.assertTrue(score >= self.a)