Skip to content

Commit cc24900

Browse files
reformat
1 parent 16c54b7 commit cc24900

File tree

3 files changed

+77
-81
lines changed

3 files changed

+77
-81
lines changed

examples/usage_alerts.py

Lines changed: 21 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,20 @@
1010
from ns1.config import Config
1111

1212
# Path hackery to ensure we import the local ns1 module
13-
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__),
14-
'..')))
13+
sys.path.insert(
14+
0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
15+
)
1516

1617
# Create NS1 client
1718
config = {
18-
'endpoint': 'https://api.nsone.net',
19-
'default_key': 'test1',
20-
'keys': {
21-
'test1': {
22-
'key': os.environ.get('NS1_APIKEY', 'test1'),
23-
'desc': 'test key'
19+
"endpoint": "https://api.nsone.net",
20+
"default_key": "test1",
21+
"keys": {
22+
"test1": {
23+
"key": os.environ.get("NS1_APIKEY", "test1"),
24+
"desc": "test key",
2425
}
25-
}
26+
},
2627
}
2728

2829
# Create a config from dictionary and create the client
@@ -40,7 +41,7 @@ def usage_alerts_example():
4041
try:
4142
alerts = client.alerting().usage.list(limit=10)
4243
print(f"Total alerts: {alerts.get('total_results', 0)}")
43-
for i, alert in enumerate(alerts.get('results', [])):
44+
for i, alert in enumerate(alerts.get("results", [])):
4445
print(f" {i+1}. {alert.get('name')} (id: {alert.get('id')})")
4546
except Exception as e:
4647
print(f"Error listing alerts: {e}")
@@ -53,9 +54,9 @@ def usage_alerts_example():
5354
subtype="query_usage",
5455
alert_at_percent=85,
5556
notifier_list_ids=[],
56-
zone_names=[]
57+
zone_names=[],
5758
)
58-
alert_id = alert['id']
59+
alert_id = alert["id"]
5960
print(f"Created alert: {alert['name']} (id: {alert_id})")
6061
print(f"Alert details: {json.dumps(alert, indent=2)}")
6162
except Exception as e:
@@ -65,10 +66,7 @@ def usage_alerts_example():
6566
# Update the alert
6667
print("\nUpdating the alert threshold to 90%:")
6768
try:
68-
updated = client.alerting().usage.patch(
69-
alert_id,
70-
alert_at_percent=90
71-
)
69+
updated = client.alerting().usage.patch(alert_id, alert_at_percent=90)
7270
print(f"Updated alert: {updated['name']}")
7371
print(f"New threshold: {updated['data']['alert_at_percent']}%")
7472
except Exception as e:
@@ -99,9 +97,7 @@ def test_validation():
9997
print("Testing invalid subtype:")
10098
try:
10199
client.alerting().usage.create(
102-
name="Test alert",
103-
subtype="invalid_subtype",
104-
alert_at_percent=85
100+
name="Test alert", subtype="invalid_subtype", alert_at_percent=85
105101
)
106102
except ValueError as e:
107103
print(f"Validation error (expected): {e}")
@@ -110,9 +106,7 @@ def test_validation():
110106
print("\nTesting threshold too low (0):")
111107
try:
112108
client.alerting().usage.create(
113-
name="Test alert",
114-
subtype="query_usage",
115-
alert_at_percent=0
109+
name="Test alert", subtype="query_usage", alert_at_percent=0
116110
)
117111
except ValueError as e:
118112
print(f"Validation error (expected): {e}")
@@ -121,18 +115,18 @@ def test_validation():
121115
print("\nTesting threshold too high (101):")
122116
try:
123117
client.alerting().usage.create(
124-
name="Test alert",
125-
subtype="query_usage",
126-
alert_at_percent=101
118+
name="Test alert", subtype="query_usage", alert_at_percent=101
127119
)
128120
except ValueError as e:
129121
print(f"Validation error (expected): {e}")
130122

131123

132-
if __name__ == '__main__':
124+
if __name__ == "__main__":
133125
print("Usage Alerts API Examples")
134126
print("-" * 30)
135-
print("Note: To run against the actual API, set the NS1_APIKEY environment variable")
127+
print(
128+
"Note: To run against the actual API, set the NS1_APIKEY environment variable"
129+
)
136130
print("Otherwise, this will run against a mock API endpoint")
137131

138132
# Run examples

ns1/alerting/usage_alerts.py

Lines changed: 35 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
from typing import List, Optional, Dict, Any
22

