如何在rpc代码中轻松创建无法 pickle 以测试边缘情况的对象?
它必须是:
编辑:预期用途看起来像这样:
class TestRPCServer:
def foo(self):
return MagicalUnpicklableObject()
def test():
with run_rpc_server_and_connect_to_it() as proxy:
with nose.assert_raises(pickle.PickleError):
proxy.foo()
最佳答案
如果您只需要一个在 pickle 时将引发异常的对象,则出于测试目的,您可以炸毁 __getstate__
method。
>>> class C:
... def __getstate__(self):
... raise Exception
...
>>> pickle.dumps(C())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps
Pickler(file, protocol).dump(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
self.save(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 723, in save_inst
stuff = getstate()
File "<stdin>", line 3, in __getstate__
Exception
如果您希望减少人为的情况,请考虑使用OS资源的对象,例如文件句柄,套接字或线程等。
>>> with open('spam.txt', 'w') as f:
... pickle.dumps(f)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps
Pickler(file, protocol).dump(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
self.save(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 306, in save
rv = reduce(self.proto)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle file objects
关于python - 创建无法 pickle 的对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35724255/