Skip to content

Commit fb43a54

Browse files
committed
Ignore AttributeError when shutting down server
It's possible for the _server attribute to not exist if make_server raises an error in the constructor.
1 parent 0daabd7 commit fb43a54

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

pytest_localserver/http.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,12 @@ def __del__(self):
3131
self.stop()
3232

3333
def stop(self):
34-
self._server.shutdown()
34+
try:
35+
server = self._server
36+
except AttributeError:
37+
pass
38+
else:
39+
server.shutdown()
3540

3641
@property
3742
def url(self):

tests/test_http.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
import itertools
2+
import subprocess
3+
import sys
4+
import textwrap
25

36
import pytest
47
import requests
@@ -266,3 +269,29 @@ def test_GET_request_chunked_no_content_length(httpserver, chunked_flag):
266269
assert resp.status_code == 200
267270
assert "Transfer-encoding" in resp.headers
268271
assert "Content-length" not in resp.headers
272+
273+
274+
def test_httpserver_init_failure_no_stderr_during_cleanup(tmp_path):
275+
"""
276+
Test that, when the server encounters an error during __init__, its cleanup
277+
does not raise an AttributeError in its __del__ method, which would emit a
278+
warning onto stderr.
279+
"""
280+
281+
script_path = tmp_path.joinpath("script.py")
282+
283+
script_path.write_text(textwrap.dedent("""
284+
from pytest_localserver import http
285+
from unittest.mock import patch
286+
287+
with patch("pytest_localserver.http.make_server", side_effect=RuntimeError("init failure")):
288+
server = http.ContentServer()
289+
"""))
290+
291+
result = subprocess.run([sys.executable, str(script_path)], stderr=subprocess.PIPE)
292+
293+
# We ensure that no warning about an AttributeError is printed on stderr
294+
# due to an error in the server's __del__ method. This AttributeError is
295+
# raised during cleanup and doesn't affect the exit code of the script, so
296+
# we can't use the exit code to tell whether the script did its job.
297+
assert b"AttributeError" not in result.stderr

0 commit comments

Comments
 (0)