测试一些使用 urllib2 的代码, 我想养一个 HTTPError以确保它得到正确处理。
HTTPError 有一个构造函数:
def __init__(self, url, code, msg, hdrs, fp):
我不知道要传递什么作为最后一个参数 fp。
你能帮我举一个会引发 HTTPError 的例子吗? 引发 HTTPError('arg1','arg2','arg3','arg4',...
如何实现?
请您参考如下方法:
传递 fp=None。
来自source code :
# The addinfourl classes depend on fp being a valid file # object. In some cases, the HTTPError may not have a valid # file object. If this happens, the simplest workaround is to # not initialize the base classes. if fp is not None: self.__super_init(fp, hdrs, url, code)
fp 需要是一个类似文件的对象,所以你可以传递一个 StringIO如果你喜欢,请反对。
