Skip to content

Commit d98576e

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 d98576e

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-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: 28 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,28 @@ 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 error (in its __del__ method), which emits a warning onto
278+
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, script_path], stderr=subprocess.PIPE)
292+
293+
# We can't check the exit code, because we are expecting the script to fail.
294+
# Instead, we ensure that no warning about an AttributeError is printed on
295+
# stderr due to an error in the server's __del__ method.
296+
assert b"AttributeError" not in result.stderr

0 commit comments

Comments
 (0)