Add safe_close helper to standardize socket cleanup in tests #698
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.
Hi! First of all, thanks for the great work on this project.
While looking at the socket-based tests, I noticed that sockets are being closed directly with
close(). In most cases this works fine, but the recommended pattern when dealing with sockets is to first callshutdown()and thenclose(). This allows the connection to be terminated more cleanly, ensuring that both read and write channels are properly closed before releasing the resource.According to the Python documentation:
In tests, failures caused by not doing this are rare, but when they happen they are usually hard to diagnose (for example, resource warnings, hanging sockets, or platform-dependent behavior). Using a small helper like
safe_closemakes the cleanup more explicit and consistent across the test code.This PR introduces a
safe_closefunction that:shutdown()firstclose()The main goal here is not to fix a concrete bug, but to improve the cleanup pattern and make it more robust and standardized for current and future tests. It also makes the intent clearer: sockets are always closed in a safe and predictable way. This was identified during an ongoing research project.