2

如果我尝试以明显的方式腌制 unittest.TestResult

    import pickle
    import unittest

    pickle_file = open( "temp" + ".pickle", 'w' )
    u=unittest.TestResult()
    pickle.dump( u, pickle_file  )

我收到错误消息(使用 Python 2.7)

    TypeError: can't pickle file objects

这曾经在 Python 2.6 中工作,但在 2.7 及更高版本中,文件描述符似乎已添加到TestResult类中。那么保存测试结果的推荐方法是什么?我是否必须以艰难的方式完成并手动保存每个字段?

4

1 回答 1

0

替换文件类型字段。

import pickle
import unittest

pickle_file = open("temp" + ".pickle", 'wb')
u = unittest.TestResult()
for k, v in vars(u).items():
    if isinstance(v, file): # if not picklable(v):
        setattr(u, k, None)
pickle.dump(u, pickle_file)

或者定义你自己的pickler:

import pickle
import unittest

class SafePickler(pickle.Pickler):
    def save(self, obj):
        try:
            pickle.Pickler.save(self, obj)
        except TypeError, e:
            pickle.Pickler.save(self, None)

pickle_file = open("temp" + ".pickle", 'wb')
u = unittest.TestResult()
SafePickler(pickle_file).dump(u)
于 2013-07-04T03:16:49.563 回答