crashbytes-result 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.
- crashbytes_result-1.0.0/.github/CODEOWNERS +1 -0
- crashbytes_result-1.0.0/.github/workflows/ci.yml +23 -0
- crashbytes_result-1.0.0/.github/workflows/publish.yml +19 -0
- crashbytes_result-1.0.0/.gitignore +11 -0
- crashbytes_result-1.0.0/LICENSE +21 -0
- crashbytes_result-1.0.0/PKG-INFO +87 -0
- crashbytes_result-1.0.0/README.md +59 -0
- crashbytes_result-1.0.0/pyproject.toml +53 -0
- crashbytes_result-1.0.0/src/crashbytes_result/__init__.py +5 -0
- crashbytes_result-1.0.0/src/crashbytes_result/_core.py +182 -0
- crashbytes_result-1.0.0/src/crashbytes_result/py.typed +0 -0
- crashbytes_result-1.0.0/tests/test_result.py +186 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
* @CrashBytes
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: [main]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
test:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
strategy:
|
|
13
|
+
matrix:
|
|
14
|
+
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v4
|
|
17
|
+
- uses: actions/setup-python@v5
|
|
18
|
+
with:
|
|
19
|
+
python-version: ${{ matrix.python-version }}
|
|
20
|
+
- run: pip install -e ".[dev]"
|
|
21
|
+
- run: ruff check src/ tests/
|
|
22
|
+
- run: mypy --strict src/
|
|
23
|
+
- run: pytest --cov=crashbytes_result --cov-branch --cov-fail-under=90
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags: ["*"]
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
publish:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
permissions:
|
|
11
|
+
id-token: write
|
|
12
|
+
steps:
|
|
13
|
+
- uses: actions/checkout@v4
|
|
14
|
+
- uses: actions/setup-python@v5
|
|
15
|
+
with:
|
|
16
|
+
python-version: "3.12"
|
|
17
|
+
- run: pip install build
|
|
18
|
+
- run: python -m build
|
|
19
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 CrashBytes
|
|
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.
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: crashbytes-result
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A practical Result type for Python — Ok, Err, and pattern matching.
|
|
5
|
+
Project-URL: Homepage, https://github.com/CrashBytes/crashbytes-result
|
|
6
|
+
Project-URL: Repository, https://github.com/CrashBytes/crashbytes-result
|
|
7
|
+
Project-URL: Issues, https://github.com/CrashBytes/crashbytes-result/issues
|
|
8
|
+
Author-email: CrashBytes <crashbytes@users.noreply.github.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: err,error-handling,monad,ok,pattern-matching,result
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: mypy; extra == 'dev'
|
|
24
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest-cov; extra == 'dev'
|
|
26
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# crashbytes-result
|
|
30
|
+
|
|
31
|
+
A practical Result type for Python — `Ok`, `Err`, and pattern matching.
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install crashbytes-result
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Usage
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from crashbytes_result import Ok, Err, Result, safe
|
|
43
|
+
|
|
44
|
+
def divide(a: float, b: float) -> Result[float, str]:
|
|
45
|
+
if b == 0:
|
|
46
|
+
return Err("division by zero")
|
|
47
|
+
return Ok(a / b)
|
|
48
|
+
|
|
49
|
+
result = divide(10, 3)
|
|
50
|
+
match result:
|
|
51
|
+
case Ok(value):
|
|
52
|
+
print(f"Result: {value}")
|
|
53
|
+
case Err(error):
|
|
54
|
+
print(f"Error: {error}")
|
|
55
|
+
|
|
56
|
+
# Or use .match()
|
|
57
|
+
msg = result.match(
|
|
58
|
+
ok=lambda v: f"Got {v:.2f}",
|
|
59
|
+
err=lambda e: f"Failed: {e}",
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
# @safe decorator
|
|
63
|
+
@safe
|
|
64
|
+
def parse_int(s: str) -> int:
|
|
65
|
+
return int(s)
|
|
66
|
+
|
|
67
|
+
parse_int("42") # Ok(42)
|
|
68
|
+
parse_int("abc") # Err(ValueError(...))
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## API
|
|
72
|
+
|
|
73
|
+
| Method | Ok | Err |
|
|
74
|
+
|--------|-----|------|
|
|
75
|
+
| `.unwrap()` | Returns value | Raises `UnwrapError` |
|
|
76
|
+
| `.unwrap_or(default)` | Returns value | Returns default |
|
|
77
|
+
| `.unwrap_err()` | Raises `UnwrapError` | Returns error |
|
|
78
|
+
| `.map(fn)` | `Ok(fn(value))` | `self` |
|
|
79
|
+
| `.map_err(fn)` | `self` | `Err(fn(error))` |
|
|
80
|
+
| `.bind(fn)` | `fn(value)` | `self` |
|
|
81
|
+
| `.match(ok, err)` | `ok(value)` | `err(error)` |
|
|
82
|
+
| `.is_ok` | `True` | `False` |
|
|
83
|
+
| `.is_err` | `False` | `True` |
|
|
84
|
+
|
|
85
|
+
## License
|
|
86
|
+
|
|
87
|
+
MIT
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# crashbytes-result
|
|
2
|
+
|
|
3
|
+
A practical Result type for Python — `Ok`, `Err`, and pattern matching.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install crashbytes-result
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from crashbytes_result import Ok, Err, Result, safe
|
|
15
|
+
|
|
16
|
+
def divide(a: float, b: float) -> Result[float, str]:
|
|
17
|
+
if b == 0:
|
|
18
|
+
return Err("division by zero")
|
|
19
|
+
return Ok(a / b)
|
|
20
|
+
|
|
21
|
+
result = divide(10, 3)
|
|
22
|
+
match result:
|
|
23
|
+
case Ok(value):
|
|
24
|
+
print(f"Result: {value}")
|
|
25
|
+
case Err(error):
|
|
26
|
+
print(f"Error: {error}")
|
|
27
|
+
|
|
28
|
+
# Or use .match()
|
|
29
|
+
msg = result.match(
|
|
30
|
+
ok=lambda v: f"Got {v:.2f}",
|
|
31
|
+
err=lambda e: f"Failed: {e}",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
# @safe decorator
|
|
35
|
+
@safe
|
|
36
|
+
def parse_int(s: str) -> int:
|
|
37
|
+
return int(s)
|
|
38
|
+
|
|
39
|
+
parse_int("42") # Ok(42)
|
|
40
|
+
parse_int("abc") # Err(ValueError(...))
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## API
|
|
44
|
+
|
|
45
|
+
| Method | Ok | Err |
|
|
46
|
+
|--------|-----|------|
|
|
47
|
+
| `.unwrap()` | Returns value | Raises `UnwrapError` |
|
|
48
|
+
| `.unwrap_or(default)` | Returns value | Returns default |
|
|
49
|
+
| `.unwrap_err()` | Raises `UnwrapError` | Returns error |
|
|
50
|
+
| `.map(fn)` | `Ok(fn(value))` | `self` |
|
|
51
|
+
| `.map_err(fn)` | `self` | `Err(fn(error))` |
|
|
52
|
+
| `.bind(fn)` | `fn(value)` | `self` |
|
|
53
|
+
| `.match(ok, err)` | `ok(value)` | `err(error)` |
|
|
54
|
+
| `.is_ok` | `True` | `False` |
|
|
55
|
+
| `.is_err` | `False` | `True` |
|
|
56
|
+
|
|
57
|
+
## License
|
|
58
|
+
|
|
59
|
+
MIT
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "crashbytes-result"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "A practical Result type for Python — Ok, Err, and pattern matching."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
authors = [{ name = "CrashBytes", email = "crashbytes@users.noreply.github.com" }]
|
|
13
|
+
keywords = ["result", "ok", "err", "monad", "error-handling", "pattern-matching"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 5 - Production/Stable",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.10",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Typing :: Typed",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
dev = ["pytest", "pytest-cov", "mypy", "ruff"]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://github.com/CrashBytes/crashbytes-result"
|
|
31
|
+
Repository = "https://github.com/CrashBytes/crashbytes-result"
|
|
32
|
+
Issues = "https://github.com/CrashBytes/crashbytes-result/issues"
|
|
33
|
+
|
|
34
|
+
[tool.ruff]
|
|
35
|
+
target-version = "py310"
|
|
36
|
+
line-length = 99
|
|
37
|
+
|
|
38
|
+
[tool.ruff.lint]
|
|
39
|
+
select = ["E", "F", "I", "N", "UP", "B", "SIM", "TCH"]
|
|
40
|
+
|
|
41
|
+
[tool.mypy]
|
|
42
|
+
strict = true
|
|
43
|
+
python_version = "3.10"
|
|
44
|
+
|
|
45
|
+
[tool.pytest.ini_options]
|
|
46
|
+
testpaths = ["tests"]
|
|
47
|
+
|
|
48
|
+
[tool.coverage.run]
|
|
49
|
+
branch = true
|
|
50
|
+
source = ["crashbytes_result"]
|
|
51
|
+
|
|
52
|
+
[tool.coverage.report]
|
|
53
|
+
fail_under = 90
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Result type for explicit error handling — Ok[T] | Err[E]."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import TYPE_CHECKING, Any, Generic, NoReturn, TypeVar
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
|
|
12
|
+
T = TypeVar("T")
|
|
13
|
+
U = TypeVar("U")
|
|
14
|
+
E = TypeVar("E")
|
|
15
|
+
F = TypeVar("F")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, slots=True)
|
|
19
|
+
class Ok(Generic[T]):
|
|
20
|
+
"""Represents a successful result containing a value."""
|
|
21
|
+
|
|
22
|
+
_value: T
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def value(self) -> T:
|
|
26
|
+
return self._value
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def is_ok(self) -> bool:
|
|
30
|
+
return True
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def is_err(self) -> bool:
|
|
34
|
+
return False
|
|
35
|
+
|
|
36
|
+
def unwrap(self) -> T:
|
|
37
|
+
"""Return the contained value."""
|
|
38
|
+
return self._value
|
|
39
|
+
|
|
40
|
+
def unwrap_or(self, default: object) -> T:
|
|
41
|
+
"""Return the contained value (ignores default)."""
|
|
42
|
+
return self._value
|
|
43
|
+
|
|
44
|
+
def unwrap_err(self) -> NoReturn:
|
|
45
|
+
"""Raise because this is Ok, not Err."""
|
|
46
|
+
raise UnwrapError(f"Called unwrap_err on Ok({self._value!r})")
|
|
47
|
+
|
|
48
|
+
def map(self, fn: Callable[[T], U]) -> Ok[U]:
|
|
49
|
+
"""Apply *fn* to the contained value."""
|
|
50
|
+
return Ok(fn(self._value))
|
|
51
|
+
|
|
52
|
+
def map_err(self, fn: Callable[[Any], Any]) -> Ok[T]:
|
|
53
|
+
"""No-op for Ok — return self."""
|
|
54
|
+
return self
|
|
55
|
+
|
|
56
|
+
def bind(self, fn: Callable[[T], Result[U, Any]]) -> Result[U, Any]:
|
|
57
|
+
"""Apply *fn* that returns a Result."""
|
|
58
|
+
return fn(self._value)
|
|
59
|
+
|
|
60
|
+
def match(
|
|
61
|
+
self,
|
|
62
|
+
ok: Callable[[T], U],
|
|
63
|
+
err: Callable[[Any], U],
|
|
64
|
+
) -> U:
|
|
65
|
+
"""Pattern match — calls *ok* branch."""
|
|
66
|
+
return ok(self._value)
|
|
67
|
+
|
|
68
|
+
def __repr__(self) -> str:
|
|
69
|
+
return f"Ok({self._value!r})"
|
|
70
|
+
|
|
71
|
+
# Support Python 3.10+ structural pattern matching
|
|
72
|
+
__match_args__ = ("_value",)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True, slots=True)
|
|
76
|
+
class Err(Generic[E]):
|
|
77
|
+
"""Represents a failed result containing an error."""
|
|
78
|
+
|
|
79
|
+
_error: E
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def error(self) -> E:
|
|
83
|
+
return self._error
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def is_ok(self) -> bool:
|
|
87
|
+
return False
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def is_err(self) -> bool:
|
|
91
|
+
return True
|
|
92
|
+
|
|
93
|
+
def unwrap(self) -> NoReturn:
|
|
94
|
+
"""Raise because this is Err."""
|
|
95
|
+
raise UnwrapError(f"Called unwrap on Err({self._error!r})")
|
|
96
|
+
|
|
97
|
+
def unwrap_or(self, default: T) -> T:
|
|
98
|
+
"""Return *default* because this is Err."""
|
|
99
|
+
return default
|
|
100
|
+
|
|
101
|
+
def unwrap_err(self) -> E:
|
|
102
|
+
"""Return the contained error."""
|
|
103
|
+
return self._error
|
|
104
|
+
|
|
105
|
+
def map(self, fn: Callable[[Any], Any]) -> Err[E]:
|
|
106
|
+
"""No-op for Err — return self."""
|
|
107
|
+
return self
|
|
108
|
+
|
|
109
|
+
def map_err(self, fn: Callable[[E], F]) -> Err[F]:
|
|
110
|
+
"""Apply *fn* to the contained error."""
|
|
111
|
+
return Err(fn(self._error))
|
|
112
|
+
|
|
113
|
+
def bind(self, fn: Callable[[Any], Any]) -> Err[E]:
|
|
114
|
+
"""No-op for Err — return self."""
|
|
115
|
+
return self
|
|
116
|
+
|
|
117
|
+
def match(
|
|
118
|
+
self,
|
|
119
|
+
ok: Callable[[Any], U],
|
|
120
|
+
err: Callable[[E], U],
|
|
121
|
+
) -> U:
|
|
122
|
+
"""Pattern match — calls *err* branch."""
|
|
123
|
+
return err(self._error)
|
|
124
|
+
|
|
125
|
+
def __repr__(self) -> str:
|
|
126
|
+
return f"Err({self._error!r})"
|
|
127
|
+
|
|
128
|
+
__match_args__ = ("_error",)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
Result = Ok[T] | Err[E]
|
|
132
|
+
"""Type alias: a value is either ``Ok[T]`` or ``Err[E]``."""
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class UnwrapError(Exception):
|
|
136
|
+
"""Raised when unwrapping a Result incorrectly."""
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def safe(
|
|
140
|
+
*args: Any,
|
|
141
|
+
) -> Any:
|
|
142
|
+
"""Decorator that wraps a function to return ``Ok`` or ``Err``.
|
|
143
|
+
|
|
144
|
+
Usage::
|
|
145
|
+
|
|
146
|
+
@safe
|
|
147
|
+
def parse_int(s: str) -> int:
|
|
148
|
+
return int(s)
|
|
149
|
+
|
|
150
|
+
@safe(ValueError, KeyError)
|
|
151
|
+
def lookup(data: dict, key: str) -> str:
|
|
152
|
+
return data[key]
|
|
153
|
+
"""
|
|
154
|
+
if len(args) == 1 and callable(args[0]) and not (
|
|
155
|
+
isinstance(args[0], type) and issubclass(args[0], BaseException)
|
|
156
|
+
):
|
|
157
|
+
fn = args[0]
|
|
158
|
+
|
|
159
|
+
@functools.wraps(fn)
|
|
160
|
+
def wrapper(*a: Any, **kw: Any) -> Any:
|
|
161
|
+
try:
|
|
162
|
+
return Ok(fn(*a, **kw))
|
|
163
|
+
except Exception as exc:
|
|
164
|
+
return Err(exc)
|
|
165
|
+
|
|
166
|
+
return wrapper
|
|
167
|
+
|
|
168
|
+
exceptions = tuple(args)
|
|
169
|
+
if not exceptions:
|
|
170
|
+
exceptions = (Exception,)
|
|
171
|
+
|
|
172
|
+
def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
|
|
173
|
+
@functools.wraps(fn)
|
|
174
|
+
def wrapper(*a: Any, **kw: Any) -> Any:
|
|
175
|
+
try:
|
|
176
|
+
return Ok(fn(*a, **kw))
|
|
177
|
+
except exceptions as exc:
|
|
178
|
+
return Err(exc)
|
|
179
|
+
|
|
180
|
+
return wrapper
|
|
181
|
+
|
|
182
|
+
return decorator
|
|
File without changes
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Tests for crashbytes-result."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from crashbytes_result import Err, Ok, UnwrapError, safe
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TestOk:
|
|
11
|
+
def test_value(self) -> None:
|
|
12
|
+
assert Ok(42).value == 42
|
|
13
|
+
|
|
14
|
+
def test_is_ok(self) -> None:
|
|
15
|
+
assert Ok(1).is_ok is True
|
|
16
|
+
|
|
17
|
+
def test_is_err(self) -> None:
|
|
18
|
+
assert Ok(1).is_err is False
|
|
19
|
+
|
|
20
|
+
def test_unwrap(self) -> None:
|
|
21
|
+
assert Ok("hello").unwrap() == "hello"
|
|
22
|
+
|
|
23
|
+
def test_unwrap_or(self) -> None:
|
|
24
|
+
assert Ok(10).unwrap_or(0) == 10
|
|
25
|
+
|
|
26
|
+
def test_unwrap_err_raises(self) -> None:
|
|
27
|
+
with pytest.raises(UnwrapError, match="Called unwrap_err on Ok"):
|
|
28
|
+
Ok(1).unwrap_err()
|
|
29
|
+
|
|
30
|
+
def test_map(self) -> None:
|
|
31
|
+
result = Ok(5).map(lambda x: x * 2)
|
|
32
|
+
assert result == Ok(10)
|
|
33
|
+
|
|
34
|
+
def test_map_err_is_noop(self) -> None:
|
|
35
|
+
result = Ok(5).map_err(lambda e: str(e))
|
|
36
|
+
assert result == Ok(5)
|
|
37
|
+
|
|
38
|
+
def test_bind_ok(self) -> None:
|
|
39
|
+
result = Ok(5).bind(lambda x: Ok(x + 1))
|
|
40
|
+
assert result == Ok(6)
|
|
41
|
+
|
|
42
|
+
def test_bind_err(self) -> None:
|
|
43
|
+
result = Ok(5).bind(lambda x: Err("fail"))
|
|
44
|
+
assert result == Err("fail")
|
|
45
|
+
|
|
46
|
+
def test_match_ok(self) -> None:
|
|
47
|
+
value = Ok(42).match(ok=lambda v: f"got {v}", err=lambda e: f"err {e}")
|
|
48
|
+
assert value == "got 42"
|
|
49
|
+
|
|
50
|
+
def test_repr(self) -> None:
|
|
51
|
+
assert repr(Ok(42)) == "Ok(42)"
|
|
52
|
+
assert repr(Ok("hi")) == "Ok('hi')"
|
|
53
|
+
|
|
54
|
+
def test_equality(self) -> None:
|
|
55
|
+
assert Ok(1) == Ok(1)
|
|
56
|
+
assert Ok(1) != Ok(2)
|
|
57
|
+
assert Ok(1) != Err(1)
|
|
58
|
+
|
|
59
|
+
def test_frozen(self) -> None:
|
|
60
|
+
with pytest.raises(AttributeError):
|
|
61
|
+
Ok(1)._value = 2 # type: ignore[misc]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class TestErr:
|
|
65
|
+
def test_error(self) -> None:
|
|
66
|
+
assert Err("fail").error == "fail"
|
|
67
|
+
|
|
68
|
+
def test_is_ok(self) -> None:
|
|
69
|
+
assert Err("x").is_ok is False
|
|
70
|
+
|
|
71
|
+
def test_is_err(self) -> None:
|
|
72
|
+
assert Err("x").is_err is True
|
|
73
|
+
|
|
74
|
+
def test_unwrap_raises(self) -> None:
|
|
75
|
+
with pytest.raises(UnwrapError, match="Called unwrap on Err"):
|
|
76
|
+
Err("oops").unwrap()
|
|
77
|
+
|
|
78
|
+
def test_unwrap_or(self) -> None:
|
|
79
|
+
assert Err("fail").unwrap_or(42) == 42
|
|
80
|
+
|
|
81
|
+
def test_unwrap_err(self) -> None:
|
|
82
|
+
assert Err("fail").unwrap_err() == "fail"
|
|
83
|
+
|
|
84
|
+
def test_map_is_noop(self) -> None:
|
|
85
|
+
result = Err("fail").map(lambda x: x * 2)
|
|
86
|
+
assert result == Err("fail")
|
|
87
|
+
|
|
88
|
+
def test_map_err(self) -> None:
|
|
89
|
+
result = Err("fail").map_err(lambda e: e.upper())
|
|
90
|
+
assert result == Err("FAIL")
|
|
91
|
+
|
|
92
|
+
def test_bind_is_noop(self) -> None:
|
|
93
|
+
result = Err("fail").bind(lambda x: Ok(x + 1))
|
|
94
|
+
assert result == Err("fail")
|
|
95
|
+
|
|
96
|
+
def test_match_err(self) -> None:
|
|
97
|
+
value = Err("bad").match(ok=lambda v: f"got {v}", err=lambda e: f"err {e}")
|
|
98
|
+
assert value == "err bad"
|
|
99
|
+
|
|
100
|
+
def test_repr(self) -> None:
|
|
101
|
+
assert repr(Err("fail")) == "Err('fail')"
|
|
102
|
+
|
|
103
|
+
def test_equality(self) -> None:
|
|
104
|
+
assert Err("a") == Err("a")
|
|
105
|
+
assert Err("a") != Err("b")
|
|
106
|
+
assert Err(1) != Ok(1)
|
|
107
|
+
|
|
108
|
+
def test_frozen(self) -> None:
|
|
109
|
+
with pytest.raises(AttributeError):
|
|
110
|
+
Err("x")._error = "y" # type: ignore[misc]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class TestPatternMatching:
|
|
114
|
+
def test_match_ok(self) -> None:
|
|
115
|
+
result: Ok[int] | Err[str] = Ok(42)
|
|
116
|
+
match result:
|
|
117
|
+
case Ok(value):
|
|
118
|
+
assert value == 42
|
|
119
|
+
case Err(error):
|
|
120
|
+
pytest.fail(f"Unexpected Err: {error}")
|
|
121
|
+
|
|
122
|
+
def test_match_err(self) -> None:
|
|
123
|
+
result: Ok[int] | Err[str] = Err("fail")
|
|
124
|
+
match result:
|
|
125
|
+
case Ok(value):
|
|
126
|
+
pytest.fail(f"Unexpected Ok: {value}")
|
|
127
|
+
case Err(error):
|
|
128
|
+
assert error == "fail"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class TestSafeDecorator:
|
|
132
|
+
def test_safe_returns_ok(self) -> None:
|
|
133
|
+
@safe
|
|
134
|
+
def parse(s: str) -> int:
|
|
135
|
+
return int(s)
|
|
136
|
+
|
|
137
|
+
result = parse("42")
|
|
138
|
+
assert result == Ok(42)
|
|
139
|
+
|
|
140
|
+
def test_safe_returns_err(self) -> None:
|
|
141
|
+
@safe
|
|
142
|
+
def parse(s: str) -> int:
|
|
143
|
+
return int(s)
|
|
144
|
+
|
|
145
|
+
result = parse("abc")
|
|
146
|
+
assert isinstance(result, Err)
|
|
147
|
+
assert isinstance(result.error, ValueError)
|
|
148
|
+
|
|
149
|
+
def test_safe_with_specific_exceptions(self) -> None:
|
|
150
|
+
@safe(ValueError)
|
|
151
|
+
def parse(s: str) -> int:
|
|
152
|
+
return int(s)
|
|
153
|
+
|
|
154
|
+
result = parse("abc")
|
|
155
|
+
assert isinstance(result, Err)
|
|
156
|
+
|
|
157
|
+
def test_safe_with_specific_exceptions_unhandled(self) -> None:
|
|
158
|
+
@safe(ValueError)
|
|
159
|
+
def parse(s: str) -> int:
|
|
160
|
+
raise TypeError("wrong type")
|
|
161
|
+
|
|
162
|
+
with pytest.raises(TypeError, match="wrong type"):
|
|
163
|
+
parse("abc")
|
|
164
|
+
|
|
165
|
+
def test_safe_preserves_name(self) -> None:
|
|
166
|
+
@safe
|
|
167
|
+
def my_func() -> int:
|
|
168
|
+
return 1
|
|
169
|
+
|
|
170
|
+
assert my_func.__name__ == "my_func"
|
|
171
|
+
|
|
172
|
+
def test_safe_with_kwargs(self) -> None:
|
|
173
|
+
@safe
|
|
174
|
+
def add(a: int, b: int = 0) -> int:
|
|
175
|
+
return a + b
|
|
176
|
+
|
|
177
|
+
assert add(1, b=2) == Ok(3)
|
|
178
|
+
|
|
179
|
+
def test_safe_no_args_catches_all(self) -> None:
|
|
180
|
+
@safe()
|
|
181
|
+
def boom() -> int:
|
|
182
|
+
raise RuntimeError("boom")
|
|
183
|
+
|
|
184
|
+
result = boom()
|
|
185
|
+
assert isinstance(result, Err)
|
|
186
|
+
assert isinstance(result.error, RuntimeError)
|