boerules 1.0.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.
- boerules-1.0.0/LICENSE +21 -0
- boerules-1.0.0/PKG-INFO +94 -0
- boerules-1.0.0/README.md +72 -0
- boerules-1.0.0/boerules/__init__.py +29 -0
- boerules-1.0.0/boerules/_client.py +146 -0
- boerules-1.0.0/boerules/_errors.py +76 -0
- boerules-1.0.0/boerules/_types.py +29 -0
- boerules-1.0.0/boerules/_wire.py +59 -0
- boerules-1.0.0/boerules/py.typed +0 -0
- boerules-1.0.0/boerules.egg-info/PKG-INFO +94 -0
- boerules-1.0.0/boerules.egg-info/SOURCES.txt +16 -0
- boerules-1.0.0/boerules.egg-info/dependency_links.txt +1 -0
- boerules-1.0.0/boerules.egg-info/requires.txt +1 -0
- boerules-1.0.0/boerules.egg-info/top_level.txt +1 -0
- boerules-1.0.0/pyproject.toml +37 -0
- boerules-1.0.0/setup.cfg +4 -0
- boerules-1.0.0/tests/test_client.py +239 -0
- boerules-1.0.0/tests/test_version.py +20 -0
boerules-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BOE
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
boerules-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: boerules
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python client for the BOE business rule engine: register and execute.
|
|
5
|
+
Author: BOE
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://boerules.com
|
|
8
|
+
Keywords: boe,business rules,rule engine,decisions,scoring,eligibility,sdk
|
|
9
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: httpx>=0.27
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# boerules
|
|
24
|
+
|
|
25
|
+
Python client for [BOE](https://boerules.com), the business rule engine. Register a ruleset and execute it in under ten lines.
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from boerules import BOE
|
|
29
|
+
|
|
30
|
+
with BOE() as boe: # reads BOE_API_KEY and BOE_BASE_URL
|
|
31
|
+
registered = boe.register(
|
|
32
|
+
id="credit-score", mode="scoring", definition=definition,
|
|
33
|
+
input_schema=input_schema,
|
|
34
|
+
)
|
|
35
|
+
result = boe.execute(registered.short_code, facts={"income": 82000})
|
|
36
|
+
print(registered.execute_url, result.result)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The wire speaks camelCase;
|
|
40
|
+
this client exposes snake case keyword arguments and frozen dataclasses.
|
|
41
|
+
|
|
42
|
+
## Install
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install boerules
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Python 3.10 or later. The one
|
|
49
|
+
runtime dependency is `httpx`.
|
|
50
|
+
|
|
51
|
+
## Configuration
|
|
52
|
+
|
|
53
|
+
`BOE(api_key=None, base_url=None, execute_base_url=None, timeout_seconds=30.0, max_retries=3)`
|
|
54
|
+
|
|
55
|
+
| Setting | Default |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `api_key` | `BOE_API_KEY` |
|
|
58
|
+
| `base_url` | `BOE_BASE_URL`, else `https://api.boerules.com/v1` |
|
|
59
|
+
| `execute_base_url` | `base_url` |
|
|
60
|
+
|
|
61
|
+
A missing key raises `BOEError` naming `BOE_API_KEY` before any request.
|
|
62
|
+
Network failures, 500, 502, 503 and 504 retry with backoff of 100 ms doubling per attempt.
|
|
63
|
+
|
|
64
|
+
## Calls
|
|
65
|
+
|
|
66
|
+
- `register(*, id, mode, definition=None, source=None, input_schema=None)` returns `RegisterResult` with `ruleset_id`, `short_code`, `engine_mode`, `version`, `created`, `execute_url`.
|
|
67
|
+
- `execute(short_code, *, facts, version=None, lineage=False)` returns `ExecuteResult` with `execution_id`, `ruleset`, `engine_mode`, `short_code`, `version`, `result`, `execution_time_ms`, `total_time_ms`, `lineage`.
|
|
68
|
+
|
|
69
|
+
## Errors
|
|
70
|
+
|
|
71
|
+
Every error is a `BOEError` with `message`, `status_code` and `code` (None when the server sent none).
|
|
72
|
+
|
|
73
|
+
| Class | Status | Code |
|
|
74
|
+
|---|---|---|
|
|
75
|
+
| `ProductionKeyCannotRegisterError` | 403, register | `production_environment_key_cannot_register` |
|
|
76
|
+
| `RulesetNotLiveInEnvironmentError` | 404, execute | `ruleset_not_live_in_environment` |
|
|
77
|
+
| `RulesetEngineModeMismatchError` | 409, register | `RULESET_ENGINE_MODE_MISMATCH` |
|
|
78
|
+
| `RulesetArchivedError` | 409 register, 410 execute | `ruleset_archived` |
|
|
79
|
+
| `SubscriptionLapsedError` | 429, execute | `subscription_lapsed` |
|
|
80
|
+
| `SubscriptionMissingError` | 429, execute | `subscription_missing` |
|
|
81
|
+
| `BOEError` | any other | none, or the unknown code |
|
|
82
|
+
|
|
83
|
+
## Tests
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
python -m unittest discover -s tests
|
|
87
|
+
mypy --strict boerules
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
The integration test runs when `BOE_API_KEY` is set and skips otherwise.
|
|
91
|
+
|
|
92
|
+
Documentation and API keys: https://boerules.com
|
|
93
|
+
|
|
94
|
+
License: MIT.
|
boerules-1.0.0/README.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# boerules
|
|
2
|
+
|
|
3
|
+
Python client for [BOE](https://boerules.com), the business rule engine. Register a ruleset and execute it in under ten lines.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
from boerules import BOE
|
|
7
|
+
|
|
8
|
+
with BOE() as boe: # reads BOE_API_KEY and BOE_BASE_URL
|
|
9
|
+
registered = boe.register(
|
|
10
|
+
id="credit-score", mode="scoring", definition=definition,
|
|
11
|
+
input_schema=input_schema,
|
|
12
|
+
)
|
|
13
|
+
result = boe.execute(registered.short_code, facts={"income": 82000})
|
|
14
|
+
print(registered.execute_url, result.result)
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The wire speaks camelCase;
|
|
18
|
+
this client exposes snake case keyword arguments and frozen dataclasses.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install boerules
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Python 3.10 or later. The one
|
|
27
|
+
runtime dependency is `httpx`.
|
|
28
|
+
|
|
29
|
+
## Configuration
|
|
30
|
+
|
|
31
|
+
`BOE(api_key=None, base_url=None, execute_base_url=None, timeout_seconds=30.0, max_retries=3)`
|
|
32
|
+
|
|
33
|
+
| Setting | Default |
|
|
34
|
+
|---|---|
|
|
35
|
+
| `api_key` | `BOE_API_KEY` |
|
|
36
|
+
| `base_url` | `BOE_BASE_URL`, else `https://api.boerules.com/v1` |
|
|
37
|
+
| `execute_base_url` | `base_url` |
|
|
38
|
+
|
|
39
|
+
A missing key raises `BOEError` naming `BOE_API_KEY` before any request.
|
|
40
|
+
Network failures, 500, 502, 503 and 504 retry with backoff of 100 ms doubling per attempt.
|
|
41
|
+
|
|
42
|
+
## Calls
|
|
43
|
+
|
|
44
|
+
- `register(*, id, mode, definition=None, source=None, input_schema=None)` returns `RegisterResult` with `ruleset_id`, `short_code`, `engine_mode`, `version`, `created`, `execute_url`.
|
|
45
|
+
- `execute(short_code, *, facts, version=None, lineage=False)` returns `ExecuteResult` with `execution_id`, `ruleset`, `engine_mode`, `short_code`, `version`, `result`, `execution_time_ms`, `total_time_ms`, `lineage`.
|
|
46
|
+
|
|
47
|
+
## Errors
|
|
48
|
+
|
|
49
|
+
Every error is a `BOEError` with `message`, `status_code` and `code` (None when the server sent none).
|
|
50
|
+
|
|
51
|
+
| Class | Status | Code |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| `ProductionKeyCannotRegisterError` | 403, register | `production_environment_key_cannot_register` |
|
|
54
|
+
| `RulesetNotLiveInEnvironmentError` | 404, execute | `ruleset_not_live_in_environment` |
|
|
55
|
+
| `RulesetEngineModeMismatchError` | 409, register | `RULESET_ENGINE_MODE_MISMATCH` |
|
|
56
|
+
| `RulesetArchivedError` | 409 register, 410 execute | `ruleset_archived` |
|
|
57
|
+
| `SubscriptionLapsedError` | 429, execute | `subscription_lapsed` |
|
|
58
|
+
| `SubscriptionMissingError` | 429, execute | `subscription_missing` |
|
|
59
|
+
| `BOEError` | any other | none, or the unknown code |
|
|
60
|
+
|
|
61
|
+
## Tests
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
python -m unittest discover -s tests
|
|
65
|
+
mypy --strict boerules
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
The integration test runs when `BOE_API_KEY` is set and skips otherwise.
|
|
69
|
+
|
|
70
|
+
Documentation and API keys: https://boerules.com
|
|
71
|
+
|
|
72
|
+
License: MIT.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Python client for BOE: register a ruleset and execute it."""
|
|
2
|
+
|
|
3
|
+
from ._client import BOE, _sdk_version
|
|
4
|
+
from ._errors import (
|
|
5
|
+
BOEError,
|
|
6
|
+
ProductionKeyCannotRegisterError,
|
|
7
|
+
RulesetArchivedError,
|
|
8
|
+
RulesetEngineModeMismatchError,
|
|
9
|
+
RulesetNotLiveInEnvironmentError,
|
|
10
|
+
SubscriptionLapsedError,
|
|
11
|
+
SubscriptionMissingError,
|
|
12
|
+
)
|
|
13
|
+
from ._types import ExecuteResult, RegisterResult
|
|
14
|
+
|
|
15
|
+
__version__ = _sdk_version()
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"__version__",
|
|
19
|
+
"BOE",
|
|
20
|
+
"BOEError",
|
|
21
|
+
"ExecuteResult",
|
|
22
|
+
"ProductionKeyCannotRegisterError",
|
|
23
|
+
"RegisterResult",
|
|
24
|
+
"RulesetArchivedError",
|
|
25
|
+
"RulesetEngineModeMismatchError",
|
|
26
|
+
"RulesetNotLiveInEnvironmentError",
|
|
27
|
+
"SubscriptionLapsedError",
|
|
28
|
+
"SubscriptionMissingError",
|
|
29
|
+
]
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Synchronous BOE client over httpx."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
from importlib import metadata
|
|
8
|
+
from types import TracebackType
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from . import _wire
|
|
14
|
+
from ._errors import BOEError, error_from_response
|
|
15
|
+
from ._types import ExecuteResult, RegisterResult
|
|
16
|
+
|
|
17
|
+
DEFAULT_BASE_URL = "https://api.boerules.com/v1"
|
|
18
|
+
_RETRYABLE_STATUS_CODES = frozenset({500, 502, 503, 504})
|
|
19
|
+
_BACKOFF_BASE_SECONDS = 0.1
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _sdk_version() -> str:
|
|
23
|
+
try:
|
|
24
|
+
return metadata.version("boerules")
|
|
25
|
+
except metadata.PackageNotFoundError:
|
|
26
|
+
return "0.0.0"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _join(base_url: str, path: str) -> str:
|
|
30
|
+
return base_url.rstrip("/") + "/" + path.lstrip("/")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class BOE:
|
|
34
|
+
"""Register and execute BOE rulesets.
|
|
35
|
+
|
|
36
|
+
Reads BOE_API_KEY and BOE_BASE_URL when the arguments are omitted.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
api_key: str | None = None,
|
|
42
|
+
base_url: str | None = None,
|
|
43
|
+
execute_base_url: str | None = None,
|
|
44
|
+
timeout_seconds: float = 30.0,
|
|
45
|
+
max_retries: int = 3,
|
|
46
|
+
transport: httpx.BaseTransport | None = None,
|
|
47
|
+
) -> None:
|
|
48
|
+
resolved_key = api_key or os.environ.get("BOE_API_KEY")
|
|
49
|
+
if not resolved_key:
|
|
50
|
+
raise BOEError(
|
|
51
|
+
"No API key. Pass api_key=... or set the BOE_API_KEY environment variable."
|
|
52
|
+
)
|
|
53
|
+
self._base_url = (base_url or os.environ.get("BOE_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
54
|
+
self._execute_base_url = (execute_base_url or self._base_url).rstrip("/")
|
|
55
|
+
self._max_retries = max_retries
|
|
56
|
+
self._http = httpx.Client(
|
|
57
|
+
timeout=timeout_seconds,
|
|
58
|
+
transport=transport,
|
|
59
|
+
headers={
|
|
60
|
+
"Authorization": f"Bearer {resolved_key}",
|
|
61
|
+
"Content-Type": "application/json",
|
|
62
|
+
"X-BOE-SDK": "python",
|
|
63
|
+
"X-BOE-SDK-Version": _sdk_version(),
|
|
64
|
+
},
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def base_url(self) -> str:
|
|
69
|
+
return self._base_url
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def execute_base_url(self) -> str:
|
|
73
|
+
return self._execute_base_url
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def is_closed(self) -> bool:
|
|
77
|
+
return self._http.is_closed
|
|
78
|
+
|
|
79
|
+
def __enter__(self) -> BOE:
|
|
80
|
+
return self
|
|
81
|
+
|
|
82
|
+
def __exit__(
|
|
83
|
+
self,
|
|
84
|
+
exc_type: type[BaseException] | None,
|
|
85
|
+
exc: BaseException | None,
|
|
86
|
+
traceback: TracebackType | None,
|
|
87
|
+
) -> None:
|
|
88
|
+
self.close()
|
|
89
|
+
|
|
90
|
+
def close(self) -> None:
|
|
91
|
+
self._http.close()
|
|
92
|
+
|
|
93
|
+
def register(
|
|
94
|
+
self,
|
|
95
|
+
*,
|
|
96
|
+
id: str,
|
|
97
|
+
mode: str,
|
|
98
|
+
definition: dict[str, Any] | None = None,
|
|
99
|
+
source: dict[str, Any] | None = None,
|
|
100
|
+
input_schema: dict[str, Any] | None = None,
|
|
101
|
+
) -> RegisterResult:
|
|
102
|
+
body = _wire.register_body(
|
|
103
|
+
id=id, mode=mode, definition=definition, source=source, input_schema=input_schema
|
|
104
|
+
)
|
|
105
|
+
wire = self._send(_join(self._base_url, "/register"), body, params=None)
|
|
106
|
+
short_code = wire.get("shortCode", "")
|
|
107
|
+
return _wire.register_result(
|
|
108
|
+
wire, fallback_execute_url=_join(self._execute_base_url, f"/execute/{short_code}")
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
def execute(
|
|
112
|
+
self,
|
|
113
|
+
short_code: str,
|
|
114
|
+
*,
|
|
115
|
+
facts: dict[str, Any],
|
|
116
|
+
version: str | None = None,
|
|
117
|
+
lineage: bool = False,
|
|
118
|
+
) -> ExecuteResult:
|
|
119
|
+
params = {"version": version} if version is not None else None
|
|
120
|
+
wire = self._send(
|
|
121
|
+
_join(self._execute_base_url, f"/execute/{short_code}"),
|
|
122
|
+
_wire.execute_body(facts=facts, lineage=lineage),
|
|
123
|
+
params=params,
|
|
124
|
+
)
|
|
125
|
+
return _wire.execute_result(wire)
|
|
126
|
+
|
|
127
|
+
def _send(self, url: str, body: dict[str, Any], *, params: dict[str, str] | None) -> dict[str, Any]:
|
|
128
|
+
attempt = 0
|
|
129
|
+
while True:
|
|
130
|
+
try:
|
|
131
|
+
response = self._http.post(url, json=body, params=params)
|
|
132
|
+
except httpx.TransportError as failure:
|
|
133
|
+
if attempt >= self._max_retries:
|
|
134
|
+
raise BOEError(f"Could not reach BOE at {url}: {failure}") from failure
|
|
135
|
+
else:
|
|
136
|
+
if response.status_code < 400:
|
|
137
|
+
parsed: dict[str, Any] = response.json()
|
|
138
|
+
return parsed
|
|
139
|
+
if response.status_code not in _RETRYABLE_STATUS_CODES or attempt >= self._max_retries:
|
|
140
|
+
try:
|
|
141
|
+
error_body: Any = response.json()
|
|
142
|
+
except ValueError:
|
|
143
|
+
error_body = None
|
|
144
|
+
raise error_from_response(response.status_code, error_body, response.text)
|
|
145
|
+
time.sleep(_BACKOFF_BASE_SECONDS * (2**attempt))
|
|
146
|
+
attempt += 1
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Typed errors.
|
|
2
|
+
|
|
3
|
+
Classification order: the body code, then an error value that is a known code,
|
|
4
|
+
then executionRefusalReason, then the status alone.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class BOEError(Exception):
|
|
13
|
+
"""A refusal from BOE. Carries the server sentence, status and code."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, message: str, *, status_code: int | None = None, code: str | None = None) -> None:
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.message = message
|
|
18
|
+
self.status_code = status_code
|
|
19
|
+
self.code = code
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ProductionKeyCannotRegisterError(BOEError):
|
|
23
|
+
"""403 from register: the key is bound to a Production environment."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class RulesetNotLiveInEnvironmentError(BOEError):
|
|
27
|
+
"""404 from execute: nothing is live in the key's environment."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class RulesetEngineModeMismatchError(BOEError):
|
|
31
|
+
"""409 from register: the ruleset holds another engine mode."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class RulesetArchivedError(BOEError):
|
|
35
|
+
"""409 from register or 410 from execute: the ruleset is archived."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SubscriptionLapsedError(BOEError):
|
|
39
|
+
"""429 from execute: the subscription lapsed."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class SubscriptionMissingError(BOEError):
|
|
43
|
+
"""429 from execute: the account has no subscription."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
ERROR_CLASS_BY_CODE: dict[str, type[BOEError]] = {
|
|
47
|
+
"production_environment_key_cannot_register": ProductionKeyCannotRegisterError,
|
|
48
|
+
"ruleset_not_live_in_environment": RulesetNotLiveInEnvironmentError,
|
|
49
|
+
"RULESET_ENGINE_MODE_MISMATCH": RulesetEngineModeMismatchError,
|
|
50
|
+
"ruleset_archived": RulesetArchivedError,
|
|
51
|
+
"subscription_lapsed": SubscriptionLapsedError,
|
|
52
|
+
"subscription_missing": SubscriptionMissingError,
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def error_from_response(status_code: int, body: Any, fallback_text: str) -> BOEError:
|
|
57
|
+
sentence = f"BOE answered HTTP {status_code}"
|
|
58
|
+
code: str | None = None
|
|
59
|
+
if isinstance(body, dict):
|
|
60
|
+
error_value = body.get("error")
|
|
61
|
+
if isinstance(error_value, str) and error_value:
|
|
62
|
+
sentence = error_value
|
|
63
|
+
elif isinstance(body.get("message"), str):
|
|
64
|
+
sentence = body["message"]
|
|
65
|
+
body_code = body.get("code")
|
|
66
|
+
refusal_reason = body.get("executionRefusalReason")
|
|
67
|
+
if isinstance(body_code, str):
|
|
68
|
+
code = body_code
|
|
69
|
+
elif isinstance(error_value, str) and error_value in ERROR_CLASS_BY_CODE:
|
|
70
|
+
code = error_value
|
|
71
|
+
elif isinstance(refusal_reason, str):
|
|
72
|
+
code = refusal_reason
|
|
73
|
+
elif fallback_text:
|
|
74
|
+
sentence = f"{sentence}: {fallback_text[:200]}"
|
|
75
|
+
error_class = ERROR_CLASS_BY_CODE.get(code, BOEError) if code else BOEError
|
|
76
|
+
return error_class(sentence, status_code=status_code, code=code)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Result dataclasses. Field names are snake case; _wire.py maps the wire names."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class RegisterResult:
|
|
11
|
+
ruleset_id: str
|
|
12
|
+
short_code: str
|
|
13
|
+
engine_mode: str
|
|
14
|
+
version: str
|
|
15
|
+
created: bool
|
|
16
|
+
execute_url: str
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class ExecuteResult:
|
|
21
|
+
execution_id: str
|
|
22
|
+
ruleset: str
|
|
23
|
+
engine_mode: str
|
|
24
|
+
short_code: str
|
|
25
|
+
version: str
|
|
26
|
+
result: Any
|
|
27
|
+
execution_time_ms: float
|
|
28
|
+
total_time_ms: float | None = None
|
|
29
|
+
lineage: dict[str, Any] | None = None
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""The one place wire camelCase names meet Python snake case names."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from ._types import ExecuteResult, RegisterResult
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def register_body(
|
|
11
|
+
*,
|
|
12
|
+
id: str,
|
|
13
|
+
mode: str,
|
|
14
|
+
definition: dict[str, Any] | None,
|
|
15
|
+
source: dict[str, Any] | None,
|
|
16
|
+
input_schema: dict[str, Any] | None,
|
|
17
|
+
) -> dict[str, Any]:
|
|
18
|
+
body: dict[str, Any] = {"id": id, "mode": mode}
|
|
19
|
+
if definition is not None:
|
|
20
|
+
body["definition"] = definition
|
|
21
|
+
if source is not None:
|
|
22
|
+
body["source"] = source
|
|
23
|
+
if input_schema is not None:
|
|
24
|
+
body["inputSchema"] = input_schema
|
|
25
|
+
return body
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def execute_body(*, facts: dict[str, Any], lineage: bool) -> dict[str, Any]:
|
|
29
|
+
body: dict[str, Any] = {"facts": facts}
|
|
30
|
+
if lineage:
|
|
31
|
+
body["options"] = {"lineage": True}
|
|
32
|
+
return body
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def register_result(wire: dict[str, Any], *, fallback_execute_url: str) -> RegisterResult:
|
|
36
|
+
# A register Lambda deployed before #1114 answers no executeUrl.
|
|
37
|
+
execute_url = wire.get("executeUrl") or fallback_execute_url
|
|
38
|
+
return RegisterResult(
|
|
39
|
+
ruleset_id=wire["rulesetId"],
|
|
40
|
+
short_code=wire["shortCode"],
|
|
41
|
+
engine_mode=wire["engineMode"],
|
|
42
|
+
version=wire["version"],
|
|
43
|
+
created=wire["created"],
|
|
44
|
+
execute_url=execute_url,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def execute_result(wire: dict[str, Any]) -> ExecuteResult:
|
|
49
|
+
return ExecuteResult(
|
|
50
|
+
execution_id=wire["executionId"],
|
|
51
|
+
ruleset=wire["ruleset"],
|
|
52
|
+
engine_mode=wire["engineMode"],
|
|
53
|
+
short_code=wire["shortCode"],
|
|
54
|
+
version=wire["version"],
|
|
55
|
+
result=wire.get("result"),
|
|
56
|
+
execution_time_ms=wire["executionTimeMs"],
|
|
57
|
+
total_time_ms=wire.get("totalTimeMs"),
|
|
58
|
+
lineage=wire.get("lineage"),
|
|
59
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: boerules
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python client for the BOE business rule engine: register and execute.
|
|
5
|
+
Author: BOE
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://boerules.com
|
|
8
|
+
Keywords: boe,business rules,rule engine,decisions,scoring,eligibility,sdk
|
|
9
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: httpx>=0.27
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# boerules
|
|
24
|
+
|
|
25
|
+
Python client for [BOE](https://boerules.com), the business rule engine. Register a ruleset and execute it in under ten lines.
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from boerules import BOE
|
|
29
|
+
|
|
30
|
+
with BOE() as boe: # reads BOE_API_KEY and BOE_BASE_URL
|
|
31
|
+
registered = boe.register(
|
|
32
|
+
id="credit-score", mode="scoring", definition=definition,
|
|
33
|
+
input_schema=input_schema,
|
|
34
|
+
)
|
|
35
|
+
result = boe.execute(registered.short_code, facts={"income": 82000})
|
|
36
|
+
print(registered.execute_url, result.result)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The wire speaks camelCase;
|
|
40
|
+
this client exposes snake case keyword arguments and frozen dataclasses.
|
|
41
|
+
|
|
42
|
+
## Install
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install boerules
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Python 3.10 or later. The one
|
|
49
|
+
runtime dependency is `httpx`.
|
|
50
|
+
|
|
51
|
+
## Configuration
|
|
52
|
+
|
|
53
|
+
`BOE(api_key=None, base_url=None, execute_base_url=None, timeout_seconds=30.0, max_retries=3)`
|
|
54
|
+
|
|
55
|
+
| Setting | Default |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `api_key` | `BOE_API_KEY` |
|
|
58
|
+
| `base_url` | `BOE_BASE_URL`, else `https://api.boerules.com/v1` |
|
|
59
|
+
| `execute_base_url` | `base_url` |
|
|
60
|
+
|
|
61
|
+
A missing key raises `BOEError` naming `BOE_API_KEY` before any request.
|
|
62
|
+
Network failures, 500, 502, 503 and 504 retry with backoff of 100 ms doubling per attempt.
|
|
63
|
+
|
|
64
|
+
## Calls
|
|
65
|
+
|
|
66
|
+
- `register(*, id, mode, definition=None, source=None, input_schema=None)` returns `RegisterResult` with `ruleset_id`, `short_code`, `engine_mode`, `version`, `created`, `execute_url`.
|
|
67
|
+
- `execute(short_code, *, facts, version=None, lineage=False)` returns `ExecuteResult` with `execution_id`, `ruleset`, `engine_mode`, `short_code`, `version`, `result`, `execution_time_ms`, `total_time_ms`, `lineage`.
|
|
68
|
+
|
|
69
|
+
## Errors
|
|
70
|
+
|
|
71
|
+
Every error is a `BOEError` with `message`, `status_code` and `code` (None when the server sent none).
|
|
72
|
+
|
|
73
|
+
| Class | Status | Code |
|
|
74
|
+
|---|---|---|
|
|
75
|
+
| `ProductionKeyCannotRegisterError` | 403, register | `production_environment_key_cannot_register` |
|
|
76
|
+
| `RulesetNotLiveInEnvironmentError` | 404, execute | `ruleset_not_live_in_environment` |
|
|
77
|
+
| `RulesetEngineModeMismatchError` | 409, register | `RULESET_ENGINE_MODE_MISMATCH` |
|
|
78
|
+
| `RulesetArchivedError` | 409 register, 410 execute | `ruleset_archived` |
|
|
79
|
+
| `SubscriptionLapsedError` | 429, execute | `subscription_lapsed` |
|
|
80
|
+
| `SubscriptionMissingError` | 429, execute | `subscription_missing` |
|
|
81
|
+
| `BOEError` | any other | none, or the unknown code |
|
|
82
|
+
|
|
83
|
+
## Tests
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
python -m unittest discover -s tests
|
|
87
|
+
mypy --strict boerules
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
The integration test runs when `BOE_API_KEY` is set and skips otherwise.
|
|
91
|
+
|
|
92
|
+
Documentation and API keys: https://boerules.com
|
|
93
|
+
|
|
94
|
+
License: MIT.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
boerules/__init__.py
|
|
5
|
+
boerules/_client.py
|
|
6
|
+
boerules/_errors.py
|
|
7
|
+
boerules/_types.py
|
|
8
|
+
boerules/_wire.py
|
|
9
|
+
boerules/py.typed
|
|
10
|
+
boerules.egg-info/PKG-INFO
|
|
11
|
+
boerules.egg-info/SOURCES.txt
|
|
12
|
+
boerules.egg-info/dependency_links.txt
|
|
13
|
+
boerules.egg-info/requires.txt
|
|
14
|
+
boerules.egg-info/top_level.txt
|
|
15
|
+
tests/test_client.py
|
|
16
|
+
tests/test_version.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
httpx>=0.27
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
boerules
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "boerules"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Python client for the BOE business rule engine: register and execute."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "BOE" }]
|
|
13
|
+
keywords = ["boe", "business rules", "rule engine", "decisions", "scoring", "eligibility", "sdk"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 5 - Production/Stable",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.10",
|
|
19
|
+
"Programming Language :: Python :: 3.11",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
requires-python = ">=3.10"
|
|
25
|
+
dependencies = ["httpx>=0.27"]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://boerules.com"
|
|
29
|
+
|
|
30
|
+
[tool.setuptools]
|
|
31
|
+
packages = ["boerules"]
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.package-data]
|
|
34
|
+
boerules = ["py.typed"]
|
|
35
|
+
|
|
36
|
+
[tool.mypy]
|
|
37
|
+
strict = true
|
boerules-1.0.0/setup.cfg
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import dataclasses
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import unittest
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
from unittest import mock
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
from boerules import (
|
|
15
|
+
BOE,
|
|
16
|
+
BOEError,
|
|
17
|
+
ProductionKeyCannotRegisterError,
|
|
18
|
+
RulesetNotLiveInEnvironmentError,
|
|
19
|
+
)
|
|
20
|
+
from boerules._errors import ERROR_CLASS_BY_CODE
|
|
21
|
+
|
|
22
|
+
REGISTER_BODY = {
|
|
23
|
+
"rulesetId": "6f1c2a4e-9b7d-4f0a-8e21-3c5d7a9b1e04",
|
|
24
|
+
"shortCode": "k7x2m9",
|
|
25
|
+
"engineMode": "scoring",
|
|
26
|
+
"version": "1.0.0",
|
|
27
|
+
"created": True,
|
|
28
|
+
"executeUrl": "https://api.boerules.com/v1/execute/k7x2m9",
|
|
29
|
+
}
|
|
30
|
+
EXECUTE_BODY = {
|
|
31
|
+
"executionId": "3b2f9c1e-7d4a-4e8b-9a6c-0f1e2d3c4b5a",
|
|
32
|
+
"ruleset": "credit-score",
|
|
33
|
+
"engineMode": "scoring",
|
|
34
|
+
"shortCode": "k7x2m9",
|
|
35
|
+
"version": "1.0.0",
|
|
36
|
+
"result": {"score": 82},
|
|
37
|
+
"executionTimeMs": 0.41,
|
|
38
|
+
"totalTimeMs": 18.62,
|
|
39
|
+
}
|
|
40
|
+
IMPLEMENTATION_MD = Path(__file__).resolve().parents[2] / "implementation.md"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Recorder:
|
|
44
|
+
def __init__(self, status: int, body: Any) -> None:
|
|
45
|
+
self.status = status
|
|
46
|
+
self.body = body
|
|
47
|
+
self.requests: list[httpx.Request] = []
|
|
48
|
+
|
|
49
|
+
def __call__(self, request: httpx.Request) -> httpx.Response:
|
|
50
|
+
self.requests.append(request)
|
|
51
|
+
return httpx.Response(self.status, json=self.body)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def client_for(recorder: Recorder, **options: Any) -> BOE:
|
|
55
|
+
return BOE(api_key="boe_test", transport=httpx.MockTransport(recorder), **options)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def register_call(boe: BOE) -> Any:
|
|
59
|
+
return boe.register(id="credit-score", mode="scoring", definition={"rules": []})
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class BOEClientTests(unittest.TestCase):
|
|
63
|
+
def test_register_posts_to_expected_url_with_bearer_and_sdk_headers(self) -> None:
|
|
64
|
+
recorder = Recorder(201, REGISTER_BODY)
|
|
65
|
+
with mock.patch.dict(os.environ, {}, clear=True):
|
|
66
|
+
register_call(client_for(recorder))
|
|
67
|
+
request = recorder.requests[0]
|
|
68
|
+
self.assertEqual(request.method, "POST")
|
|
69
|
+
self.assertEqual(str(request.url), "https://api.boerules.com/v1/register")
|
|
70
|
+
self.assertEqual(request.headers["Authorization"], "Bearer boe_test")
|
|
71
|
+
self.assertEqual(request.headers["X-BOE-SDK"], "python")
|
|
72
|
+
self.assertIn("X-BOE-SDK-Version", request.headers)
|
|
73
|
+
|
|
74
|
+
def test_register_body_uses_wire_camel_case_names(self) -> None:
|
|
75
|
+
recorder = Recorder(201, REGISTER_BODY)
|
|
76
|
+
client_for(recorder).register(
|
|
77
|
+
id="credit-score", mode="scoring", definition={"rules": []}, input_schema={"type": "object"}
|
|
78
|
+
)
|
|
79
|
+
sent = json.loads(recorder.requests[0].content)
|
|
80
|
+
self.assertEqual(sent["inputSchema"], {"type": "object"})
|
|
81
|
+
self.assertNotIn("input_schema", sent)
|
|
82
|
+
self.assertEqual(sent["id"], "credit-score")
|
|
83
|
+
self.assertEqual(sent["definition"], {"rules": []})
|
|
84
|
+
|
|
85
|
+
def test_register_result_maps_camel_case_to_snake_case(self) -> None:
|
|
86
|
+
result = register_call(client_for(Recorder(201, REGISTER_BODY)))
|
|
87
|
+
self.assertEqual(result.short_code, "k7x2m9")
|
|
88
|
+
self.assertEqual(result.execute_url, "https://api.boerules.com/v1/execute/k7x2m9")
|
|
89
|
+
self.assertEqual(result.ruleset_id, REGISTER_BODY["rulesetId"])
|
|
90
|
+
self.assertEqual(result.engine_mode, "scoring")
|
|
91
|
+
self.assertTrue(result.created)
|
|
92
|
+
|
|
93
|
+
def test_register_without_execute_url_builds_it_from_execute_base_url(self) -> None:
|
|
94
|
+
legacy = {k: v for k, v in REGISTER_BODY.items() if k != "executeUrl"}
|
|
95
|
+
result = register_call(client_for(Recorder(201, legacy), execute_base_url="https://x.test/v1/"))
|
|
96
|
+
self.assertEqual(result.execute_url, "https://x.test/v1/execute/k7x2m9")
|
|
97
|
+
|
|
98
|
+
def test_register_result_is_frozen(self) -> None:
|
|
99
|
+
result = register_call(client_for(Recorder(201, REGISTER_BODY)))
|
|
100
|
+
with self.assertRaises(dataclasses.FrozenInstanceError):
|
|
101
|
+
result.version = "9.9.9" # type: ignore[misc]
|
|
102
|
+
|
|
103
|
+
def test_execute_sends_facts_and_version_pin(self) -> None:
|
|
104
|
+
recorder = Recorder(200, EXECUTE_BODY)
|
|
105
|
+
result = client_for(recorder).execute("k7x2m9", facts={"Applicant": [{"income": 1}]}, version="1.0.0")
|
|
106
|
+
request = recorder.requests[0]
|
|
107
|
+
self.assertEqual(request.url.path, "/v1/execute/k7x2m9")
|
|
108
|
+
self.assertEqual(request.url.params["version"], "1.0.0")
|
|
109
|
+
self.assertEqual(json.loads(request.content), {"facts": {"Applicant": [{"income": 1}]}})
|
|
110
|
+
self.assertEqual(result.result, {"score": 82})
|
|
111
|
+
self.assertEqual(result.execution_time_ms, 0.41)
|
|
112
|
+
self.assertEqual(result.total_time_ms, 18.62)
|
|
113
|
+
|
|
114
|
+
def test_execute_without_version_sends_no_version_parameter(self) -> None:
|
|
115
|
+
recorder = Recorder(200, EXECUTE_BODY)
|
|
116
|
+
client_for(recorder).execute("k7x2m9", facts={})
|
|
117
|
+
self.assertNotIn("version", recorder.requests[0].url.params)
|
|
118
|
+
|
|
119
|
+
def test_production_key_register_403_raises_production_key_cannot_register_error(self) -> None:
|
|
120
|
+
body = {"error": "Production keys cannot register.", "code": "production_environment_key_cannot_register"}
|
|
121
|
+
with self.assertRaises(ProductionKeyCannotRegisterError) as caught:
|
|
122
|
+
register_call(client_for(Recorder(403, body)))
|
|
123
|
+
self.assertEqual(caught.exception.code, "production_environment_key_cannot_register")
|
|
124
|
+
self.assertEqual(caught.exception.status_code, 403)
|
|
125
|
+
|
|
126
|
+
def test_not_live_404_raises_ruleset_not_live_in_environment_error(self) -> None:
|
|
127
|
+
sentence = "Nothing is live in Production. Promote a version."
|
|
128
|
+
body = {"error": sentence, "code": "ruleset_not_live_in_environment"}
|
|
129
|
+
with self.assertRaises(RulesetNotLiveInEnvironmentError) as caught:
|
|
130
|
+
client_for(Recorder(404, body)).execute("k7x2m9", facts={})
|
|
131
|
+
self.assertEqual(caught.exception.code, "ruleset_not_live_in_environment")
|
|
132
|
+
self.assertEqual(caught.exception.status_code, 404)
|
|
133
|
+
self.assertEqual(str(caught.exception), sentence)
|
|
134
|
+
self.assertEqual(caught.exception.message, sentence)
|
|
135
|
+
|
|
136
|
+
def test_codeless_404_raises_boe_error_with_no_code(self) -> None:
|
|
137
|
+
with self.assertRaises(BOEError) as caught:
|
|
138
|
+
client_for(Recorder(404, {"error": "Ruleset not found."})).execute("zzzzzz", facts={})
|
|
139
|
+
self.assertIs(type(caught.exception), BOEError)
|
|
140
|
+
self.assertIsNone(caught.exception.code)
|
|
141
|
+
self.assertEqual(caught.exception.status_code, 404)
|
|
142
|
+
|
|
143
|
+
def test_unknown_error_code_raises_boe_error_with_code_and_status(self) -> None:
|
|
144
|
+
body = {"error": "Odd.", "code": "something_new"}
|
|
145
|
+
with self.assertRaises(BOEError) as caught:
|
|
146
|
+
register_call(client_for(Recorder(409, body)))
|
|
147
|
+
self.assertIs(type(caught.exception), BOEError)
|
|
148
|
+
self.assertEqual(caught.exception.code, "something_new")
|
|
149
|
+
self.assertEqual(caught.exception.status_code, 409)
|
|
150
|
+
|
|
151
|
+
def test_error_value_that_is_a_known_code_classifies(self) -> None:
|
|
152
|
+
with self.assertRaises(BOEError) as caught:
|
|
153
|
+
client_for(Recorder(410, {"error": "ruleset_archived"})).execute("k7x2m9", facts={})
|
|
154
|
+
self.assertEqual(caught.exception.code, "ruleset_archived")
|
|
155
|
+
|
|
156
|
+
def test_400_is_final_and_sends_one_request(self) -> None:
|
|
157
|
+
recorder = Recorder(400, {"error": "bad"})
|
|
158
|
+
with self.assertRaises(BOEError):
|
|
159
|
+
client_for(recorder).execute("k7x2m9", facts={})
|
|
160
|
+
self.assertEqual(len(recorder.requests), 1)
|
|
161
|
+
|
|
162
|
+
def test_500_retries_then_raises(self) -> None:
|
|
163
|
+
recorder = Recorder(500, {"error": "boom"})
|
|
164
|
+
with mock.patch("boerules._client.time.sleep"):
|
|
165
|
+
with self.assertRaises(BOEError):
|
|
166
|
+
client_for(recorder, max_retries=2).execute("k7x2m9", facts={})
|
|
167
|
+
self.assertEqual(len(recorder.requests), 3)
|
|
168
|
+
|
|
169
|
+
def test_api_key_and_base_url_read_from_environment(self) -> None:
|
|
170
|
+
recorder = Recorder(201, REGISTER_BODY)
|
|
171
|
+
env = {"BOE_API_KEY": "boe_env", "BOE_BASE_URL": "https://env.test/v1/"}
|
|
172
|
+
with mock.patch.dict(os.environ, env, clear=True):
|
|
173
|
+
boe = BOE(transport=httpx.MockTransport(recorder))
|
|
174
|
+
register_call(boe)
|
|
175
|
+
request = recorder.requests[0]
|
|
176
|
+
self.assertEqual(str(request.url), "https://env.test/v1/register")
|
|
177
|
+
self.assertEqual(request.headers["Authorization"], "Bearer boe_env")
|
|
178
|
+
|
|
179
|
+
def test_missing_api_key_raises_before_any_request(self) -> None:
|
|
180
|
+
recorder = Recorder(200, {})
|
|
181
|
+
with mock.patch.dict(os.environ, {}, clear=True):
|
|
182
|
+
with self.assertRaises(BOEError) as caught:
|
|
183
|
+
BOE(transport=httpx.MockTransport(recorder))
|
|
184
|
+
self.assertIn("BOE_API_KEY", str(caught.exception))
|
|
185
|
+
self.assertEqual(recorder.requests, [])
|
|
186
|
+
|
|
187
|
+
def test_context_manager_closes_client(self) -> None:
|
|
188
|
+
with client_for(Recorder(200, {})) as boe:
|
|
189
|
+
self.assertFalse(boe.is_closed)
|
|
190
|
+
self.assertTrue(boe.is_closed)
|
|
191
|
+
|
|
192
|
+
def test_execute_base_url_defaults_to_base_url(self) -> None:
|
|
193
|
+
boe = BOE(api_key="k", base_url="https://a.test/v1/")
|
|
194
|
+
self.assertEqual(boe.execute_base_url, "https://a.test/v1")
|
|
195
|
+
self.assertEqual(boe.execute_base_url, boe.base_url)
|
|
196
|
+
boe.close()
|
|
197
|
+
|
|
198
|
+
def test_error_names_and_fields_match_implementation_md(self) -> None:
|
|
199
|
+
text = IMPLEMENTATION_MD.read_text()
|
|
200
|
+
section = text.split("### Status and error table", 1)[1].split("\n## ", 1)[0]
|
|
201
|
+
codes: set[str] = set()
|
|
202
|
+
for line in section.splitlines():
|
|
203
|
+
if not line.startswith("| `"):
|
|
204
|
+
continue
|
|
205
|
+
cells = [cell.strip() for cell in line.strip().strip("|").split("|")]
|
|
206
|
+
found = re.fullmatch(r"`([A-Za-z_][A-Za-z0-9_]*)`", cells[3])
|
|
207
|
+
if found:
|
|
208
|
+
codes.add(found.group(1))
|
|
209
|
+
self.assertGreaterEqual(len(codes), 6)
|
|
210
|
+
self.assertEqual(codes - set(ERROR_CLASS_BY_CODE), set())
|
|
211
|
+
for code, error_class in ERROR_CLASS_BY_CODE.items():
|
|
212
|
+
self.assertTrue(issubclass(error_class, BOEError), code)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
@unittest.skipUnless(os.environ.get("BOE_API_KEY"), "BOE_API_KEY is not set")
|
|
216
|
+
class DeployedApiTests(unittest.TestCase):
|
|
217
|
+
def test_register_then_execute_against_deployed_api(self) -> None:
|
|
218
|
+
with BOE() as boe:
|
|
219
|
+
registered = boe.register(
|
|
220
|
+
id="python-sdk-proof",
|
|
221
|
+
mode="scoring",
|
|
222
|
+
source={
|
|
223
|
+
"id": "python-sdk-proof",
|
|
224
|
+
"mode": "scoring",
|
|
225
|
+
"rules": [
|
|
226
|
+
{
|
|
227
|
+
"id": "income-score",
|
|
228
|
+
"inputs": [{"name": "a", "type": "Applicant"}],
|
|
229
|
+
"then": {"score": ["multiply", 0.001, "$a.income"]},
|
|
230
|
+
}
|
|
231
|
+
],
|
|
232
|
+
},
|
|
233
|
+
)
|
|
234
|
+
executed = boe.execute(registered.short_code, facts={"Applicant": [{"income": 72000}]})
|
|
235
|
+
self.assertEqual(executed.short_code, registered.short_code)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
if __name__ == "__main__":
|
|
239
|
+
unittest.main()
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
from importlib import metadata
|
|
3
|
+
|
|
4
|
+
import boerules
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class VersionTest(unittest.TestCase):
|
|
8
|
+
def test_version_matches_installed_metadata(self) -> None:
|
|
9
|
+
try:
|
|
10
|
+
installed = metadata.version("boerules")
|
|
11
|
+
except metadata.PackageNotFoundError:
|
|
12
|
+
self.skipTest("boerules is not installed")
|
|
13
|
+
self.assertEqual(boerules.__version__, installed)
|
|
14
|
+
|
|
15
|
+
def test_version_is_a_string(self) -> None:
|
|
16
|
+
self.assertIsInstance(boerules.__version__, str)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
if __name__ == "__main__":
|
|
20
|
+
unittest.main()
|