python / python/cpython

mock.patch applied at class level behaves incorrectly

未關閉
#93,582 6 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

stdlib type-bug
主要語言
Python
星號
77.2k
分支
36k
PR 合併指標
PR 指標待擷取

描述

Bug report

When applying @mock.patch to classes where the test_ method is inherited, this applies the patch to the base class,, instead of to the specific class. In this case, the patch to the g method applies in MockedFTests and MockedFStraightGTests.

# a.py
import unittest
from unittest import mock

def f():
    return 41

def g():
    return 43

class BaseFTests(unittest.TestCase):
    def test_a(self):
        self._asserts(f())

    def _asserts(self, val):
        print(self, val)

@mock.patch('a.f', new=lambda: 2)
class MockedFTests(BaseFTests):
    def _asserts(self, val):
        print(self, val)
        self.assertEqual(val, 2)
        self.assertEqual(g(), 43)

@mock.patch('a.g', new=lambda: 3)
class MockedFMockedGTests(MockedFTests):
    def _asserts(self, val):
        print(self, val)
        self.assertEqual(val, g()-1)

class MockedFStraightGTests(MockedFTests):
    def _asserts(self, val):
        print(self, val)
        self.assertEqual(val, 2)
        self.assertEqual(g(), 43)

Expect all tests to pass.
Actual output: 2 tests fail with error AssertionError: 3 != 43

Your environment

  • CPython versions tested on: Python 3.10.4 on Windows

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

首先,使用 unittest.mock.patch 在一個小模組中重現該範例,重點關注繼承的 test_ 方法以及 BaseFTests、MockedFTests、MockedFMockedGTests 和 MockedFStraightGTests 類別。追蹤 unittest.mock 中類別層級 patch 的行為,並為回報的繼承情況新增回歸測試。完成的標準是:範例的測試通過,且不會將子類別 patch 套用到兄弟類別。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
testing-qa
Issue 類型
缺陷
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
基本清楚
新手友好度
42/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。