python / python/cpython

unittest.mock.patch of a subclass poisons base class

オープン
#117,507 コメント 4 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

stdlib type-bug
主要言語
Python
スター
77.2k
フォーク
35.9k
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. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

提供された Python 3.12 reproducer を実行し、issue で問題のある動作が特定されている Lib/unittest/mock.py の 1412 行付近を調べてください。変更を加える前に、関連する PR gh-117665、gh-117667、gh-117687 を確認してください。Test1 を通して観測される継承メソッドの動作が、サブクラスにパッチを適用しても変更されなくなれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
testing-qa
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。