Skip to content

Commit df2d094

Browse files
authored
Fixing push status that has been broken since moving to a client (#80)
* Fixing push status that has been broken since moving to a client * Adding unit test to cover the bug
1 parent 79a9a7f commit df2d094

File tree

6 files changed

+100
-67
lines changed

6 files changed

+100
-67
lines changed

cachet_url_monitor/client.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/env python
22
from typing import Dict
3+
from typing import Optional
34

45
import click
56
import requests
@@ -81,7 +82,7 @@ def get_default_metric_value(self, metric_id):
8182
else:
8283
raise exceptions.MetricNonexistentError(metric_id)
8384

84-
def get_component_status(self, component_id):
85+
def get_component_status(self, component_id: int) -> Optional[status.ComponentStatus]:
8586
"""Retrieves the current status of the given component. It will fail if the component does
8687
not exist or doesn't respond with the expected data.
8788
:return component status.
@@ -94,13 +95,13 @@ def get_component_status(self, component_id):
9495
else:
9596
raise exceptions.ComponentNonexistentError(component_id)
9697

97-
def push_status(self, component_id, component_status):
98+
def push_status(self, component_id: int, component_status: status.ComponentStatus):
9899
"""Pushes the status of the component to the cachet server.
99100
"""
100-
params = {'id': component_id, 'status': component_status}
101+
params = {'id': component_id, 'status': component_status.value}
101102
return requests.put(f"{self.url}/components/{component_id}", params=params, headers=self.headers)
102103

103-
def push_metrics(self, metric_id, latency_time_unit, elapsed_time_in_seconds, timestamp):
104+
def push_metrics(self, metric_id: int, latency_time_unit: str, elapsed_time_in_seconds: int, timestamp: int):
104105
"""Pushes the total amount of seconds the request took to get a response from the URL.
105106
"""
106107
value = latency_unit.convert_to_unit(latency_time_unit, elapsed_time_in_seconds)
@@ -122,7 +123,7 @@ def push_incident(self, status_value: status.ComponentStatus, is_public_incident
122123
# This is the first time the incident is being created.
123124
params = {'name': 'URL unavailable', 'message': message,
124125
'status': status.IncidentStatus.INVESTIGATING.value,
125-
'visible': is_public_incident, 'component_id': component_id, 'component_status': status_value,
126+
'visible': is_public_incident, 'component_id': component_id, 'component_status': status_value.value,
126127
'notify': True}
127128
return requests.post(f'{self.url}/incidents', params=params, headers=self.headers)
128129

cachet_url_monitor/configuration.py

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,15 @@
22
import abc
33
import copy
44
import logging
5-
import os
65
import re
76
import time
7+
from typing import Dict
88

99
import requests
1010
from yaml import dump
1111

1212
import cachet_url_monitor.status as st
1313
from cachet_url_monitor.client import CachetClient, normalize_url
14-
from cachet_url_monitor.exceptions import MetricNonexistentError
1514
from cachet_url_monitor.status import ComponentStatus
1615

1716
# This is the mandatory fields that must be in the configuration file in this
@@ -33,13 +32,37 @@ class Configuration(object):
3332
"""Represents a configuration file, but it also includes the functionality
3433
of assessing the API and pushing the results to cachet.
3534
"""
36-
37-
def __init__(self, config, endpoint_index: int):
38-
self.endpoint_index: int = endpoint_index
35+
endpoint_index: int
36+
endpoint: str
37+
client: CachetClient
38+
token: str
39+
current_fails: int
40+
trigger_update: bool
41+
headers: Dict[str, str]
42+
43+
endpoint_method: str
44+
endpoint_url: str
45+
endpoint_timeout: int
46+
endpoint_header: Dict[str, str]
47+
48+
allowed_fails: int
49+
component_id: int
50+
metric_id: int
51+
default_metric_value: int
52+
latency_unit: str
53+
54+
status: ComponentStatus
55+
previous_status: ComponentStatus
56+
57+
def __init__(self, config, endpoint_index: int, client: CachetClient, token: str):
58+
self.endpoint_index = endpoint_index
3959
self.data = config
4060
self.endpoint = self.data['endpoints'][endpoint_index]
41-
self.current_fails: int = 0
42-
self.trigger_update: bool = True
61+
self.client = client
62+
self.token = token
63+
64+
self.current_fails = 0
65+
self.trigger_update = True
4366

4467
if 'name' not in self.endpoint:
4568
# We have to make this mandatory, otherwise the logs are confusing when there are multiple URLs.
@@ -54,7 +77,7 @@ def __init__(self, config, endpoint_index: int):
5477
self.validate()
5578

5679
# We store the main information from the configuration file, so we don't keep reading from the data dictionary.
57-
self.token = os.environ.get('CACHET_TOKEN') or self.data['cachet']['token']
80+
5881
self.headers = {'X-Cachet-Token': self.token}
5982

6083
self.endpoint_method = self.endpoint['method']
@@ -63,14 +86,11 @@ def __init__(self, config, endpoint_index: int):
6386
self.endpoint_header = self.endpoint.get('header') or None
6487
self.allowed_fails = self.endpoint.get('allowed_fails') or 0
6588

66-
self.api_url = os.environ.get('CACHET_API_URL') or self.data['cachet']['api_url']
6789
self.component_id = self.endpoint['component_id']
6890
self.metric_id = self.endpoint.get('metric_id')
6991

70-
self.client = CachetClient(self.api_url, self.token)
71-
7292
if self.metric_id is not None:
73-
self.default_metric_value = self.get_default_metric_value(self.metric_id)
93+
self.default_metric_value = self.client.get_default_metric_value(self.metric_id)
7494

7595
# The latency_unit configuration is not mandatory and we fallback to seconds, by default.
7696
self.latency_unit = self.data['cachet'].get('latency_unit') or 's'
@@ -88,15 +108,6 @@ def __init__(self, config, endpoint_index: int):
88108
for expectation in self.expectations:
89109
self.logger.info('Registered expectation: %s' % (expectation,))
90110

91-
def get_default_metric_value(self, metric_id):
92-
"""Returns default value for configured metric."""
93-
get_metric_request = requests.get('%s/metrics/%s' % (self.api_url, metric_id), headers=self.headers)
94-
95-
if get_metric_request.ok:
96-
return get_metric_request.json()['data']['default_value']
97-
else:
98-
raise MetricNonexistentError(metric_id)
99-
100111
def get_action(self):
101112
"""Retrieves the action list from the configuration. If it's empty, returns an empty list.
102113
:return: The list of actions, which can be an empty list.
@@ -162,7 +173,7 @@ def evaluate(self):
162173
status: ComponentStatus = expectation.get_status(self.request)
163174

164175
# The greater the status is, the worse the state of the API is.
165-
if status.value > self.status.value:
176+
if status.value >= self.status.value:
166177
self.status = status
167178
self.message = expectation.get_message(self.request)
168179
self.logger.info(self.message)

cachet_url_monitor/latency_unit.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
#!/usr/bin/env python
2+
from typing import Dict
23

3-
seconds_per_unit = {"ms": 1000, "milliseconds": 1000, "s": 1, "seconds": 1, "m": float(1) / 60,
4+
seconds_per_unit: Dict[str, float] = {"ms": 1000, "milliseconds": 1000, "s": 1, "seconds": 1, "m": float(1) / 60,
45
"minutes": float(1) / 60, "h": float(1) / 3600, "hours": float(1) / 3600}
56

67

7-
def convert_to_unit(time_unit, value):
8+
def convert_to_unit(time_unit: str, value: float):
89
"""
910
Will convert the given value from seconds to the given time_unit.
1011

cachet_url_monitor/scheduler.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import schedule
88
from yaml import load, SafeLoader
99

10+
from cachet_url_monitor.client import CachetClient
1011
from cachet_url_monitor.configuration import Configuration
1112

1213
cachet_mandatory_fields = ['api_url', 'token']
@@ -105,14 +106,14 @@ def build_agent(configuration, logger):
105106

106107

107108
def validate_config():
108-
if 'endpoints' not in config_file.keys():
109+
if 'endpoints' not in config_data.keys():
109110
fatal_error('Endpoints is a mandatory field')
110111

111-
if config_file['endpoints'] is None:
112+
if config_data['endpoints'] is None:
112113
fatal_error('Endpoints array can not be empty')
113114

114115
for key in cachet_mandatory_fields:
115-
if key not in config_file['cachet']:
116+
if key not in config_data['cachet']:
116117
fatal_error('Missing cachet mandatory fields')
117118

118119

@@ -132,14 +133,16 @@ def fatal_error(message):
132133
sys.exit(1)
133134

134135
try:
135-
config_file = load(open(sys.argv[1], 'r'), SafeLoader)
136+
config_data = load(open(sys.argv[1], 'r'), SafeLoader)
136137
except FileNotFoundError:
137138
logging.getLogger('cachet_url_monitor.scheduler').fatal(f'File not found: {sys.argv[1]}')
138139
sys.exit(1)
139140

140141
validate_config()
141142

142-
for endpoint_index in range(len(config_file['endpoints'])):
143-
configuration = Configuration(config_file, endpoint_index)
143+
for endpoint_index in range(len(config_data['endpoints'])):
144+
token = os.environ.get('CACHET_TOKEN') or config_data['cachet']['token']
145+
api_url = os.environ.get('CACHET_API_URL') or config_data['cachet']['api_url']
146+
configuration = Configuration(config_data, endpoint_index, CachetClient(api_url, token), token)
144147
NewThread(Scheduler(configuration,
145148
build_agent(configuration, logging.getLogger('cachet_url_monitor.scheduler')))).start()

tests/test_client.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,3 +145,11 @@ def json():
145145

146146
self.assertEqual(status, ComponentStatus.OPERATIONAL,
147147
'Getting component status value is incorrect.')
148+
149+
@requests_mock.mock()
150+
def test_push_status(self, m):
151+
m.put(f'{CACHET_URL}/components/123?id=123&status={ComponentStatus.PARTIAL_OUTAGE.value}',
152+
headers={'X-Cachet-Token': TOKEN})
153+
response = self.client.push_status(123, ComponentStatus.PARTIAL_OUTAGE)
154+
155+
self.assertTrue(response.ok, 'Pushing status value is failed.')

tests/test_configuration.py

Lines changed: 41 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -9,42 +9,35 @@
99
from yaml import load, SafeLoader
1010

1111
import cachet_url_monitor.status
12+
from cachet_url_monitor.client import CachetClient
13+
import cachet_url_monitor.exceptions
1214

1315
sys.modules['logging'] = mock.Mock()
1416
from cachet_url_monitor.configuration import Configuration
1517
import os
1618

1719

1820
class ConfigurationTest(unittest.TestCase):
19-
@mock.patch.dict(os.environ, {'CACHET_TOKEN': 'token2'})
21+
client: CachetClient
22+
configuration: Configuration
23+
2024
def setUp(self):
2125
def getLogger(name):
2226
self.mock_logger = mock.Mock()
2327
return self.mock_logger
2428

2529
sys.modules['logging'].getLogger = getLogger
26-
27-
# def get(url, headers):
28-
# get_return = mock.Mock()
29-
# get_return.ok = True
30-
# get_return.json = mock.Mock()
31-
# get_return.json.return_value = {'data': {'status': 1, 'default_value': 0.5}}
32-
# return get_return
33-
#
34-
# sys.modules['requests'].get = get
35-
30+
self.client = mock.Mock()
31+
# We set the initial status to OPERATIONAL.
32+
self.client.get_component_status.return_value = cachet_url_monitor.status.ComponentStatus.OPERATIONAL
3633
self.configuration = Configuration(
37-
load(open(os.path.join(os.path.dirname(__file__), 'configs/config.yml'), 'rt'), SafeLoader), 0)
38-
# sys.modules['requests'].Timeout = Timeout
39-
# sys.modules['requests'].ConnectionError = ConnectionError
40-
# sys.modules['requests'].HTTPError = HTTPError
34+
load(open(os.path.join(os.path.dirname(__file__), 'configs/config.yml'), 'rt'), SafeLoader), 0, self.client,
35+
'token2')
4136

4237
def test_init(self):
4338
self.assertEqual(len(self.configuration.data), 2, 'Number of root elements in config.yml is incorrect')
4439
self.assertEqual(len(self.configuration.expectations), 3, 'Number of expectations read from file is incorrect')
4540
self.assertDictEqual(self.configuration.headers, {'X-Cachet-Token': 'token2'}, 'Header was not set correctly')
46-
self.assertEqual(self.configuration.api_url, 'https://demo.cachethq.io/api/v1',
47-
'Cachet API URL was set incorrectly')
4841
self.assertDictEqual(self.configuration.endpoint_header, {'SOME-HEADER': 'SOME-VALUE'}, 'Header is incorrect')
4942

5043
@requests_mock.mock()
@@ -98,31 +91,49 @@ def test_evaluate_with_http_error(self, m):
9891
'Component status set incorrectly')
9992
self.mock_logger.exception.assert_called_with('Unexpected HTTP response')
10093

101-
@requests_mock.mock()
102-
def test_push_status(self, m):
103-
m.put('https://demo.cachethq.io/api/v1/components/1?id=1&status=1', headers={'X-Cachet-Token': 'token2'})
104-
self.assertEqual(self.configuration.status, cachet_url_monitor.status.ComponentStatus.OPERATIONAL,
105-
'Incorrect component update parameters')
94+
def test_push_status(self):
95+
self.client.get_component_status.return_value = cachet_url_monitor.status.ComponentStatus.OPERATIONAL
96+
push_status_response = mock.Mock()
97+
self.client.push_status.return_value = push_status_response
98+
push_status_response.ok = True
99+
self.configuration.status = cachet_url_monitor.status.ComponentStatus.PARTIAL_OUTAGE
100+
106101
self.configuration.push_status()
107102

108-
@requests_mock.mock()
109-
def test_push_status_with_failure(self, m):
110-
m.put('https://demo.cachethq.io/api/v1/components/1?id=1&status=1', headers={'X-Cachet-Token': 'token2'},
111-
status_code=400)
112-
self.assertEqual(self.configuration.status, cachet_url_monitor.status.ComponentStatus.OPERATIONAL,
113-
'Incorrect component update parameters')
103+
self.client.push_status.assert_called_once_with(1, cachet_url_monitor.status.ComponentStatus.OPERATIONAL)
104+
105+
def test_push_status_with_failure(self):
106+
self.client.get_component_status.return_value = cachet_url_monitor.status.ComponentStatus.OPERATIONAL
107+
push_status_response = mock.Mock()
108+
self.client.push_status.return_value = push_status_response
109+
push_status_response.ok = False
110+
self.configuration.status = cachet_url_monitor.status.ComponentStatus.PARTIAL_OUTAGE
111+
112+
self.configuration.push_status()
113+
114+
self.client.push_status.assert_called_once_with(1, cachet_url_monitor.status.ComponentStatus.OPERATIONAL)
115+
116+
def test_push_status_same_status(self):
117+
self.client.get_component_status.return_value = cachet_url_monitor.status.ComponentStatus.OPERATIONAL
118+
self.configuration.status = cachet_url_monitor.status.ComponentStatus.OPERATIONAL
119+
114120
self.configuration.push_status()
115121

122+
self.client.push_status.assert_not_called()
123+
116124

117125
class ConfigurationMultipleUrlTest(unittest.TestCase):
118126
@mock.patch.dict(os.environ, {'CACHET_TOKEN': 'token2'})
119127
def setUp(self):
120128
config_yaml = load(open(os.path.join(os.path.dirname(__file__), 'configs/config_multiple_urls.yml'), 'rt'),
121129
SafeLoader)
130+
self.client = []
122131
self.configuration = []
123132

124133
for index in range(len(config_yaml['endpoints'])):
125-
self.configuration.append(Configuration(config_yaml, index))
134+
client = mock.Mock()
135+
self.client.append(client)
136+
self.configuration.append(Configuration(config_yaml, index, client, 'token2'))
126137

127138
def test_init(self):
128139
expected_method = ['GET', 'POST']
@@ -133,8 +144,6 @@ def test_init(self):
133144
self.assertEqual(len(config.data), 2, 'Number of root elements in config.yml is incorrect')
134145
self.assertEqual(len(config.expectations), 1, 'Number of expectations read from file is incorrect')
135146
self.assertDictEqual(config.headers, {'X-Cachet-Token': 'token2'}, 'Header was not set correctly')
136-
self.assertEqual(config.api_url, 'https://demo.cachethq.io/api/v1',
137-
'Cachet API URL was set incorrectly')
138147

139148
self.assertEqual(expected_method[index], config.endpoint_method)
140149
self.assertEqual(expected_url[index], config.endpoint_url)
@@ -146,4 +155,4 @@ def test_init(self):
146155
with pytest.raises(cachet_url_monitor.configuration.ConfigurationValidationError):
147156
self.configuration = Configuration(
148157
load(open(os.path.join(os.path.dirname(__file__), 'configs/config_invalid_type.yml'), 'rt'),
149-
SafeLoader), 0)
158+
SafeLoader), 0, mock.Mock(), 'token2')

0 commit comments

Comments
 (0)