33
USAGE_SUBTYPES = {
4-
"query_usage", "record_usage", "china_query_usage",
5-
"rum_decision_usage", "filter_chain_usage", "monitor_usage",
4+
"query_usage",
5+
"record_usage",
6+
"china_query_usage",
7+
"rum_decision_usage",
8+
"filter_chain_usage",
9+
"monitor_usage",
610
}
711

812

@@ -12,7 +16,8 @@ def _validate(name: str, subtype: str, alert_at_percent: int) -> None:
1216
if subtype not in USAGE_SUBTYPES:
1317
raise ValueError("invalid subtype")
1418
if not isinstance(alert_at_percent, int) or not (
15-
1 <= alert_at_percent <= 100):
19+
1 <= alert_at_percent <= 100
20+
):
1621
raise ValueError("data.alert_at_percent must be int in 1..100")
1722

1823

@@ -26,12 +31,15 @@ class UsageAlertsAPI:
2631
def __init__(self, client) -> None:
2732
self._c = client
2833

29-
def create(self, *,
30-
name: str,
31-
subtype: str,
32-
alert_at_percent: int,
33-
notifier_list_ids: Optional[List[str]] = None,
34-
zone_names: Optional[List[str]] = None) -> Dict[str, Any]:
34+
def create(
35+
self,
36+
*,
37+
name: str,
38+
subtype: str,
39+
alert_at_percent: int,
40+
notifier_list_ids: Optional[List[str]] = None,
41+
zone_names: Optional[List[str]] = None,
42+
) -> Dict[str, Any]:
3543
_validate(name, subtype, alert_at_percent)
3644
body = {
3745
"name": name,
@@ -46,17 +54,22 @@ def create(self, *,
4654
def get(self, alert_id: str) -> Dict[str, Any]:
4755
return self._c._get(f"/alerting/v1/alerts/{alert_id}")
4856

49-
def patch(self, alert_id: str, *,
50-
name: Optional[str] = None,
51-
alert_at_percent: Optional[int] = None,
52-
notifier_list_ids: Optional[List[str]] = None,
53-
zone_names: Optional[List[str]] = None) -> Dict[str, Any]:
57+
def patch(
58+
self,
59+
alert_id: str,
60+
*,
61+
name: Optional[str] = None,
62+
alert_at_percent: Optional[int] = None,
63+
notifier_list_ids: Optional[List[str]] = None,
64+
zone_names: Optional[List[str]] = None,
65+
) -> Dict[str, Any]:
5466
patch: Dict[str, Any] = {}
5567
if name is not None:
5668
patch["name"] = name
5769
if alert_at_percent is not None:
5870
if not isinstance(alert_at_percent, int) or not (
59-
1 <= alert_at_percent <= 100):
71+
1 <= alert_at_percent <= 100
72+
):
6073
raise ValueError("data.alert_at_percent must be int in 1..100")
6174
patch["data"] = {"alert_at_percent": int(alert_at_percent)}
6275
if notifier_list_ids is not None:
@@ -68,10 +81,13 @@ def patch(self, alert_id: str, *,
6881
def delete(self, alert_id: str) -> None:
6982
self._c._delete(f"/alerting/v1/alerts/{alert_id}")
7083

71-
def list(self, *,
72-
limit: int = 50,
73-
next: Optional[str] = None,
74-
order_descending: bool = False) -> Dict[str, Any]:
84+
def list(
85+
self,
86+
*,
87+
limit: int = 50,
88+
next: Optional[str] = None,
89+
order_descending: bool = False,
90+
) -> Dict[str, Any]:
7591
params: Dict[str, Any] = {"limit": limit}
7692
if next:
7793
params["next"] = next

tests/unit/test_usage_alerts.py

Lines changed: 21 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ def usage_alerts_client(config):
2626
}
2727
)
2828
from ns1 import NS1
29+
2930
client = NS1(config=config)
3031
return client
3132

@@ -45,7 +46,7 @@ def test_create_usage_alert(usage_alerts_client):
4546
"notifier_list_ids": ["n1"],
4647
"zone_names": [],
4748
"created_at": 1597937213,
48-
"updated_at": 1597937213
49+
"updated_at": 1597937213,
4950
}
5051

5152
# Patch the client reference
@@ -54,7 +55,7 @@ def test_create_usage_alert(usage_alerts_client):
5455
name="Test Alert",
5556
subtype="query_usage",
5657
alert_at_percent=85,
57-
notifier_list_ids=["n1"]
58+
notifier_list_ids=["n1"],
5859
)
5960

