小编Yev*_*evs的帖子

Python 3 urlopen上下文管理器嘲笑

我是新手测试,需要一些帮助.

假设有这种方法:

from urllib.request import urlopen

def get_posts():
    with urlopen('some url here') as data:
        return json.loads(data.read().decode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

问题是如何测试这个方法(如果可能的话,使用mock.patch装饰器)?

我现在拥有的:

@mock.patch('mymodule.urlopen')
def test_get_post(self, mocked_urlopen):
    mocked_urlopen.__enter__ = Mock(return_value=self.test_data)
    mocked_urlopen.__exit__ = Mock(return_value=False)
    ...
Run Code Online (Sandbox Code Playgroud)

但它似乎没有奏效.

PS有没有方便的方法在测试中使用数据变量(哪种类型是HTTPResponse),所以它可能只是简单的字符串?

testing unit-testing python-3.x

7
推荐指数
2
解决办法
2193
查看次数

标签 统计

python-3.x ×1

testing ×1

unit-testing ×1