Skip to content

Commit 155f6a3

Browse files
wraps cpu usage endpoint.
1 parent 469ca1c commit 155f6a3

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

pythonanywhere_core/resources.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import getpass
2+
3+
from pythonanywhere_core.base import call_api, get_api_endpoint
4+
from pythonanywhere_core.exceptions import PythonAnywhereApiException
5+
6+
7+
class CPU:
8+
def __init__(self):
9+
self.base_url = get_api_endpoint(username=getpass.getuser(), flavor="cpu")
10+
11+
def get_cpu_usage(self):
12+
"""Get current CPU usage information."""
13+
response = call_api(url=self.base_url, method="GET")
14+
if not response.ok:
15+
raise PythonAnywhereApiException(f"GET to {self.base_url} failed, got {response}:{response.text}")
16+
return response.json()

tests/test_resources.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import getpass
2+
3+
import pytest
4+
import responses
5+
6+
from pythonanywhere_core.base import get_api_endpoint
7+
from pythonanywhere_core.resources import CPU
8+
from pythonanywhere_core.exceptions import PythonAnywhereApiException
9+
10+
11+
@pytest.fixture
12+
def base_url():
13+
return get_api_endpoint(username=getpass.getuser(), flavor="cpu")
14+
15+
16+
@pytest.fixture
17+
def cpu_api():
18+
return CPU()
19+
20+
21+
def test_get_cpu_usage_success(api_responses, api_token, cpu_api, base_url):
22+
example_response = {
23+
'daily_cpu_limit_seconds': 100000,
24+
'daily_cpu_total_usage_seconds': 0.064381,
25+
'next_reset_time': '2025-08-09T03:26:37'
26+
}
27+
28+
api_responses.add(
29+
responses.GET,
30+
base_url,
31+
json=example_response,
32+
status=200
33+
)
34+
35+
result = cpu_api.get_cpu_usage()
36+
37+
assert result == example_response
38+
39+
40+
def test_get_cpu_usage_api_error(api_responses, api_token, cpu_api, base_url):
41+
api_responses.add(
42+
responses.GET,
43+
base_url,
44+
json={"detail": "Not found"},
45+
status=400
46+
)
47+
48+
with pytest.raises(PythonAnywhereApiException) as exc_info:
49+
cpu_api.get_cpu_usage()
50+
51+
assert "Not found" in str(exc_info.value)

0 commit comments

Comments
 (0)