为什么模拟补丁仅在运行特定测试而不是整个测试套件时起作用?

Han*_*nny 9 django unit-testing mocking pytest liveservertestcase

我专门使用 Django 和 Pytest 来运行测试套件,并尝试测试当用户访问网站时特定表单是否显示预期数据(集成测试)。

这个特定的视图使用一个存储过程,我正在嘲笑它,因为测试永远无法访问它。

我的测试代码如下所示:

#test_integrations.py

from my_app.tests.data_setup import setup_data, setup_sb7_data
from unittest.mock import patch

...

# Setup to use a non-headless browser so we can see whats happening for debugging
@pytest.mark.usefixtures("standard_browser")
class SeniorPageTestCase(StaticLiveServerTestCase):
    """
    These tests surround the senior form
    """

    @classmethod
    def setUpClass(cls):
        cls.host = socket.gethostbyname(socket.gethostname())
        super(SeniorPageTestCase, cls).setUpClass()

    def setUp(self):
        # setup the dummy data - this works fine
        basic_setup(self)
        # setup the 'results'
        self.sb7_mock_data = setup_sb7_data(self)

    @patch("my_app.utils.get_employee_sb7_data")
    def test_senior_form_displays(self, mock_sb7_get):
        # login the dummy user we created
        login_user(self, "futureuser")
        # setup the results
        mock_sb7_get.return_value = self.sb7_mock_data
        # hit the page for the form
        self.browser.get(self.live_server_url + "/my_app/senior")
        form_id = "SeniorForm"
        # assert that the form displays on the page
        self.assertTrue(self.browser.find_element_by_id(form_id))
Run Code Online (Sandbox Code Playgroud)
# utils.py

from django.conf import settings
from django.db import connections


def get_employee_sb7_data(db_name, user_number, window):
    """
    Executes the stored procedure for getting employee data

    Args:
        user_number: Takes the user_number
        db (db connection): Takes a string of the DB to connect to

    Returns:

    """
    cursor = connections[db_name].cursor()
    cursor.execute(
        'exec sp_sb7 %s, "%s"' % (user_number, window.senior_close)
    )
    columns = [col[0] for col in cursor.description]
    results = [dict(zip(columns, row)) for row in cursor.fetchall()]
    return results
Run Code Online (Sandbox Code Playgroud)
# views.py

from myapp.utils import (
    get_employee_sb7_data,
)

...

###### Senior ######
@login_required
@group_required("user_senior")
def senior(request):

    # Additional Logic / Getting Other Models here

    # Execute stored procedure to get data for user
    user_number = request.user.user_no
    results = get_employee_sb7_data("production_db", user_number, window)
    if not results:
        return render(request, "users/senior_not_required.html")

    # Additional view stuff

    return render(
        request,
        "users/senior.html",
        {
            "data": data,
            "form": form,
            "results": results,
        },
    )
Run Code Online (Sandbox Code Playgroud)

如果我运行这个测试本身:

pytest my_app/tests/test_integrations.py::SeniorPageTestCase

测试顺利通过。浏览器出现 - 表单显示了我们所期望的虚拟数据,并且一切正常。

但是,如果我运行:

pytest my_app

所有其他测试都会运行并通过 - 但此类中的所有测试都会失败,因为它没有修补该功能。

它尝试调用实际的存储过程(该过程失败,因为它尚未位于生产服务器上),但失败了。

为什么当我专门调用该 TestCase 时它会正确修补 - 但当我只是pytest在应用程序或项目级别运行时却无法正确修补?

我很茫然,不知道如何很好地调试它。任何帮助表示赞赏

小智 7

因此,发生的情况是在修补之前导入您的视图。

我们先看一下工作案例:

  1. pytest 导入 test_integrations 文件
  2. 执行测试并运行补丁装饰器的内部函数
  3. 还没有导入 utils,因此补丁导入并替换了该函数
  4. 执行测试主体,将 url 传递给测试客户端
  5. 测试客户端导入解析器,然后导入视图,视图又导入实用程序。
  6. 由于实用程序已经修补,一切正常

如果另一个测试用例首先运行,它也导入相同的视图,那么该导入将获胜,并且补丁无法替换该导入。

您的解决方案是引用相同的符号。所以在test_integrations.py

@patch("myapp.views.get_employee_sb7_data")
Run Code Online (Sandbox Code Playgroud)

  • 感谢您对需要发生的事情所做的精彩解释和更正。我现在对正在发生的事情有了更深入的了解(尽管 Mocks 对我来说仍然有点令人困惑 - 文档看起来像泥巴一样清晰!哈!)。我很感激! (2认同)