【问题标题】:Mocking database calls in python using pytest-mock使用 pytest-mock 在 python 中模拟数据库调用
【发布时间】:2021-02-16 11:11:25
【问题描述】:

我已经定义了这个函数:

def count_occurrences(cursor, cust_id):
    cursor.execute("SELECT count(id) FROM users WHERE customer_id = %s", (cust_id))
    total_count = cursor.fetchone()[0]
    if total_count == 0:
        return True
    else:
        return False

我想对其进行单元测试,因为我需要在这里模拟数据库调用。

如何使用 pytest、mock 来做到这一点?

【问题讨论】:

    标签: python-3.x database unit-testing mocking pytest


    【解决方案1】:

    因此测试起来相对简单,因为您的函数需要一个光标对象,我们可以用Mock 对象替换它。那么我们要做的就是configure我们的模拟游标返回不同的数据来测试我们拥有的不同场景。

    对于您的测试,有两种可能的结果,TrueFalse。因此,我们为fetchone 提供不同的返回值来测试这两种结果,如下所示,使用pytest.mark.parametrize

    @pytest.mark.parametrize("count,expected", 
        [(0, True), (1, False), (25, False), (None, False)]
    )
    def test_count_occurences(count, expected):
        mock_cursor = MagicMock()
        mock_cursor.configure_mock(
            **{
                "fetchone.return_value": [count]
            }
        )
    
        actual = count_occurrences(mock_cursor, "some_id")
        assert actual == expected
    

    当我们运行它时,我们看到针对提供的所有输入运行了四个单独的测试。

    collected 4 items                                                                                                
    
    test_foo.py::test_count_occurences[0-True] PASSED                                                          [ 25%]
    test_foo.py::test_count_occurences[1-False] PASSED                                                         [ 50%]
    test_foo.py::test_count_occurences[25-False] PASSED                                                        [ 75%]
    test_foo.py::test_count_occurences[None-False] PASSED                                                      [100%]
    
    =============================================== 4 passed in 0.07s ================================================
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-17
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 1970-01-01
      • 2011-07-14
      相关资源
      最近更新 更多