相关疑难解决方法(0)

我可以在python单元测试中伪造/模拟我的模拟对象的类型

在我的python代码中,我检查其中一个参数的类型,以确保它是我期望的类型.例如:

def myfunction(dbConnection):
    if (type(dbConnection)<>bpgsql.Connection):
        r['error'] += ' invalid database connection'
Run Code Online (Sandbox Code Playgroud)

我想通过模拟连接进行测试.有没有办法让模拟对象伪装成正确的类型?

python unit-testing mocking

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

如何模拟在 isinstance 测试中使用的类?

我想测试一下功能is_myclass。请帮助我了解如何编写成功的测试。

def is_myclass(obj):
    """This absurd stub is a simplified version of the production code."""
    isinstance(obj, MyClass)
    MyClass()
Run Code Online (Sandbox Code Playgroud)

文档

unittest.mock 的 Python 文档说明了解决该isinstance问题的三种方法:

  • spec参数设置为真实的类。
  • 将真正的类分配给__class__属性。
  • spec在真实类的补丁中使用。

__class__

通常,__class__对象的属性将返回其类型。对于具有规范的模拟对象,__class__返回规范类。这允许模拟对象通过 isinstance() 测试它们正在替换/伪装为的对象:

>>> mock = Mock(spec=3)
>>> isinstance(mock, int)
True
Run Code Online (Sandbox Code Playgroud)

__class__可分配给,这允许模拟通过isinstance()检查而不强迫您使用规范:

>>> mock = Mock()
>>> mock.__class__ = dict
>>> isinstance(mock, dict)
True
Run Code Online (Sandbox Code Playgroud)

[...]

如果您使用specorspec_set并且patch()正在替换一个类,那么创建的模拟的返回值将具有相同的规范。

>>> Original = Class
>>> patcher …
Run Code Online (Sandbox Code Playgroud)

python unit-testing mocking python-unittest

5
推荐指数
1
解决办法
4057
查看次数

是否可以在Python 3.6中模拟内置的len()函数?

可以len()在Python 3.6中模拟内置函数吗?

我有一个类,定义了一个简单的方法,该方法依赖于以下len()功能:

class MyLenFunc(object):
    def is_longer_than_three_characters(self, some_string):
        return len(some_string) > 3
Run Code Online (Sandbox Code Playgroud)

我正在尝试为此方法编写一个单元测试,但是我无法在len()不产生错误的情况下模拟出该函数。这是我到目前为止的内容:

import unittest
from unittest.mock import patch
import my_len_func


class TestMyLenFunc(unittest.TestCase):

    @patch('builtins.len')
    def test_len_function_is_called(self, mock_len):
        # Arrange
        test_string = 'four'

        # Act
        test_object = my_len_func.MyLenFunc()
        test_object.is_longer_than_three_characters(test_string)

        # Assert
        self.assertEqual(1, mock_len.call_count)


if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

我在这里找到了另一个SO问题/答案它暗示不可能模拟出内置函数,因为它们是不可变的。但是,我在这里这里发现了另外两个网站,这表明其他情况。我在上面的单元测试课程中的尝试直接来自这些网站中的后者(是的,我已经尝试了此处提到的其他技术。所有方法都以相同的错误结尾)。

我收到的错误要花很长时间才能发布完整的内容,因此我将剪掉它的重复部分(您将从错误消息的最后一部分中看到它是递归的)。错误文本如下:

ERROR: test_len_function_is_called (__main__.TestMyLenFunc)
---------------------------------------------------------------------- 
Traceback (most recent call last):
    File "C:\Python36\Lib\unittest\mock.py", line 1179, in patched
        return func(*args, …
Run Code Online (Sandbox Code Playgroud)

python unit-testing mocking python-3.x

4
推荐指数
1
解决办法
3475
查看次数