mreg-api 0.7.0__tar.gz → 0.8.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {mreg_api-0.7.0 → mreg_api-0.8.0}/CHANGELOG.md +22 -1
- {mreg_api-0.7.0 → mreg_api-0.8.0}/PKG-INFO +1 -1
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/guides/exceptions.md +21 -15
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/guides/resources.md +4 -4
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/_version.py +3 -3
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/client.py +15 -14
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/exceptions.py +45 -29
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/managers.py +34 -12
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api.egg-info/PKG-INFO +1 -1
- mreg_api-0.8.0/mreg_api.egg-info/scm_version.json +8 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/conftest.py +3 -4
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_hostgroups.py +10 -10
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_networks.py +7 -7
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_roles.py +9 -9
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/test_client.py +95 -28
- mreg_api-0.7.0/mreg_api.egg-info/scm_version.json +0 -8
- {mreg_api-0.7.0 → mreg_api-0.8.0}/.claude/CLAUDE.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/.github/workflows/docs.yml +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/.github/workflows/publish.yml +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/.github/workflows/test.yml +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/.gitignore +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/.markdownlint.json +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/.pre-commit-config.yaml +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/LICENSE +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/NOTES.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/README.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/TESTING.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/ci/Dockerfile +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/ci/docker-compose.yml +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/ci/run_tests.sh +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/_macros/main.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/guides/authentication.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/guides/caching.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/guides/configuration.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/guides/eventlog.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/guides/requestlog.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/index.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/quick-start.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/reference/cache.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/reference/client.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/reference/events.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/reference/exceptions.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/reference/managers.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/reference/models.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/docs/reference/requestlog.md +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/__about__.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/__init__.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/cache.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/endpoints.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/events.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/models/__init__.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/models/abstracts.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/models/fields.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/models/history.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/models/models.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/py.typed +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/requestlog.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/types.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/utilities/__init__.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/utilities/fs.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api/utilities/shared.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api.egg-info/SOURCES.txt +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api.egg-info/dependency_links.txt +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api.egg-info/requires.txt +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api.egg-info/scm_file_list.json +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/mreg_api.egg-info/top_level.txt +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/pyproject.toml +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/setup.cfg +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/__init__.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/conftest.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/__init__.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_atoms.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_cname.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_dhcp.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_host_records.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_hosts.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_ip.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_labels.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_meta.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_nameservers.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_network_policy.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_permissions.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/integration/test_zones.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/models/__init__.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/models/test_fields.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/models/test_history.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/models/test_models.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/test_cache.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/test_events.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/test_exceptions.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/test_managers.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/test_requestlog.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/tests/test_types.py +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/uv.lock +0 -0
- {mreg_api-0.7.0 → mreg_api-0.8.0}/zensical.toml +0 -0
|
@@ -5,7 +5,28 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
-
## Unreleased
|
|
8
|
+
<!-- ## Unreleased -->
|
|
9
|
+
|
|
10
|
+
## [0.8.0](https://github.com/unioslo/mreg-api/releases/tag/0.8.0) - 2026-10-15
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Status-based HTTP error classes, all subclassing `exceptions.HTTPStatusError`:
|
|
15
|
+
- `exceptions.ClientError` (4xx) with subclasses `BadRequestError` (400), `UnauthorizedError` (401), `ForbiddenError` (403), `NotFoundError` (404) and `ConflictError` (409).
|
|
16
|
+
- `exceptions.ServerError` (5xx).
|
|
17
|
+
- `exceptions.http_error_class(status_code)` to look up the error class for a status code.
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
|
|
21
|
+
- **BREAKING**: HTTP errors are now classified by status code instead of HTTP method. Failed requests raise a status-based subclass of `HTTPStatusError` (see Added). The HTTP method is still available via `exc.request.method`.
|
|
22
|
+
- **BREAKING**: `MregClient.network.community.get_by_id(required=False)` now only returns `None` on 404. Other errors (e.g. 403, 5xx) are raised. `required=True` raises `NotFoundError` instead of `GetError` on 404.
|
|
23
|
+
- **BREAKING**: `exceptions.LoginFailedError` and `exceptions.InvalidAuthTokenError` now subclass `exceptions.UnauthorizedError`. `InvalidAuthTokenError` previously subclassed `LoginFailedError`.
|
|
24
|
+
|
|
25
|
+
### Removed
|
|
26
|
+
|
|
27
|
+
- **BREAKING**: Method-based HTTP errors `exceptions.GetError`, `PostError`, `PatchError` and `DeleteError`, along with `exceptions.ERROR_MAPPING` and `exceptions.determine_http_error_class()`. Catch the status code-based classes instead (e.g. `NotFoundError`, `ConflictError` for specific statuses, `ClientError` for any 4xx response, `ServerError` for any 5xx response, or `HTTPStatusError` for any failed request).
|
|
28
|
+
|
|
29
|
+
## [0.7.0](https://github.com/unioslo/mreg-api/releases/tag/0.7.0) - 2026-10-13
|
|
9
30
|
|
|
10
31
|
### Added
|
|
11
32
|
|
|
@@ -33,32 +33,38 @@ except MregApiBaseError as exc:
|
|
|
33
33
|
|
|
34
34
|
## Catching HTTP status errors
|
|
35
35
|
|
|
36
|
-
HTTP operations against the server raise a subclass of [`HTTPStatusError`][mreg_api.exceptions.HTTPStatusError]
|
|
36
|
+
HTTP operations against the server raise a subclass of [`HTTPStatusError`][mreg_api.exceptions.HTTPStatusError] based on the response status code, regardless of the HTTP method used:
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
- [`ClientError`][mreg_api.exceptions.ClientError] for 4xx responses, with dedicated subclasses for common status codes:
|
|
39
|
+
- [`BadRequestError`][mreg_api.exceptions.BadRequestError] for 400 responses (e.g. invalid field values)
|
|
40
|
+
- [`UnauthorizedError`][mreg_api.exceptions.UnauthorizedError] for 401 responses (e.g. a missing, invalid, or expired token)
|
|
41
|
+
- [`ForbiddenError`][mreg_api.exceptions.ForbiddenError] for 403 responses
|
|
42
|
+
- [`NotFoundError`][mreg_api.exceptions.NotFoundError] for 404 responses
|
|
43
|
+
- [`ConflictError`][mreg_api.exceptions.ConflictError] for 409 responses
|
|
44
|
+
- [`ServerError`][mreg_api.exceptions.ServerError] for 5xx responses
|
|
39
45
|
|
|
40
|
-
|
|
41
|
-
- [`PostError`][mreg_api.exceptions.PostError] for POST requests
|
|
42
|
-
- [`PatchError`][mreg_api.exceptions.PatchError] for PATCH requests
|
|
43
|
-
- [`DeleteError`][mreg_api.exceptions.DeleteError] for DELETE requests
|
|
46
|
+
Other status codes raise the nearest parent class; use `exc.status_code` to inspect the exact code, and `exc.request.method` if you need the HTTP method.
|
|
44
47
|
|
|
45
|
-
|
|
48
|
+
Authentication errors subclass `UnauthorizedError`: `login()` raises [`LoginFailedError`][mreg_api.exceptions.LoginFailedError] on rejected credentials, and `test_auth()` raises [`InvalidAuthTokenError`][mreg_api.exceptions.InvalidAuthTokenError] on a rejected token.
|
|
49
|
+
|
|
50
|
+
For example:
|
|
46
51
|
|
|
47
52
|
``` python
|
|
48
53
|
from mreg_api import MregClient
|
|
49
|
-
from mreg_api.exceptions import
|
|
54
|
+
from mreg_api.exceptions import ClientError, ConflictError, ServerError
|
|
50
55
|
|
|
51
56
|
client = MregClient(url="https://mreg.example.com")
|
|
52
57
|
|
|
53
58
|
try:
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
+
client.host.update("myhost.example.com", name="taken.example.com")
|
|
60
|
+
except ConflictError as exc:
|
|
61
|
+
# 409: the new name is already in use.
|
|
62
|
+
...
|
|
63
|
+
except ClientError as exc:
|
|
64
|
+
# Any other 4xx response.
|
|
59
65
|
...
|
|
60
|
-
except
|
|
61
|
-
#
|
|
66
|
+
except ServerError as exc:
|
|
67
|
+
# 5xx response.
|
|
62
68
|
...
|
|
63
69
|
```
|
|
64
70
|
|
|
@@ -61,7 +61,7 @@ host = client.host.get(123) # by ID
|
|
|
61
61
|
host = client.host.get(host) # refresh a model object
|
|
62
62
|
```
|
|
63
63
|
|
|
64
|
-
By default a missing resource
|
|
64
|
+
By default a missing resource raises [`EntityNotFound`][mreg_api.exceptions.EntityNotFound]. Pass `required=False` to return `None` instead:
|
|
65
65
|
|
|
66
66
|
``` python
|
|
67
67
|
host = client.host.get("myhost", required=False)
|
|
@@ -84,7 +84,7 @@ n = client.host.count(name__startswith="test-")
|
|
|
84
84
|
|
|
85
85
|
### Creating
|
|
86
86
|
|
|
87
|
-
`create` takes keyword arguments matching the model's fields. Every create method returns the created object on success.
|
|
87
|
+
`create` takes keyword arguments matching the model's fields. Every create method returns the created object on success. An [`HTTPStatusError`][mreg_api.exceptions.HTTPStatusError] subclass is raised if the server rejects the creation (e.g. [`ConflictError`][mreg_api.exceptions.ConflictError] if it already exists).
|
|
88
88
|
|
|
89
89
|
``` python
|
|
90
90
|
host = client.host.create(
|
|
@@ -96,7 +96,7 @@ host = client.host.create(
|
|
|
96
96
|
|
|
97
97
|
### Updating
|
|
98
98
|
|
|
99
|
-
`update` accepts a model object or an identifier (name, ID), plus the fields to change. The available fields vary depending on the resource.
|
|
99
|
+
`update` accepts a model object or an identifier (name, ID), plus the fields to change. The available fields vary depending on the resource. An [`HTTPStatusError`][mreg_api.exceptions.HTTPStatusError] subclass is raised if the server rejects the update.
|
|
100
100
|
|
|
101
101
|
``` python
|
|
102
102
|
client.host.update(
|
|
@@ -117,7 +117,7 @@ refreshed = client.host.refresh(host)
|
|
|
117
117
|
|
|
118
118
|
### Deleting
|
|
119
119
|
|
|
120
|
-
`delete` accepts a model object or an identifier.
|
|
120
|
+
`delete` accepts a model object or an identifier. An [`HTTPStatusError`][mreg_api.exceptions.HTTPStatusError] subclass is raised if the server rejects the deletion.
|
|
121
121
|
|
|
122
122
|
``` python
|
|
123
123
|
client.host.delete(host) # by object
|
|
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
|
|
|
18
18
|
commit_id: str | None
|
|
19
19
|
__commit_id__: str | None
|
|
20
20
|
|
|
21
|
-
__version__ = version = '0.
|
|
22
|
-
__version_tuple__ = version_tuple = (0,
|
|
21
|
+
__version__ = version = '0.8.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 8, 0)
|
|
23
23
|
|
|
24
|
-
__commit_id__ = commit_id = '
|
|
24
|
+
__commit_id__ = commit_id = 'g7da738fc6'
|
|
@@ -46,8 +46,9 @@ from mreg_api.exceptions import InvalidAuthTokenError
|
|
|
46
46
|
from mreg_api.exceptions import LoginFailedError
|
|
47
47
|
from mreg_api.exceptions import MregValidationError
|
|
48
48
|
from mreg_api.exceptions import MultipleEntitiesFound
|
|
49
|
+
from mreg_api.exceptions import ResponseError
|
|
49
50
|
from mreg_api.exceptions import UnexpectedResponseError
|
|
50
|
-
from mreg_api.exceptions import
|
|
51
|
+
from mreg_api.exceptions import http_error_class
|
|
51
52
|
from mreg_api.managers import AtomManager
|
|
52
53
|
from mreg_api.managers import BacnetIDManager
|
|
53
54
|
from mreg_api.managers import CNAMEManager
|
|
@@ -157,7 +158,7 @@ def check_response(response: Response) -> None:
|
|
|
157
158
|
HTTPStatusError: If the response indicates an error.
|
|
158
159
|
"""
|
|
159
160
|
if not response.is_success:
|
|
160
|
-
raise
|
|
161
|
+
raise http_error_class(response.status_code)(response=response)
|
|
161
162
|
|
|
162
163
|
|
|
163
164
|
class PaginatedResponse(BaseModel):
|
|
@@ -448,7 +449,6 @@ class MregClient:
|
|
|
448
449
|
self.cache: MregApiCache[Response] = self._create_cache(_cache_config)
|
|
449
450
|
|
|
450
451
|
# State setup/reset
|
|
451
|
-
self._token: str | None = None
|
|
452
452
|
self.requests: RequestLog = RequestLog(maxsize=request_log_size)
|
|
453
453
|
self.events: EventLog = EventLog(max_size=event_log_size)
|
|
454
454
|
|
|
@@ -594,21 +594,22 @@ class MregClient:
|
|
|
594
594
|
|
|
595
595
|
"""
|
|
596
596
|
self.session.headers.update({Header.AUTH: f"Token {token}"})
|
|
597
|
-
self._token = token
|
|
598
597
|
|
|
599
598
|
def get_token(self) -> str | None:
|
|
600
|
-
"""Get the current authorization token if set.
|
|
599
|
+
"""Get the current authorization token if set. Strips the "Token " prefix.
|
|
601
600
|
|
|
602
601
|
Returns:
|
|
603
|
-
Token string or None if not
|
|
602
|
+
Token string or None if not set.
|
|
604
603
|
|
|
605
604
|
"""
|
|
606
|
-
|
|
605
|
+
token = self.session.headers.get(Header.AUTH, None)
|
|
606
|
+
if token:
|
|
607
|
+
return str(token).partition(" ")[2] # "Token abcd1234"
|
|
608
|
+
return None
|
|
607
609
|
|
|
608
610
|
def unset_token(self) -> None:
|
|
609
611
|
"""Unset the current authorization token."""
|
|
610
612
|
self.session.headers.pop(Header.AUTH, None)
|
|
611
|
-
self._token = None
|
|
612
613
|
|
|
613
614
|
def set_correlation_id(self, suffix: str) -> str:
|
|
614
615
|
"""Set correlation ID for request tracking.
|
|
@@ -702,15 +703,13 @@ class MregClient:
|
|
|
702
703
|
logger.warning("Failed to log out: %s", e)
|
|
703
704
|
|
|
704
705
|
def test_auth(self) -> None:
|
|
705
|
-
"""Test if the
|
|
706
|
+
"""Test if the client is authorized with the current token.
|
|
706
707
|
|
|
707
708
|
Does not handle connection errors.
|
|
708
709
|
|
|
709
710
|
Raises:
|
|
710
|
-
InvalidAuthTokenError: If the authorization test fails
|
|
711
|
-
|
|
712
|
-
Returns:
|
|
713
|
-
True if authorization is valid, False otherwise
|
|
711
|
+
InvalidAuthTokenError: If the authorization test fails (HTTP 401)
|
|
712
|
+
ResponseError: If the authorization test fails for any reason other than HTTP 401.
|
|
714
713
|
"""
|
|
715
714
|
try:
|
|
716
715
|
ret = self.session.get(
|
|
@@ -720,7 +719,9 @@ class MregClient:
|
|
|
720
719
|
)
|
|
721
720
|
ret.raise_for_status()
|
|
722
721
|
except httpx.HTTPStatusError as e:
|
|
723
|
-
|
|
722
|
+
if e.response.status_code == 401:
|
|
723
|
+
raise InvalidAuthTokenError(f"Authorization test failed: {e}", response=e.response) from e
|
|
724
|
+
raise ResponseError(f"Authorization test failed: {e}", response=e.response) from e
|
|
724
725
|
|
|
725
726
|
def request(
|
|
726
727
|
self,
|
|
@@ -13,7 +13,6 @@ from typing_extensions import deprecated
|
|
|
13
13
|
from typing_extensions import override
|
|
14
14
|
|
|
15
15
|
from mreg_api.__about__ import __version__
|
|
16
|
-
from mreg_api.types import HTTPMethod
|
|
17
16
|
|
|
18
17
|
logger = logging.getLogger(__name__)
|
|
19
18
|
|
|
@@ -210,20 +209,40 @@ class HTTPStatusError(ResponseError):
|
|
|
210
209
|
"""Server returned a 4xx or 5xx status code."""
|
|
211
210
|
|
|
212
211
|
|
|
213
|
-
class
|
|
214
|
-
"""
|
|
212
|
+
class ClientError(HTTPStatusError):
|
|
213
|
+
"""HTTP 4xx client error."""
|
|
215
214
|
|
|
216
215
|
|
|
217
|
-
class
|
|
218
|
-
"""
|
|
216
|
+
class ServerError(HTTPStatusError):
|
|
217
|
+
"""HTTP 5xx server error."""
|
|
219
218
|
|
|
220
219
|
|
|
221
|
-
class
|
|
222
|
-
"""
|
|
220
|
+
class BadRequestError(ClientError):
|
|
221
|
+
"""HTTP 400 Bad Request."""
|
|
223
222
|
|
|
224
223
|
|
|
225
|
-
class
|
|
226
|
-
"""
|
|
224
|
+
class UnauthorizedError(ClientError):
|
|
225
|
+
"""HTTP 401 Unauthorized."""
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class ForbiddenError(ClientError):
|
|
229
|
+
"""HTTP 403 Forbidden."""
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class NotFoundError(ClientError):
|
|
233
|
+
"""HTTP 404 Not Found."""
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class ConflictError(ClientError):
|
|
237
|
+
"""HTTP 409 Conflict."""
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class LoginFailedError(UnauthorizedError):
|
|
241
|
+
"""Login failed."""
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
class InvalidAuthTokenError(UnauthorizedError):
|
|
245
|
+
"""Invalid authentication token."""
|
|
227
246
|
|
|
228
247
|
|
|
229
248
|
class UnexpectedResponseError(ResponseError):
|
|
@@ -384,14 +403,6 @@ class InvalidIPv6Network(InvalidNetwork):
|
|
|
384
403
|
"""Entity is not a valid IPv6 network."""
|
|
385
404
|
|
|
386
405
|
|
|
387
|
-
class LoginFailedError(ResponseError):
|
|
388
|
-
"""Login failed."""
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
class InvalidAuthTokenError(LoginFailedError):
|
|
392
|
-
"""Invalid authentication token."""
|
|
393
|
-
|
|
394
|
-
|
|
395
406
|
class CacheError(MregApiBaseError):
|
|
396
407
|
"""Error related to caching."""
|
|
397
408
|
|
|
@@ -539,25 +550,30 @@ def parse_mreg_error(resp: Response) -> MREGErrorResponse | None:
|
|
|
539
550
|
return None
|
|
540
551
|
|
|
541
552
|
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
553
|
+
# Status codes with a dedicated exception class. Other 4xx/5xx codes
|
|
554
|
+
# fall back to ClientError/ServerError.
|
|
555
|
+
STATUS_ERROR_MAPPING: dict[int, type[HTTPStatusError]] = {
|
|
556
|
+
400: BadRequestError,
|
|
557
|
+
401: UnauthorizedError,
|
|
558
|
+
403: ForbiddenError,
|
|
559
|
+
404: NotFoundError,
|
|
560
|
+
409: ConflictError,
|
|
547
561
|
}
|
|
548
562
|
|
|
549
563
|
|
|
550
|
-
def
|
|
551
|
-
"""Get the appropriate exception class for a given HTTP
|
|
564
|
+
def http_error_class(status_code: int) -> type[HTTPStatusError]:
|
|
565
|
+
"""Get the appropriate exception class for a given HTTP status code.
|
|
552
566
|
|
|
553
567
|
Args:
|
|
554
|
-
|
|
568
|
+
status_code (int): The HTTP status code.
|
|
555
569
|
|
|
556
570
|
Returns:
|
|
557
|
-
The exception class corresponding to the
|
|
571
|
+
type[HTTPStatusError]: The exception class corresponding to the status code.
|
|
558
572
|
"""
|
|
559
|
-
if t :=
|
|
573
|
+
if t := STATUS_ERROR_MAPPING.get(status_code):
|
|
560
574
|
return t
|
|
561
|
-
|
|
562
|
-
|
|
575
|
+
if 400 <= status_code < 500:
|
|
576
|
+
return ClientError
|
|
577
|
+
if 500 <= status_code < 600:
|
|
578
|
+
return ServerError
|
|
563
579
|
return HTTPStatusError
|
|
@@ -50,10 +50,11 @@ from mreg_api.exceptions import EntityAlreadyExists
|
|
|
50
50
|
from mreg_api.exceptions import EntityNotFound
|
|
51
51
|
from mreg_api.exceptions import EntityRelationMissing
|
|
52
52
|
from mreg_api.exceptions import ForceMissing
|
|
53
|
-
from mreg_api.exceptions import
|
|
53
|
+
from mreg_api.exceptions import HTTPStatusError
|
|
54
54
|
from mreg_api.exceptions import InputFailure
|
|
55
55
|
from mreg_api.exceptions import InternalError
|
|
56
56
|
from mreg_api.exceptions import MultipleEntitiesFound
|
|
57
|
+
from mreg_api.exceptions import NotFoundError
|
|
57
58
|
from mreg_api.exceptions import UnexpectedResponseError
|
|
58
59
|
from mreg_api.models import CNAME
|
|
59
60
|
from mreg_api.models import MX
|
|
@@ -592,7 +593,7 @@ class WriteResourceManager(ResourceManager[T], ABC):
|
|
|
592
593
|
data (dict[str, Any]): The data to PATCH to the resource endpoint.
|
|
593
594
|
params (QueryParams | None): Optional query parameters to include in the PATCH request.
|
|
594
595
|
|
|
595
|
-
Raises `
|
|
596
|
+
Raises `HTTPStatusError` (from the client) if the server rejects the patch.
|
|
596
597
|
"""
|
|
597
598
|
_ = self._client.patch(self._endpoint_with_path_param(obj), json=data, params=params)
|
|
598
599
|
|
|
@@ -872,6 +873,7 @@ class HostManager(NamedResourceManager[Host], HistoryManager[Host]):
|
|
|
872
873
|
ptr_fallback (bool): When True (default), fall back to PTR override if no host is found.
|
|
873
874
|
|
|
874
875
|
Raises:
|
|
876
|
+
ValueError: If the provided IP address is not valid.
|
|
875
877
|
MultipleEntitiesFound: If more than one host matches the IP address.
|
|
876
878
|
EntityNotFound: If `required` is True and no host is found.
|
|
877
879
|
"""
|
|
@@ -902,6 +904,7 @@ class HostManager(NamedResourceManager[Host], HistoryManager[Host]):
|
|
|
902
904
|
required (bool): When True (default), raise EntityNotFound if not found.
|
|
903
905
|
|
|
904
906
|
Raises:
|
|
907
|
+
ValueError: If the provided MAC address is not valid.
|
|
905
908
|
EntityNotFound: If `required` is True and no host is found.
|
|
906
909
|
"""
|
|
907
910
|
addr = MacAddress.parse_or_raise(mac)
|
|
@@ -920,6 +923,9 @@ class HostManager(NamedResourceManager[Host], HistoryManager[Host]):
|
|
|
920
923
|
Args:
|
|
921
924
|
ip (str | IP_AddressT): IP address to filter by.
|
|
922
925
|
|
|
926
|
+
Raises:
|
|
927
|
+
ValueError: If the provided IP address is not valid.
|
|
928
|
+
|
|
923
929
|
Returns:
|
|
924
930
|
list[Host]: List of hosts matching the IP address.
|
|
925
931
|
"""
|
|
@@ -936,6 +942,12 @@ class HostManager(NamedResourceManager[Host], HistoryManager[Host]):
|
|
|
936
942
|
|
|
937
943
|
Args:
|
|
938
944
|
mac (str | MacAddress): The MAC address to filter by.
|
|
945
|
+
|
|
946
|
+
Raises:
|
|
947
|
+
ValueError: If the provided MAC address is not valid.
|
|
948
|
+
|
|
949
|
+
Returns:
|
|
950
|
+
list[Host]: List of hosts matching the MAC address.
|
|
939
951
|
"""
|
|
940
952
|
addr = MacAddress.parse_or_raise(mac)
|
|
941
953
|
return self._fetch_list_by_field("ipaddresses__macaddress", str(addr))
|
|
@@ -2238,7 +2250,7 @@ class CommunityManager:
|
|
|
2238
2250
|
required (bool): When True (default), raise EntityNotFound if not found.
|
|
2239
2251
|
|
|
2240
2252
|
Raises:
|
|
2241
|
-
|
|
2253
|
+
NotFoundError: If `required` is True and the community is not found.
|
|
2242
2254
|
"""
|
|
2243
2255
|
nw_addr = self._resolve_network_address(network)
|
|
2244
2256
|
try:
|
|
@@ -2246,7 +2258,7 @@ class CommunityManager:
|
|
|
2246
2258
|
return self._client.get_typed(
|
|
2247
2259
|
Endpoint.NetworkCommunity.with_params(nw_addr, community_id), Community
|
|
2248
2260
|
)
|
|
2249
|
-
except
|
|
2261
|
+
except NotFoundError:
|
|
2250
2262
|
if required:
|
|
2251
2263
|
raise
|
|
2252
2264
|
return None
|
|
@@ -2277,7 +2289,7 @@ class CommunityManager:
|
|
|
2277
2289
|
return self.get_by_id(community, network, required=required)
|
|
2278
2290
|
else:
|
|
2279
2291
|
return self.get_by_name(community, network, required=required)
|
|
2280
|
-
except (EntityNotFound,
|
|
2292
|
+
except (EntityNotFound, NotFoundError) as e:
|
|
2281
2293
|
if required:
|
|
2282
2294
|
raise EntityNotFound(
|
|
2283
2295
|
f"Community {community!r} not found in network {network!r}.",
|
|
@@ -2432,8 +2444,12 @@ class NetworkManager(WriteResourceManager[Network]):
|
|
|
2432
2444
|
required (bool): When True (default), raise EntityNotFound if not found.
|
|
2433
2445
|
|
|
2434
2446
|
Raises:
|
|
2447
|
+
ValueError: If the provided IP address is not valid.
|
|
2435
2448
|
EntityNotFound: If `required` is True and no network is found.
|
|
2436
|
-
|
|
2449
|
+
|
|
2450
|
+
Returns:
|
|
2451
|
+
Network | None: The network containing the IP address, or None if not found and `required` is False.
|
|
2452
|
+
""" # noqa: E501
|
|
2437
2453
|
addr = str(NetworkOrIP.parse_or_raise(str(ip), mode="ip"))
|
|
2438
2454
|
resp = self._client.get(Endpoint.NetworksByIP.with_id(addr), ok404=True)
|
|
2439
2455
|
if not resp:
|
|
@@ -2655,6 +2671,10 @@ class NetworkManager(WriteResourceManager[Network]):
|
|
|
2655
2671
|
network (str | int | Network): Network reference (address, numeric ID, or Network instance).
|
|
2656
2672
|
start (str): The start IP address of the excluded range.
|
|
2657
2673
|
end (str): The end IP address of the excluded range.
|
|
2674
|
+
|
|
2675
|
+
Raises:
|
|
2676
|
+
ValueError: If the start or end IPs are not valid IP addresses.
|
|
2677
|
+
InputFailure: If the start and end IP addresses are not of the same version.
|
|
2658
2678
|
"""
|
|
2659
2679
|
network = self._resolve(network)
|
|
2660
2680
|
start_ip = NetworkOrIP.parse_or_raise(start, mode="ip")
|
|
@@ -2846,6 +2866,12 @@ class IPAddressManager(WriteResourceManager[IPAddress]):
|
|
|
2846
2866
|
|
|
2847
2867
|
Args:
|
|
2848
2868
|
mac (str | MacAddress): The MAC address to filter by.
|
|
2869
|
+
|
|
2870
|
+
Raises:
|
|
2871
|
+
ValueError: If the provided MAC address is not valid.
|
|
2872
|
+
|
|
2873
|
+
Returns:
|
|
2874
|
+
list[IPAddress]: List of IP addresses with the given MAC address.
|
|
2849
2875
|
"""
|
|
2850
2876
|
addr = MacAddress.parse_or_raise(mac)
|
|
2851
2877
|
return self._fetch_list_by_field("macaddress", str(addr))
|
|
@@ -4483,11 +4509,7 @@ class DelegationManager:
|
|
|
4483
4509
|
cls = self._model_for(zone)
|
|
4484
4510
|
try:
|
|
4485
4511
|
return self._get(self._endpoint_with_name(zone, name), cls)
|
|
4486
|
-
except
|
|
4487
|
-
# get_typed raises GetError on a 404; only a missing delegation is a
|
|
4488
|
-
# "not found" — let any other transport error propagate unchanged.
|
|
4489
|
-
if e.status_code != 404:
|
|
4490
|
-
raise
|
|
4512
|
+
except NotFoundError as e:
|
|
4491
4513
|
if required:
|
|
4492
4514
|
raise EntityNotFound(
|
|
4493
4515
|
f"Could not find delegation {name!r} in zone {zone.name!r}", model=cls, identifier=name
|
|
@@ -4906,7 +4928,7 @@ class LDAPHealthManager(GetManager[LDAPHealth]):
|
|
|
4906
4928
|
try:
|
|
4907
4929
|
self._client.get(Endpoint.HealthLDAP)
|
|
4908
4930
|
return LDAPHealth(status="OK")
|
|
4909
|
-
except
|
|
4931
|
+
except HTTPStatusError as e:
|
|
4910
4932
|
# LDAP being down causes a 503 error, which we should
|
|
4911
4933
|
# interpret as a valid response, not an error.
|
|
4912
4934
|
if e.status_code == 503:
|
|
@@ -19,7 +19,7 @@ from typing import Any
|
|
|
19
19
|
import pytest
|
|
20
20
|
|
|
21
21
|
from mreg_api.client import MregClient
|
|
22
|
-
from mreg_api.exceptions import
|
|
22
|
+
from mreg_api.exceptions import HTTPStatusError
|
|
23
23
|
from mreg_api.models import Zone
|
|
24
24
|
|
|
25
25
|
|
|
@@ -219,8 +219,7 @@ def seed_test_network(
|
|
|
219
219
|
network=test_network,
|
|
220
220
|
description="Integration test seed network",
|
|
221
221
|
)
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
except PostError:
|
|
222
|
+
resource_tracker.add(lambda: client.network.delete(net))
|
|
223
|
+
except HTTPStatusError:
|
|
225
224
|
pass # overlaps with existing subnets from a previous run; acceptable
|
|
226
225
|
yield
|
|
@@ -6,10 +6,10 @@ import pytest
|
|
|
6
6
|
from inline_snapshot import snapshot
|
|
7
7
|
|
|
8
8
|
from mreg_api.client import MregClient
|
|
9
|
-
from mreg_api.exceptions import
|
|
9
|
+
from mreg_api.exceptions import ConflictError
|
|
10
10
|
from mreg_api.exceptions import EntityAlreadyExists
|
|
11
11
|
from mreg_api.exceptions import EntityNotFound
|
|
12
|
-
from mreg_api.exceptions import
|
|
12
|
+
from mreg_api.exceptions import NotFoundError
|
|
13
13
|
from mreg_api.models import Zone
|
|
14
14
|
|
|
15
15
|
if TYPE_CHECKING:
|
|
@@ -341,7 +341,7 @@ def test_add_host_conflict(
|
|
|
341
341
|
|
|
342
342
|
# int hostgroup reference exercises the ID branch of _resolve_hostgroup_name
|
|
343
343
|
client.hostgroup.add_host(group.id, host)
|
|
344
|
-
with pytest.raises(
|
|
344
|
+
with pytest.raises(ConflictError) as excinfo:
|
|
345
345
|
client.hostgroup.add_host(group.id, host)
|
|
346
346
|
|
|
347
347
|
msg = excinfo.exconly()
|
|
@@ -351,7 +351,7 @@ def test_add_host_conflict(
|
|
|
351
351
|
.replace(integration_client.url, "<server-url>")
|
|
352
352
|
)
|
|
353
353
|
assert msg == snapshot("""\
|
|
354
|
-
mreg_api.exceptions.
|
|
354
|
+
mreg_api.exceptions.ConflictError: 409 Conflict: POST <server-url>/api/v1/hostgroups/<hostgroup-name>/hosts/
|
|
355
355
|
1 error:
|
|
356
356
|
<host-name> already in hosts (conflict)\
|
|
357
357
|
""")
|
|
@@ -380,7 +380,7 @@ def test_remove_host_not_member(
|
|
|
380
380
|
resource_tracker.add(lambda: client.hostgroup.delete(group_name))
|
|
381
381
|
|
|
382
382
|
# int hostgroup reference exercises the ID branch of _resolve_hostgroup_name
|
|
383
|
-
with pytest.raises(
|
|
383
|
+
with pytest.raises(NotFoundError) as excinfo:
|
|
384
384
|
client.hostgroup.remove_host(group.id, host)
|
|
385
385
|
|
|
386
386
|
msg = excinfo.exconly()
|
|
@@ -390,7 +390,7 @@ def test_remove_host_not_member(
|
|
|
390
390
|
.replace(integration_client.url, "<server-url>")
|
|
391
391
|
)
|
|
392
392
|
assert msg == snapshot("""\
|
|
393
|
-
mreg_api.exceptions.
|
|
393
|
+
mreg_api.exceptions.NotFoundError: 404 Not Found: DELETE <server-url>/api/v1/hostgroups/<hostgroup-name>/hosts/<host-name>
|
|
394
394
|
1 error:
|
|
395
395
|
'<host-name>' is not a member of '<hostgroup-name>'. (not_found)\
|
|
396
396
|
""")
|
|
@@ -454,14 +454,14 @@ def test_remove_owner_nonexistent(
|
|
|
454
454
|
name = f"{test_prefix}hg-remove-owner-nonexistent"
|
|
455
455
|
group = client.hostgroup.create(name=name, description="test_remove_owner_nonexistent")
|
|
456
456
|
resource_tracker.add(lambda: client.hostgroup.delete(name))
|
|
457
|
-
with pytest.raises(
|
|
457
|
+
with pytest.raises(NotFoundError) as excinfo:
|
|
458
458
|
client.hostgroup.remove_owner(group, "exampleuser1")
|
|
459
459
|
msg = excinfo.exconly()
|
|
460
460
|
msg = msg.replace(name, "<hostgroup-name>").replace(integration_client.url, "<server-url>")
|
|
461
461
|
|
|
462
462
|
assert msg == snapshot(
|
|
463
463
|
"""\
|
|
464
|
-
mreg_api.exceptions.
|
|
464
|
+
mreg_api.exceptions.NotFoundError: 404 Not Found: DELETE <server-url>/api/v1/hostgroups/<hostgroup-name>/owners/exampleuser1
|
|
465
465
|
1 error:
|
|
466
466
|
'exampleuser1' is not an owner of '<hostgroup-name>'. (not_found)\
|
|
467
467
|
"""
|
|
@@ -482,13 +482,13 @@ def test_add_owner_conflict(
|
|
|
482
482
|
resource_tracker.add(lambda: client.hostgroup.delete(name))
|
|
483
483
|
|
|
484
484
|
client.hostgroup.add_owner(group, "example-user-1")
|
|
485
|
-
with pytest.raises(
|
|
485
|
+
with pytest.raises(ConflictError) as excinfo:
|
|
486
486
|
client.hostgroup.add_owner(group, "example-user-1")
|
|
487
487
|
|
|
488
488
|
msg = excinfo.exconly()
|
|
489
489
|
msg = msg.replace(name, "<hostgroup-name>").replace(integration_client.url, "<server-url>")
|
|
490
490
|
assert msg == snapshot("""\
|
|
491
|
-
mreg_api.exceptions.
|
|
491
|
+
mreg_api.exceptions.ConflictError: 409 Conflict: POST <server-url>/api/v1/hostgroups/<hostgroup-name>/owners/
|
|
492
492
|
1 error:
|
|
493
493
|
example-user-1 already in owners (conflict)\
|
|
494
494
|
""")
|
|
@@ -8,10 +8,10 @@ import pytest
|
|
|
8
8
|
from inline_snapshot import snapshot
|
|
9
9
|
|
|
10
10
|
from mreg_api.client import MregClient
|
|
11
|
+
from mreg_api.exceptions import ConflictError
|
|
11
12
|
from mreg_api.exceptions import EntityAlreadyExists
|
|
12
13
|
from mreg_api.exceptions import EntityNotFound
|
|
13
|
-
from mreg_api.exceptions import
|
|
14
|
-
from mreg_api.exceptions import PatchError
|
|
14
|
+
from mreg_api.exceptions import NotFoundError
|
|
15
15
|
from mreg_api.models.models import Network
|
|
16
16
|
|
|
17
17
|
if TYPE_CHECKING:
|
|
@@ -197,7 +197,7 @@ def test_update_network_range_overlaps_existing(integration_client: MregClient)
|
|
|
197
197
|
net2,
|
|
198
198
|
description="integration test range overlap resize net2",
|
|
199
199
|
)
|
|
200
|
-
with pytest.raises(
|
|
200
|
+
with pytest.raises(ConflictError) as excinfo:
|
|
201
201
|
integration_client.network.update(net1, network="172.16.0.0/23")
|
|
202
202
|
msg = excinfo.value.formatted_message().replace(integration_client.url, "<URL>")
|
|
203
203
|
assert msg == snapshot("""\
|
|
@@ -321,7 +321,7 @@ def test_community_get_nonexistent_by_id_raises(
|
|
|
321
321
|
integration_client: MregClient,
|
|
322
322
|
test_network: str,
|
|
323
323
|
) -> None:
|
|
324
|
-
"""CommunityManager.get() always returns EntityNotFound, even if the underlyinng `get_by_id` raises `
|
|
324
|
+
"""CommunityManager.get() always returns EntityNotFound, even if the underlyinng `get_by_id` raises `NotFoundError`."""
|
|
325
325
|
with pytest.raises(EntityNotFound):
|
|
326
326
|
integration_client.network.community.get(999999, test_network)
|
|
327
327
|
|
|
@@ -338,8 +338,8 @@ def test_community_get_by_id_nonexistent_raises(
|
|
|
338
338
|
integration_client: MregClient,
|
|
339
339
|
test_network: str,
|
|
340
340
|
) -> None:
|
|
341
|
-
"""CommunityManager.get_by_id raises `
|
|
342
|
-
with pytest.raises(
|
|
341
|
+
"""CommunityManager.get_by_id raises `NotFoundError` due to 404 error from the server."""
|
|
342
|
+
with pytest.raises(NotFoundError) as excinfo:
|
|
343
343
|
integration_client.network.community.get_by_id(999999, test_network)
|
|
344
344
|
|
|
345
345
|
msg = excinfo.exconly()
|
|
@@ -349,7 +349,7 @@ def test_community_get_by_id_nonexistent_raises(
|
|
|
349
349
|
.replace(integration_client.url, "<server-url>")
|
|
350
350
|
)
|
|
351
351
|
assert msg == snapshot("""\
|
|
352
|
-
mreg_api.exceptions.
|
|
352
|
+
mreg_api.exceptions.NotFoundError: 404 Not Found: GET <server-url>/api/v1/networks/<network>/communities/999999
|
|
353
353
|
1 error:
|
|
354
354
|
Not found. (not_found)\
|
|
355
355
|
""")
|
|
@@ -6,11 +6,11 @@ import pytest
|
|
|
6
6
|
from inline_snapshot import snapshot
|
|
7
7
|
|
|
8
8
|
from mreg_api.client import MregClient
|
|
9
|
-
from mreg_api.exceptions import
|
|
9
|
+
from mreg_api.exceptions import ConflictError
|
|
10
10
|
from mreg_api.exceptions import EntityAlreadyExists
|
|
11
11
|
from mreg_api.exceptions import EntityNotFound
|
|
12
12
|
from mreg_api.exceptions import ForceMissing
|
|
13
|
-
from mreg_api.exceptions import
|
|
13
|
+
from mreg_api.exceptions import NotFoundError
|
|
14
14
|
from mreg_api.models import Zone
|
|
15
15
|
|
|
16
16
|
if TYPE_CHECKING:
|
|
@@ -265,9 +265,9 @@ def test_add_atom_conflict(
|
|
|
265
265
|
resource_tracker.add(lambda: client.role.delete(role_name))
|
|
266
266
|
|
|
267
267
|
client.role.add_atom(role, atom)
|
|
268
|
-
# Adding the same atom twice now surfaces the server's 409 as a
|
|
268
|
+
# Adding the same atom twice now surfaces the server's 409 as a ConflictError
|
|
269
269
|
# (previously translated to EntityAlreadyExists).
|
|
270
|
-
with pytest.raises(
|
|
270
|
+
with pytest.raises(ConflictError) as excinfo:
|
|
271
271
|
client.role.add_atom(role, atom)
|
|
272
272
|
|
|
273
273
|
msg = excinfo.exconly()
|
|
@@ -277,7 +277,7 @@ def test_add_atom_conflict(
|
|
|
277
277
|
.replace(integration_client.url, "<server-url>")
|
|
278
278
|
)
|
|
279
279
|
assert msg == snapshot("""\
|
|
280
|
-
mreg_api.exceptions.
|
|
280
|
+
mreg_api.exceptions.ConflictError: 409 Conflict: POST <server-url>/api/v1/hostpolicy/roles/<role-name>/atoms/
|
|
281
281
|
1 error:
|
|
282
282
|
<atom-name> already in atoms (conflict)\
|
|
283
283
|
""")
|
|
@@ -365,7 +365,7 @@ def test_add_host_conflict(
|
|
|
365
365
|
resource_tracker.add(lambda: client.role.remove_host(role.id, host_name))
|
|
366
366
|
|
|
367
367
|
client.role.add_host(role, host)
|
|
368
|
-
with pytest.raises(
|
|
368
|
+
with pytest.raises(ConflictError) as excinfo:
|
|
369
369
|
client.role.add_host(role, host)
|
|
370
370
|
|
|
371
371
|
msg = excinfo.exconly()
|
|
@@ -375,7 +375,7 @@ def test_add_host_conflict(
|
|
|
375
375
|
.replace(integration_client.url, "<server-url>")
|
|
376
376
|
)
|
|
377
377
|
assert msg == snapshot("""\
|
|
378
|
-
mreg_api.exceptions.
|
|
378
|
+
mreg_api.exceptions.ConflictError: 409 Conflict: POST <server-url>/api/v1/hostpolicy/roles/<role-name>/hosts/
|
|
379
379
|
1 error:
|
|
380
380
|
<host-name> already in hosts (conflict)\
|
|
381
381
|
""")
|
|
@@ -403,7 +403,7 @@ def test_remove_host_not_member(
|
|
|
403
403
|
resource_tracker.add(lambda: client.host.delete(host_name))
|
|
404
404
|
resource_tracker.add(lambda: client.role.delete(role_name))
|
|
405
405
|
|
|
406
|
-
with pytest.raises(
|
|
406
|
+
with pytest.raises(NotFoundError) as excinfo:
|
|
407
407
|
client.role.remove_host(role, host)
|
|
408
408
|
|
|
409
409
|
msg = excinfo.exconly()
|
|
@@ -413,7 +413,7 @@ def test_remove_host_not_member(
|
|
|
413
413
|
.replace(integration_client.url, "<server-url>")
|
|
414
414
|
)
|
|
415
415
|
assert msg == snapshot("""\
|
|
416
|
-
mreg_api.exceptions.
|
|
416
|
+
mreg_api.exceptions.NotFoundError: 404 Not Found: DELETE <server-url>/api/v1/hostpolicy/roles/<role-name>/hosts/<host-name>
|
|
417
417
|
1 error:
|
|
418
418
|
'<host-name>' is not a member of '<role-name>'. (not_found)\
|
|
419
419
|
""")
|
|
@@ -13,17 +13,23 @@ from pytest_httpserver import HTTPServer
|
|
|
13
13
|
from werkzeug import Response
|
|
14
14
|
|
|
15
15
|
from mreg_api.__about__ import __version__
|
|
16
|
+
from mreg_api.client import Header
|
|
16
17
|
from mreg_api.client import MregClient
|
|
17
18
|
from mreg_api.client import check_response
|
|
18
19
|
from mreg_api.client import strip_none
|
|
19
20
|
from mreg_api.endpoints import Endpoint
|
|
20
21
|
from mreg_api.events import EventKind
|
|
21
|
-
from mreg_api.exceptions import
|
|
22
|
-
from mreg_api.exceptions import
|
|
22
|
+
from mreg_api.exceptions import BadRequestError
|
|
23
|
+
from mreg_api.exceptions import ClientError
|
|
24
|
+
from mreg_api.exceptions import ConflictError
|
|
25
|
+
from mreg_api.exceptions import ForbiddenError
|
|
26
|
+
from mreg_api.exceptions import InvalidAuthTokenError
|
|
23
27
|
from mreg_api.exceptions import MregValidationError
|
|
24
28
|
from mreg_api.exceptions import MultipleEntitiesFound
|
|
25
|
-
from mreg_api.exceptions import
|
|
26
|
-
from mreg_api.exceptions import
|
|
29
|
+
from mreg_api.exceptions import NotFoundError
|
|
30
|
+
from mreg_api.exceptions import ResponseError
|
|
31
|
+
from mreg_api.exceptions import ServerError
|
|
32
|
+
from mreg_api.exceptions import UnauthorizedError
|
|
27
33
|
from mreg_api.managers import HostManager
|
|
28
34
|
from mreg_api.models.models import Host
|
|
29
35
|
from mreg_api.types import HTTPMethod
|
|
@@ -77,7 +83,7 @@ def test_client_caching(httpserver: HTTPServer) -> None:
|
|
|
77
83
|
resp = client.get(str(Endpoint.Hosts), params=None, ok404=False)
|
|
78
84
|
|
|
79
85
|
# Ensure that trying to access the endpoint now raises an exception (oneshot)
|
|
80
|
-
with pytest.raises(
|
|
86
|
+
with pytest.raises(ServerError) as exc_info:
|
|
81
87
|
client._do_get(str(Endpoint.Hosts), params=None, ok404=False)
|
|
82
88
|
assert "No handler found" in exc_info.value.response.text
|
|
83
89
|
assert exc_info.value.response.status_code == snapshot(500)
|
|
@@ -817,6 +823,74 @@ def test_client_manager_composition_usage(client: MregClient, httpserver: HTTPSe
|
|
|
817
823
|
)
|
|
818
824
|
|
|
819
825
|
|
|
826
|
+
def test_client_test_auth_ok(client: MregClient, httpserver: HTTPServer) -> None:
|
|
827
|
+
"""Test successful MregClient.test_auth."""
|
|
828
|
+
assert isinstance(client.host, HostManager)
|
|
829
|
+
|
|
830
|
+
httpserver.expect_oneshot_request(
|
|
831
|
+
"/api/v1/hosts/", headers={Header.AUTH: "Token abcd1234"}
|
|
832
|
+
).respond_with_response(Response(status=200))
|
|
833
|
+
|
|
834
|
+
client.set_token("abcd1234")
|
|
835
|
+
assert client.get_token() == "abcd1234" # ensure we set it correctly
|
|
836
|
+
|
|
837
|
+
client.test_auth()
|
|
838
|
+
|
|
839
|
+
|
|
840
|
+
def test_client_test_auth_no_token(client: MregClient, httpserver: HTTPServer) -> None:
|
|
841
|
+
"""Test MregClient.test_auth with no token set."""
|
|
842
|
+
assert isinstance(client.host, HostManager)
|
|
843
|
+
|
|
844
|
+
httpserver.expect_oneshot_request("/api/v1/hosts/").respond_with_response(Response(status=401))
|
|
845
|
+
|
|
846
|
+
client.unset_token() # ensure we are starting without a token
|
|
847
|
+
with pytest.raises(InvalidAuthTokenError):
|
|
848
|
+
client.test_auth()
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
def test_client_test_auth_invalid_token(client: MregClient, httpserver: HTTPServer) -> None:
|
|
852
|
+
"""Test MregClient.test_auth with an invalid token."""
|
|
853
|
+
assert isinstance(client.host, HostManager)
|
|
854
|
+
|
|
855
|
+
# Always respond with 401
|
|
856
|
+
httpserver.expect_oneshot_request("/api/v1/hosts/").respond_with_response(Response(status=401))
|
|
857
|
+
|
|
858
|
+
client.set_token("wrong-token")
|
|
859
|
+
assert client.get_token() == "wrong-token" # ensure we set it correctly
|
|
860
|
+
|
|
861
|
+
with pytest.raises(InvalidAuthTokenError):
|
|
862
|
+
client.test_auth()
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
def test_client_test_auth_non_401_error(client: MregClient, httpserver: HTTPServer) -> None:
|
|
866
|
+
"""Test MregClient.test_auth with a non-401 error."""
|
|
867
|
+
assert isinstance(client.host, HostManager)
|
|
868
|
+
|
|
869
|
+
httpserver.expect_oneshot_request("/api/v1/hosts/").respond_with_response(Response(status=500))
|
|
870
|
+
|
|
871
|
+
client.set_token("wrong-token")
|
|
872
|
+
assert client.get_token() == "wrong-token" # ensure we set it correctly
|
|
873
|
+
|
|
874
|
+
with pytest.raises(ResponseError):
|
|
875
|
+
client.test_auth()
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
def test_client_get_token(client: MregClient) -> None:
|
|
879
|
+
"""Test the get_token method of the MregClient."""
|
|
880
|
+
# Initially, no token should be set
|
|
881
|
+
assert client.get_token() is None
|
|
882
|
+
|
|
883
|
+
# Set a token and verify it can be retrieved
|
|
884
|
+
token = "my-token"
|
|
885
|
+
client.set_token(token)
|
|
886
|
+
assert client.get_token() == token
|
|
887
|
+
assert client.session.headers.get(Header.AUTH) == f"Token {token}" # with "Token " prefix
|
|
888
|
+
|
|
889
|
+
# Unset the token and verify it is None again
|
|
890
|
+
client.unset_token()
|
|
891
|
+
assert client.get_token() is None
|
|
892
|
+
|
|
893
|
+
|
|
820
894
|
def get_mreg_client_managers(client: MregClient) -> list[tuple[str, str, type[Any]]]:
|
|
821
895
|
"""Return a list of (attribute_name, class_name, class_type) for all managers in the client."""
|
|
822
896
|
# XXX: This is very similar to tests.test_managers.get_resource_managers :\
|
|
@@ -880,24 +954,16 @@ def test_client_manager_composition_has_get_method(client: MregClient) -> None:
|
|
|
880
954
|
)
|
|
881
955
|
|
|
882
956
|
|
|
883
|
-
@pytest.mark.parametrize(
|
|
884
|
-
"method,expected_exc",
|
|
885
|
-
[
|
|
886
|
-
("GET", GetError),
|
|
887
|
-
("POST", PostError),
|
|
888
|
-
("PATCH", PatchError),
|
|
889
|
-
("DELETE", DeleteError),
|
|
890
|
-
],
|
|
891
|
-
)
|
|
957
|
+
@pytest.mark.parametrize("method", ["GET", "POST", "PATCH", "DELETE"])
|
|
892
958
|
def test_request_exception_handling_live(
|
|
893
|
-
httpserver: HTTPServer, client: MregClient, method: HTTPMethod
|
|
959
|
+
httpserver: HTTPServer, client: MregClient, method: HTTPMethod
|
|
894
960
|
) -> None:
|
|
895
|
-
"""Test that check_response raises the appropriate exception type on
|
|
961
|
+
"""Test that check_response raises the appropriate exception type on 400 response.
|
|
896
962
|
|
|
897
963
|
Uses actual HTTP requests to test exception handling.
|
|
898
964
|
"""
|
|
899
965
|
httpserver.expect_oneshot_request("/test_check_response").respond_with_response(Response(status=400))
|
|
900
|
-
with pytest.raises(
|
|
966
|
+
with pytest.raises(BadRequestError):
|
|
901
967
|
_ = client.request(method, "/test_check_response")
|
|
902
968
|
|
|
903
969
|
|
|
@@ -925,24 +991,25 @@ def test_check_response_2xx(method: HTTPMethod, status_code: int) -> None:
|
|
|
925
991
|
check_response(response)
|
|
926
992
|
|
|
927
993
|
|
|
994
|
+
@pytest.mark.parametrize("method", ["GET", "POST", "PATCH", "DELETE"])
|
|
928
995
|
@pytest.mark.parametrize(
|
|
929
|
-
"
|
|
996
|
+
"status_code, expected_exc",
|
|
930
997
|
[
|
|
931
|
-
(
|
|
932
|
-
(
|
|
933
|
-
(
|
|
934
|
-
(
|
|
998
|
+
(400, BadRequestError),
|
|
999
|
+
(401, UnauthorizedError),
|
|
1000
|
+
(403, ForbiddenError),
|
|
1001
|
+
(404, NotFoundError),
|
|
1002
|
+
(409, ConflictError),
|
|
1003
|
+
(418, ClientError),
|
|
1004
|
+
(500, ServerError),
|
|
1005
|
+
(503, ServerError),
|
|
935
1006
|
],
|
|
936
1007
|
)
|
|
937
|
-
@pytest.mark.parametrize(
|
|
938
|
-
"status_code",
|
|
939
|
-
[400, 403, 404, 409, 500],
|
|
940
|
-
)
|
|
941
1008
|
@pytest.mark.parametrize("lowercase_method", [True, False])
|
|
942
1009
|
def test_check_response_error(
|
|
943
|
-
method: str, expected_exc: type[Exception],
|
|
1010
|
+
method: str, status_code: int, expected_exc: type[Exception], lowercase_method: bool
|
|
944
1011
|
) -> None:
|
|
945
|
-
"""Test that check_response raises the
|
|
1012
|
+
"""Test that check_response raises the status-based error regardless of HTTP method."""
|
|
946
1013
|
# Ensure method casing does not matter for HTTPX!
|
|
947
1014
|
if lowercase_method:
|
|
948
1015
|
method = method.lower()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|