python / python/cpython

unittest.mock.patch of a subclass poisons base class

未关闭
#117,507 4 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib type-bug
主要语言
Python
星标
77.2k
派生
36k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description:

this is an entirely silly example boiled down from a much more complex one to demonstrate the behaviour. the actual code here is nonsensical (Test2 will always fail) but Test1 should work just fine -- the decoration of the subclass Test2 seems to also decorate Test1's methods unexpectedly

from unittest import mock

s = 0

@mock.patch(f"{__name__}.s", 5)
class Test1:
    def test_1(self):
        assert s == 5, s


@mock.patch(f"{__name__}.s", 2)
class Test2(Test1): pass

Test1().test_1()
$ python3.12 t2.py
Traceback (most recent call last):
  File "/Users/asottile/workspace/sentry/t2.py", line 14, in <module>
    Test1().test_1()
  File "/opt/homebrew/Cellar/python@3.12/3.12.2_1/Frameworks/Python.framework/Versions/3.12/lib/python3.12/unittest/mock.py", line 1387, in patched
    return func(*newargs, **newkeywargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/asottile/workspace/sentry/t2.py", line 8, in test_1
    assert s == 5, s
AssertionError: 2

the problem appears to be here: https://github.com/python/cpython/blob/ea94b3b149eeadf33c2f7c46f16dcda0adc7cf4e/Lib/unittest/mock.py#L1412

whereas I think it should always return a new callable instead of mutating a potentially unrelated method

CPython versions tested on:

3.12

Operating systems tested on:

macOS

Linked PRs
  • gh-117665
  • gh-117667
  • gh-117687

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

运行提供的 Python 3.12 reproducer,并检查 Lib/unittest/mock.py 中第 1412 行附近的位置,issue 在此指出了有问题的行为。进行更改前,先审阅相关 PR gh-117665、gh-117667 和 gh-117687;当对一个子类进行 patch 不再改变通过 Test1 观察到的继承方法行为时,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
testing-qa
Issue 类型
缺陷
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
描述清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。