Skip to content

Commit 3dce92a

Browse files
authored
Make unit test deterministic by mocking network connection (#17614)
1 parent 87d1815 commit 3dce92a

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
CheckEndpoints lets its clients pass alternative to `urllib.requests.urlopen` which:
2+
1. exposes the external dependency more clearly
3+
2. supports deterministic testing

datadog_checks_dev/datadog_checks/dev/conditions.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,13 @@ def __init__(
6767
timeout=1, # type: int
6868
attempts=60, # type: int
6969
wait=1, # type: int
70+
send_request=None,
7071
):
7172
self.endpoints = [endpoints] if isinstance(endpoints, string_types) else endpoints
7273
self.timeout = timeout
7374
self.attempts = attempts
7475
self.wait = wait
76+
self.send_request = urlopen if send_request is None else send_request
7577

7678
def __call__(self):
7779
last_endpoint = ''
@@ -81,12 +83,12 @@ def __call__(self):
8183
for endpoint in self.endpoints:
8284
last_endpoint = endpoint
8385
try:
84-
request = urlopen(endpoint, timeout=self.timeout)
86+
response = self.send_request(endpoint, timeout=self.timeout)
8587
except Exception as e:
8688
last_error = str(e)
8789
break
8890
else:
89-
status_code = request.getcode()
91+
status_code = response.getcode()
9092
if 400 <= status_code < 600:
9193
last_error = 'status {}'.format(status_code)
9294
break

datadog_checks_dev/tests/test_conditions.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,19 @@
55
import sys
66

77
import pytest
8+
from six.moves.urllib.response import addinfourl
89

910
from datadog_checks.dev.conditions import CheckCommandOutput, CheckDockerLogs, CheckEndpoints, WaitFor
1011
from datadog_checks.dev.errors import RetryError
1112
from datadog_checks.dev.subprocess import run_command
1213

1314
from .common import not_windows_ci
1415

16+
try:
17+
from unittest import mock # Python 3
18+
except ImportError:
19+
import mock # Python 2
20+
1521
HERE = os.path.dirname(os.path.abspath(__file__))
1622
DOCKER_DIR = os.path.join(HERE, 'docker')
1723

@@ -97,6 +103,8 @@ def test_fail(self):
97103
check_endpoints()
98104

99105
def test_success(self):
100-
check_endpoints = CheckEndpoints(['https://google.com', 'https://bing.com'])
106+
mock_resp = mock.create_autospec(addinfourl)
107+
mock_resp.getcode.return_value = 200
108+
check_endpoints = CheckEndpoints(['https://test.com'], send_request=lambda *args, **kwargs: mock_resp)
101109

102110
check_endpoints()

0 commit comments

Comments
 (0)