简体   繁体   中英

How to save unittest.TestResult

If I try to pickle unittest.TestResult in the obvious way

    import pickle
    import unittest

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

I get the error (with Python 2.7)

    TypeError: can't pickle file objects

This used to work in Python 2.6, but in 2.7 and later it appears that file descriptors were added to the TestResult class. So what is the recommended way to save test results? Do I have to do it the hard way and manually save each of the fields?

Replace file type fields.

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)

Or define your own 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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