python / python/cpython

unittest.mock.patch of a subclass poisons base class

Aperta
#117,507 4 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

stdlib type-bug
Lingua principale
Python
Stelle
77.2k
Fork
35.9k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Esegui il reproducer Python 3.12 fornito e ispeziona Lib/unittest/mock.py intorno alla riga 1412, dove l’issue identifica il comportamento problematico. Esamina le PR collegati gh-117665, gh-117667 e gh-117687 prima di apportare modifiche; il lavoro è completato quando il patch di una sottoclasse non modifica più il comportamento del metodo ereditato osservato tramite Test1.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
testing-qa
Tipo di issue
Bug
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.