相关疑难解决方法(0)

模拟 - 如何在调用者上引发异常?

假设这是代码

def move(*args, **kwargs):   
    try:
        shutil.move(source, destination)
    except Exception as e:
        raise e
Run Code Online (Sandbox Code Playgroud)

在我的tests.py中

@patch.object(shutil, 'move')
def test_move_catch_exception(self, mock_rmtree):
    ''' Tests moving a target hits exception. '''
    mock_rmtree.side_effect = Exception('abc')
    self.assertRaises(Exception, move,
                             self.src_f, self.src_f, **self.kwargs)
Run Code Online (Sandbox Code Playgroud)

它说这个

  File "unittests.py", line 84, in test_move_catch_exception
    self.src_f, self.src_f, **self.kwargs)
AssertionError: Exception not raised
Run Code Online (Sandbox Code Playgroud)

如果我坚持mock_rmtree就会通过.如何在调用者上断言(在本例中为函数move)?


aquavitae所指出的,主要原因是复制粘贴错误,而且我在开始时也断言了一个元组.始终使用正确的返回类型...

python unit-testing mocking

19
推荐指数
1
解决办法
2万
查看次数

Python模拟类实例变量

我正在使用Python的mock库.我知道如何通过遵循文档来模拟类实例方法:

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'
Run Code Online (Sandbox Code Playgroud)

但是,尝试模拟类实例变量但不起作用(instance.labels在以下示例中):

>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     instance.labels = [1, 1, 2, 2]
...     result = some_function()
...     assert result == 'the result'
Run Code Online (Sandbox Code Playgroud)

基本上,我想instance.labelssome_function得到我想要的价值.任何提示?

python unit-testing mocking

13
推荐指数
1
解决办法
3万
查看次数

如何使用Python Mock引发异常 - 但Errno设置为给定值

鉴于此Python代码:

elif request.method == 'DELETE':
    try:
        os.remove(full_file)
        return jsonify({'results':'purged %s' % full_file})

    except OSError as e:
        if e.errno != errno.ENOENT:
            raise

        return jsonify({'results':'file not present: %s' % full_file})
Run Code Online (Sandbox Code Playgroud)

我想测试所有可能的路径,包括异常处理.使用Mock,很容易引发异常,我使用此代码:

with patch('os.remove', new=Mock(side_effect=OSError(errno.ENOENT))):
    self.assertRaises(OSError, self.app.delete, file_URL) # broken
Run Code Online (Sandbox Code Playgroud)

模拟引发异常,其打印值为2(ENOENT) - 但e.errno设置为NONE.到目前为止,我还没有找到一种方法来设置它.结果是,异常总是被重新引发,我的单元测试中从未到达最后一行代码.

我也尝试使用errno set创建一个虚拟类,然后返回它.但除非它有*side_effect*设置为调用,否则它不会引发异常,当我设置side_effect时,我不会将object.errno作为返回值.

有没有办法让Mock引发一个Exception,那个Exception对象是否设置了errno属性?

python unit-testing mocking

9
推荐指数
1
解决办法
4451
查看次数

标签 统计

mocking ×3

python ×3

unit-testing ×3