6061
# Verify _post was called with correct arguments
@@ -64,10 +65,11 @@ def test_create_usage_alert(usage_alerts_client):
6465
"subtype": "query_usage",
6566
"data": {"alert_at_percent": 85},
6667
"notifier_list_ids": ["n1"],
67-
"zone_names": []
68+
"zone_names": [],
6869
}
6970
client._post.assert_called_once_with(
70-
"/alerting/v1/alerts", json=expected_body)
71+
"/alerting/v1/alerts", json=expected_body
72+
)
7173

7274
# Verify result
7375
assert alert["id"] == "a1b2c3"
@@ -91,7 +93,7 @@ def test_get_usage_alert(usage_alerts_client):
9193
"subtype": "query_usage",
9294
"data": {"alert_at_percent": 85},
9395
"notifier_list_ids": ["n1"],
94-
"zone_names": []
96+
"zone_names": [],
9597
}
9698

9799
# Patch the client reference
@@ -121,24 +123,20 @@ def test_patch_usage_alert(usage_alerts_client):
121123
"subtype": "query_usage",
122124
"data": {"alert_at_percent": 90},
123125
"notifier_list_ids": ["n1"],
124-
"zone_names": []
126+
"zone_names": [],
125127
}
126128

127129
# Patch the client reference
128130
with mock.patch.object(client.alerting().usage, "_c", client):
129131
alert = client.alerting().usage.patch(
130-
alert_id,
131-
name="Updated Alert",
132-
alert_at_percent=90
132+
alert_id, name="Updated Alert", alert_at_percent=90
133133
)
134134

135135
# Verify _patch was called with correct arguments
136-
expected_body = {
137-
"name": "Updated Alert",
138-
"data": {"alert_at_percent": 90}
139-
}
136+
expected_body = {"name": "Updated Alert", "data": {"alert_at_percent": 90}}
140137
client._patch.assert_called_once_with(
141-
f"/alerting/v1/alerts/{alert_id}", json=expected_body)
138+
f"/alerting/v1/alerts/{alert_id}", json=expected_body
139+
)
142140

143141
# Verify type/subtype are not in the arguments
144142
call_args = client._patch.call_args[1]["json"]
@@ -183,25 +181,20 @@ def test_list_usage_alerts(usage_alerts_client):
183181
"name": "Alert 1",
184182
"type": "account",
185183
"subtype": "query_usage",
186-
"data": {"alert_at_percent": 80}
184+
"data": {"alert_at_percent": 80},
187185
}
188-
]
186+
],
189187
}
190188

191189
# Patch the client reference
192190
with mock.patch.object(client.alerting().usage, "_c", client):
193-
response = client.alerting().usage.list(
194-
limit=1,
195-
order_descending=True
196-
)
191+
response = client.alerting().usage.list(limit=1, order_descending=True)
197192

198193
# Verify _get was called with correct URL and params
199-
expected_params = {
200-
"limit": 1,
201-
"order_descending": "true"
202-
}
194+
expected_params = {"limit": 1, "order_descending": "true"}
203195
client._get.assert_called_once_with(
204-
"/alerting/v1/alerts", params=expected_params)
196+
"/alerting/v1/alerts", params=expected_params
197+
)
205198

206199
# Verify result
207200
assert "results" in response
@@ -219,27 +212,20 @@ def test_validation_threshold_bounds(usage_alerts_client):
219212
# Test below minimum
220213
with pytest.raises(ValueError) as excinfo:
221214
client.alerting().usage.create(
222-
name="Test Alert",
223-
subtype="query_usage",
224-
alert_at_percent=0
215+
name="Test Alert", subtype="query_usage", alert_at_percent=0
225216
)
226217
assert "alert_at_percent must be int in 1..100" in str(excinfo.value)
227218

228219
# Test above maximum
229220
with pytest.raises(ValueError) as excinfo:
230221
client.alerting().usage.create(
231-
name="Test Alert",
232-
subtype="query_usage",
233-
alert_at_percent=101
222+
name="Test Alert", subtype="query_usage", alert_at_percent=101
234223
)
235224
assert "alert_at_percent must be int in 1..100" in str(excinfo.value)
236225

237226
# Test same validation in patch
238227
with pytest.raises(ValueError) as excinfo:
239-
client.alerting().usage.patch(
240-
"a1",
241-
alert_at_percent=101
242-
)
228+
client.alerting().usage.patch("a1", alert_at_percent=101)
243229
assert "alert_at_percent must be int in 1..100" in str(excinfo.value)
244230

245231

0 commit comments

Comments
 (0)