fix: Eliminate port allocation race condition in all affected test files #1528
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
This PR extends the port allocation race condition fix to all test files affected by the same TOCTOU issue, eliminating intermittent test failures when running with pytest-xdist parallel workers.
Motivation and Context
When running tests with pytest-xdist parallel workers, multiple workers would receive the same "free" port from
socket.bind(("127.0.0.1", 0)), causing a TOCTOU (Time-of-Check-Time-of-Use) race condition. This manifested as:This builds on the initial fix in tests/server/fastmcp/test_integration.py by applying the same solution to 7 additional test files that had the identical issue.
How Has This Been Tested?
PYTEST_DISABLE_PLUGIN_AUTOLOAD="" uv run --frozen pytest tests/ -vEach pytest-xdist worker now receives an exclusive port range from 40000-59999 based on its worker ID, eliminating port conflicts entirely.
Breaking Changes
None. This is an internal test infrastructure change with no impact on the public API or user-facing functionality.
Types of changes
Checklist
Additional context
Files modified:
tests/server/test_streamable_http_security.py- Updatedserver_portfixturetests/server/test_sse_security.py- Updatedserver_portfixturetests/shared/test_streamable_http.py- Updated 3 port fixtures (basic, json, event server)tests/shared/test_sse.py- Updatedserver_portfixturetests/shared/test_ws.py- Updatedserver_portfixturetests/client/test_http_unicode.py- Updatedunicode_server_portfixturetests/client/test_notification_response.py- Updatednon_sdk_server_portfixturetests/test_test_helpers.py- Fixed socket cleanup to prevent ResourceWarningImplementation details:
All affected fixtures now use
get_worker_specific_port(worker_id)instead of the race-pronesocket.bind(("127.0.0.1", 0))pattern. The helper function allocates worker-specific port ranges ensuring no overlap between parallel test workers.