python / python/cpython

mock.mock_open __exit__ called as instance method from contextlib.ExitStack context

Offen
#150,484 2 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

3.13 3.14 stdlib type-bug
Vorherrschende Sprache
Python
Sterne
77.2k
Forks
35.9k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug report

Bug description:

In Python 3.13 onwards:

from contextlib import ExitStack
from unittest import mock
with mock.patch("__main__.open", mock.mock_open()) as m:
    with ExitStack() as exit_stack:
        with exit_stack.enter_context(open("/tmp/test.txt", "w")):
            pass

raises

TypeError: mock_open.<locals>._exit_side_effect() takes 3 positional arguments but 4 were given

The issue seems to come from https://github.com/python/cpython/commit/3f7c0810f6158a7ff37be432f8d7f9511427489f

It appears that in Python versions 3.12 and earlier, mock_open().__exit__ was always called with 4 args (self, exctype, excinst, exctb) when used with contextlib.ExitStack but that used to be a no-op before the exit handler was added.

I'm not sure whether this should be fixed by:

  1. changing the way ExitStack calls its stack of __exit__ callbacks
  2. making mock_open and open more similar, or
  3. making mock_open's exit handler take *args, **kwargs same as the enter handler??

Thanks

CPython versions tested on:

3.12, 3.13, 3.14

Operating systems tested on:

Linux

Linked PRs
  • gh-150521
  • gh-150535
  • gh-151829
  • gh-151861

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit dem Reproducer unter Verwendung von contextlib.ExitStack und unittest.mock.mock_open und untersuche dann das im Issue beschriebene Callback-Verhalten. Die Aufgabe ist abgeschlossen, wenn der TypeError in Python 3.13+ behoben ist, das erwartete Kontextmanager-Verhalten erhalten bleibt und Coverage für den gemeldeten Fall hinzugefügt wurde.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
testing
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
25/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.