Skip to content

Fixture teardown runs after the restrictions are lifted #537

Closed

Description

@MHammett

pytest_runtest_teardown removes the restrictions before pytest tears down the test's fixtures. Every fixture finalizer therefore runs with the network open, while the same fixture's setup is blocked.

Reproduction

# test_teardown.py
import socket

import pytest


def dial():
    try:
        with socket.socket() as sock:
            sock.connect(("0.0.0.0", 0))  # refused by the OS at once
    except (RuntimeError, OSError) as exc:
        return type(exc).__name__


@pytest.fixture
def fixture():
    print("setup:", dial())
    yield
    print("teardown:", dial())


def test_it(fixture):
    print("call:", dial())
$ pytest -s -q --disable-socket --allow-hosts=127.0.0.1 test_teardown.py
setup: SocketConnectBlockedError
call: SocketConnectBlockedError
.teardown: OSError

OSError there means connect() really ran. Class-, module- and session-scoped fixtures, request.addfinalizer callbacks and xunit teardown_module behave the same way. I've seen this with pytest-socket 0.8.1 on pytest 8.4.2 and 9.1.1 (pluggy 1.6.0), both autoloaded and loaded with -p pytest_socket.

Cause

The finalizers are run by pytest's own pytest_runtest_teardown in _pytest/runner.py, via item.session._setupstate.teardown_exact(nextitem). That hook and pytest-socket's pytest_runtest_teardown are both plain hook implementations, and pluggy calls those newest-registered first. pytest-socket always registers after pytest's built-in plugins, so _remove_restrictions() runs before any finalizer.

Suggested fix

+@pytest.hookimpl(trylast=True)
 def pytest_runtest_teardown() -> None:
     _remove_restrictions()

With only that line added to a copy of 0.8.1, the reproduction prints teardown: SocketConnectBlockedError. Nothing lifts the restrictions between setup and teardown any more, so teardown runs under whatever pytest_runtest_setup chose for that test, including markers and the socket_enabled/socket_disabled fixtures. If that's welcome, I can open a PR with this change and a test that dials from a fixture's teardown.

There's a related case this doesn't cover, which may be worth a separate look. After a teardown error under -x or --maxfail, pytest only decides to stop once that teardown has run with nextitem set. The fixtures the next test would have shared are then finalized later, by _pytest.runner.pytest_sessionfinish, outside any test's restrictions.

Activity

  1. added
    bug
    on Oct 12, 2026
  2. Gabrieljr42 commented on Oct 18, 2026

    @Gabrieljr42

    Thanks for the clear reproduction and hook-order analysis. I opened PR #557 to keep restrictions active through fixture finalizers and restore them even when teardown raises. I left the separate early-stop pytest_sessionfinish case out of scope.

  3. miketheman commented on Oct 21, 2026

    @miketheman
    Owner

    Thanks for this report, @MHammett. The reproduction and the hook-order analysis made the problem easy to confirm, and your note about teardown deferred to pytest_sessionfinish turned into a test case.

    #564 fixes it by tearing each fixture down under the socket state its setup ran under, at every scope, including teardown deferred by -x. It went a different direction than the trylast one-liner: that version is skipped when a finalizer raises, and it would run shared fixtures' teardown under whichever test runs last.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions