zstdlib 0.10.6__tar.gz → 0.10.8__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.
Files changed (44) hide show
  1. {zstdlib-0.10.6 → zstdlib-0.10.8}/PKG-INFO +3 -4
  2. {zstdlib-0.10.6 → zstdlib-0.10.8}/pyproject.toml +9 -5
  3. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/log/test_cute.py +12 -3
  4. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/log/test_trace.py +3 -3
  5. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/test_enum.py +3 -3
  6. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/test_io.py +8 -8
  7. zstdlib-0.10.8/tests/test_keyed_instance.py +304 -0
  8. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/test_prompt.py +35 -9
  9. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/test_singleton.py +7 -4
  10. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/__init__.py +6 -2
  11. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/ansi.py +3 -3
  12. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/enum.py +6 -4
  13. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/frozen.py +30 -19
  14. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/io.py +28 -22
  15. zstdlib-0.10.8/zstdlib/keyed_instance.py +164 -0
  16. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/lazy.py +2 -5
  17. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/macos.py +3 -3
  18. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/prompt.py +18 -10
  19. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/signal_cm.py +2 -1
  20. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/singleton.py +3 -5
  21. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib.egg-info/PKG-INFO +3 -4
  22. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib.egg-info/SOURCES.txt +2 -0
  23. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib.egg-info/requires.txt +1 -0
  24. {zstdlib-0.10.6 → zstdlib-0.10.8}/LICENSE +0 -0
  25. {zstdlib-0.10.6 → zstdlib-0.10.8}/README.md +0 -0
  26. {zstdlib-0.10.6 → zstdlib-0.10.8}/setup.cfg +0 -0
  27. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/__init__.py +0 -0
  28. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/log/__init__.py +0 -0
  29. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/log/base.py +0 -0
  30. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/test_ansi.py +0 -0
  31. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/test_exc_capture.py +0 -0
  32. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/test_frozen.py +0 -0
  33. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/test_hybridmethod.py +0 -0
  34. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/test_lazy.py +0 -0
  35. {zstdlib-0.10.6 → zstdlib-0.10.8}/tests/test_not_set.py +0 -0
  36. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/exc_capture.py +0 -0
  37. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/hybridmethod.py +0 -0
  38. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/log/__init__.py +0 -0
  39. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/log/cute.py +0 -0
  40. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/log/trace.py +0 -0
  41. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/not_set.py +0 -0
  42. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib/py.typed +0 -0
  43. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib.egg-info/dependency_links.txt +0 -0
  44. {zstdlib-0.10.6 → zstdlib-0.10.8}/zstdlib.egg-info/top_level.txt +0 -0
@@ -1,16 +1,15 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zstdlib
3
- Version: 0.10.6
3
+ Version: 0.10.8
4
4
  Summary: A set of useful python utilities
5
- License: GPLv3
5
+ License-Expression: GPL-3.0-only
6
6
  Project-URL: Homepage, https://github.com/zwimer/zstdlib
7
7
  Classifier: Programming Language :: Python :: 3
8
8
  Classifier: Programming Language :: Python :: 3.14
9
- Classifier: Development Status :: 5 - Production/Stable
10
- Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
11
9
  Requires-Python: >=3.14
12
10
  Description-Content-Type: text/markdown
13
11
  License-File: LICENSE
12
+ Requires-Dist: fasteners
14
13
  Requires-Dist: osascript2
15
14
  Dynamic: license-file
16
15
 
@@ -1,5 +1,5 @@
1
1
  [build-system]
2
- requires = ["setuptools>=61.2"]
2
+ requires = ["setuptools>=77"]
3
3
  build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
@@ -7,15 +7,15 @@ name = "zstdlib"
7
7
  classifiers = [
8
8
  "Programming Language :: Python :: 3",
9
9
  "Programming Language :: Python :: 3.14",
10
- "Development Status :: 5 - Production/Stable",
11
- "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
12
10
  ]
13
- license = {text = "GPLv3"}
11
+ license = "GPL-3.0-only"
12
+ license-files = ["LICENSE"]
14
13
  description = "A set of useful python utilities"
15
14
  urls = {Homepage = "https://github.com/zwimer/zstdlib"}
16
15
  requires-python = ">= 3.14"
17
16
  dynamic = ["version"]
18
17
  dependencies = [
18
+ "fasteners",
19
19
  "osascript2" # For macOS
20
20
  ]
21
21
 
@@ -25,7 +25,6 @@ content-type = "text/markdown"
25
25
 
26
26
  [tool.setuptools]
27
27
  include-package-data = true
28
- license-files = ["LICENSE"]
29
28
 
30
29
  [tool.setuptools.packages.find]
31
30
  namespaces = false
@@ -40,6 +39,7 @@ attr = "zstdlib.__version__"
40
39
 
41
40
  [tool.pylint.MASTER]
42
41
  ignore-paths = '^tests/.*$'
42
+ jobs = 0
43
43
  [tool.pylint."MESSAGES CONTROL"]
44
44
  disable = [
45
45
  "unnecessary-lambda-assignment",
@@ -50,6 +50,9 @@ disable = [
50
50
  "invalid-name"
51
51
  ]
52
52
 
53
+ [tool.mypy]
54
+ strict = true
55
+
53
56
  [tool.black]
54
57
  line-length = 110
55
58
  target-version = ["py314"]
@@ -63,6 +66,7 @@ ignore=[
63
66
  "E731",
64
67
  "I001",
65
68
  "PLR0913", "PLR2004",
69
+ "PYI025",
66
70
  "S101", "S603",
67
71
  "TID252",
68
72
  ]
@@ -69,7 +69,10 @@ class TestCuteFormatter(LeftBase, unittest.TestCase):
69
69
  for i in levels:
70
70
  log.log(i, msg)
71
71
  self.assertEqual(len(levels), len(self.messages[log]))
72
- l_name = lambda idx: self.messages[log][idx].split("|")[0].strip()
72
+
73
+ def l_name(idx: int) -> str:
74
+ return self.messages[log][idx].split("|")[0].strip()
75
+
73
76
  self.assertEqual(Color.dim("Level 5".ljust(8)), l_name(0))
74
77
  self.assertEqual("DEBUG", l_name(1))
75
78
  self.assertEqual(Color.blue("INFO".ljust(8)), l_name(2))
@@ -85,7 +88,10 @@ class TestCuteFormatter(LeftBase, unittest.TestCase):
85
88
  log.log(4, msg)
86
89
  log.log(5, msg)
87
90
  self.assertEqual(2, len(self.messages[log]))
88
- l_name = lambda idx: self.messages[log][idx].split("|")[0].strip()
91
+
92
+ def l_name(idx: int) -> str:
93
+ return self.messages[log][idx].split("|")[0].strip()
94
+
89
95
  self.assertEqual(Color.dim("Level 4".ljust(8)), l_name(0))
90
96
  self.assertEqual("Level 5", l_name(1))
91
97
 
@@ -96,7 +102,10 @@ class TestCuteFormatter(LeftBase, unittest.TestCase):
96
102
  log.log(14, msg)
97
103
  log.log(15, msg)
98
104
  self.assertEqual(2, len(self.messages[log]))
99
- l_name = lambda idx: self.messages[log][idx].split("|")[0].strip()
105
+
106
+ def l_name(idx: int) -> str:
107
+ return self.messages[log][idx].split("|")[0].strip()
108
+
100
109
  self.assertEqual("Level 14".ljust(8), l_name(0))
101
110
  self.assertEqual(Color.bright_red_bg_yellow("Level 15".ljust(8)), l_name(1))
102
111
 
@@ -42,15 +42,15 @@ class TestTrace(LeftBase, unittest.TestCase):
42
42
  self.assertTrue(hasattr(logging, "trace"))
43
43
  self.assertTrue(hasattr(logging.getLogger(), "trace"))
44
44
  self.assertEqual(logging.TRACE, 5)
45
- self.assertEqual(logging.getLevelName(logging.TRACE), "TRACE") # type: ignore[call-overload]
45
+ self.assertEqual(logging.getLevelName(logging.TRACE), "TRACE")
46
46
  # Root check
47
47
  with self.hijack("") as log:
48
48
  old = log.getEffectiveLevel()
49
49
  # pylint: disable-next=not-callable
50
- logging.trace("test1") # type: ignore[misc]
50
+ logging.trace("test1")
51
51
  log.setLevel(logging.DEBUG)
52
52
  # pylint: disable-next=not-callable
53
- logging.trace("test2") # type: ignore[misc]
53
+ logging.trace("test2")
54
54
  log.setLevel(old)
55
55
  self.assertEqual(self.messages[log], ["test1"])
56
56
  # Logger check
@@ -1,5 +1,5 @@
1
1
  # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring,unused-variable
2
- from typing import Self
2
+ from typing import Self, Any
3
3
  import unittest
4
4
 
5
5
  from zstdlib.enum import EnumType, Enum, entries, values, auto
@@ -25,7 +25,7 @@ class TestEnumType(unittest.TestCase):
25
25
  class ET1(metaclass=EnumType, dupes_ok=True):
26
26
  a: int = 5
27
27
  b: int = 5
28
- c: dict = {} # noqa: RUF012
28
+ c: dict[Any, Any] = {} # noqa: RUF012
29
29
 
30
30
  with self.assertRaises(ValueError):
31
31
 
@@ -36,7 +36,7 @@ class TestEnumType(unittest.TestCase):
36
36
  with self.assertRaises(TypeError):
37
37
 
38
38
  class ET3(metaclass=EnumType):
39
- a: dict = {} # noqa: RUF012
39
+ a: dict[Any, Any] = {} # noqa: RUF012
40
40
 
41
41
  def test_type_check(self) -> None:
42
42
  class ET1(metaclass=EnumType, type_check=set()):
@@ -5,7 +5,7 @@ import unittest
5
5
  from zstdlib.io import ProtectedFile, BinaryIO, TextIO, io
6
6
 
7
7
 
8
- class RamFile(tempfile.SpooledTemporaryFile):
8
+ class RamFile(tempfile.SpooledTemporaryFile[Any]):
9
9
  """A file-like object that stores its contents in memory."""
10
10
 
11
11
  rollover = NotImplemented # Disallow rollover
@@ -22,7 +22,7 @@ class RamFile(tempfile.SpooledTemporaryFile):
22
22
  class TestIO(unittest.TestCase):
23
23
 
24
24
  def test_init(self) -> None:
25
- with RamFile(mode="wb+") as fb, RamFile() as fs:
25
+ with RamFile(mode="w+b") as fb, RamFile() as fs:
26
26
  ts = TextIO(fs)
27
27
  tb = BinaryIO(fb)
28
28
  with self.assertRaises(TypeError):
@@ -44,7 +44,7 @@ class TestIO(unittest.TestCase):
44
44
  def test_unread(self) -> None:
45
45
  with RamFile() as raw:
46
46
  f = io(raw)
47
- f.unread("hello") # type: ignore[arg-type] # STF types as bytes regardless of mode :/
47
+ f.unread("hello")
48
48
  self.assertEqual("hello", f._buffer)
49
49
 
50
50
  def test_read(self) -> None:
@@ -55,18 +55,18 @@ class TestIO(unittest.TestCase):
55
55
  self.assertEqual("fo", f.read(2))
56
56
  self.assertEqual("o", f.read(1))
57
57
  # Test read of buffer
58
- f.unread("bar") # type: ignore[arg-type] # STF types as bytes regardless of mode :/
58
+ f.unread("bar")
59
59
  self.assertEqual("b", f.read(1))
60
60
  # Test read of file + buffer
61
- f.unread("foob") # type: ignore[arg-type] # STF types as bytes regardless of mode :/
61
+ f.unread("foob")
62
62
  self.assertEqual("foobar", f.read(6))
63
- f.unread("foobar") # type: ignore[arg-type] # STF types as bytes regardless of mode :/
63
+ f.unread("foobar")
64
64
  self.assertEqual("foobarbaz", f.read())
65
65
 
66
66
  def test_peek(self) -> None:
67
67
  with RamFile() as raw:
68
68
  f = io(raw)
69
- f.unread("foo") # type: ignore[arg-type] # STF types as bytes regardless of mode :/
69
+ f.unread("foo")
70
70
  # Test peek of buffer
71
71
  for i in range(3):
72
72
  self.assertEqual("fo", f.peek(2))
@@ -77,7 +77,7 @@ class TestIO(unittest.TestCase):
77
77
  self.assertEqual("ba", f.peek(2))
78
78
  self.assertEqual("bar", f.read())
79
79
  # Test peek of both
80
- f.unread("baz") # type: ignore[arg-type] # STF types as bytes regardless of mode :/
80
+ f.unread("baz")
81
81
  raw.load("qux")
82
82
  for i in range(3):
83
83
  for k in range(5):
@@ -0,0 +1,304 @@
1
+ # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
2
+ from collections.abc import Callable, Iterator
3
+ from dataclasses import dataclass, field
4
+ from threading import Thread, get_ident
5
+ from contextlib import contextmanager
6
+ import multiprocessing as mp
7
+ from typing import Any
8
+ import traceback
9
+ import unittest
10
+ import pickle # nosec B403
11
+ import time
12
+ import sys
13
+ import os
14
+
15
+ from zstdlib.keyed_instance import KeyedInstanceProcessError
16
+ from zstdlib import CircularConstructionError, KeyedInstance
17
+
18
+
19
+ class Nop:
20
+ def __init__(self, key: int, *_: object) -> None:
21
+ self.key = key
22
+
23
+
24
+ # For test cases involving forking
25
+
26
+
27
+ def nop() -> None:
28
+ pass
29
+
30
+
31
+ @contextmanager
32
+ def try_do(name: str, q: mp.Queue[str]) -> Iterator[None]:
33
+ try:
34
+ yield
35
+ except KeyedInstanceProcessError:
36
+ q.put("KIPE")
37
+ except Exception as e: # noqa: BLE001
38
+ traceback.print_exc()
39
+ q.put(f"{e.__class__.__name__}: {e.args[0]}")
40
+ else:
41
+ q.put(name)
42
+
43
+
44
+ def subprocess_fn(q: mp.Queue[str]) -> None:
45
+ def test4() -> None:
46
+ with try_do("os.fork", q):
47
+ if not os.fork(): # Child dies
48
+ sys.exit(0)
49
+ for i in ("fork", "spawn"):
50
+ with try_do(f"mp.{i}", q):
51
+ p = mp.get_context(i).Process(target=nop) # type: ignore[attr-defined]
52
+ p.start()
53
+ p.join(1)
54
+ if p.is_alive():
55
+ p.kill()
56
+ raise RuntimeError("Process had to be killed")
57
+
58
+ # Multiprocessing is allowed right now, these should work
59
+ test4()
60
+
61
+ # Define a subclass
62
+ class Foo(KeyedInstance, Nop):
63
+ pass
64
+
65
+ # No instances yet, still ok
66
+ test4()
67
+ _ = Foo(1)
68
+
69
+ # This should fail, except spawn
70
+ test4()
71
+
72
+
73
+ # Main test cases
74
+
75
+
76
+ class TestKeyedInstance(unittest.TestCase):
77
+
78
+ def test_subclass(self) -> None:
79
+
80
+ class Foo(KeyedInstance, Nop):
81
+ pass
82
+
83
+ class Sup:
84
+ pass
85
+
86
+ with self.assertRaises(TypeError):
87
+
88
+ class Bar1(Sup, Foo):
89
+ pass
90
+
91
+ with self.assertRaises(TypeError):
92
+
93
+ class Bar2(Foo, Sup):
94
+ pass
95
+
96
+ def test_key(self) -> None:
97
+
98
+ class Foo(KeyedInstance, Nop):
99
+ pass
100
+
101
+ class Bar(KeyedInstance, Nop):
102
+ pass
103
+
104
+ a1_1 = Foo(1)
105
+ a1_2 = Foo(1)
106
+ a1_3 = Foo(1, 6)
107
+ a2_1 = Foo(2)
108
+ b1_1 = Bar(1)
109
+ b1_2 = Bar(1)
110
+
111
+ self.assertIs(a1_1, a1_2)
112
+ self.assertIs(a1_1, a1_3)
113
+ self.assertIs(b1_1, b1_2)
114
+ self.assertIsNot(a1_1, a2_1)
115
+ self.assertIsNot(a1_1, b1_1)
116
+
117
+ def test_circular(self) -> None:
118
+
119
+ class ToZero(KeyedInstance):
120
+ def __init__(self, x: int) -> None:
121
+ assert 0 <= x < 10
122
+ if x > 0:
123
+ _ = type(self)(x - 1)
124
+
125
+ _ = ToZero(6)
126
+
127
+ class Crazy(KeyedInstance):
128
+ def __init__(self, b: bool) -> None:
129
+ self.same = type(self)(b) # Father is self, circle
130
+
131
+ with self.assertRaises(CircularConstructionError):
132
+ _ = Crazy(True)
133
+
134
+ class Crazy2(KeyedInstance):
135
+ def __init__(self, b: bool) -> None:
136
+ self.inverse = type(self)(not b) # Grandfather is self
137
+
138
+ with self.assertRaises(CircularConstructionError):
139
+ _ = Crazy2(True)
140
+
141
+ def test_multiproc(self) -> None:
142
+
143
+ class Foo(KeyedInstance, Nop):
144
+ pass
145
+
146
+ foo1 = Foo(1)
147
+ with self.assertRaises(TypeError):
148
+ _ = pickle.dumps(foo1)
149
+
150
+ # Run tests
151
+ q: mp.Queue[str] = mp.Queue()
152
+ p = mp.get_context("spawn").Process(target=subprocess_fn, args=(q,))
153
+ p.start()
154
+ p.join(10) # This should be rather instant, this is generous
155
+ alive = p.is_alive()
156
+ time.sleep(0.1) # Let everything flush to the queue, just in case
157
+ q.put("Alive" if alive else "Dead")
158
+ if alive:
159
+ p.kill()
160
+ q.put(str(p.exitcode))
161
+ fin = "queue done, shutdown"
162
+ q.put(fin) # Better than relying on Empty b/c queue pipe / caches aren't instant
163
+ time.sleep(0.1) # Let everything flush to the queue, just in case
164
+
165
+ # Check results
166
+ results: list[str] = []
167
+ while not results or results[-1] != fin:
168
+ results.append(q.get(timeout=3)) # Should be done nearly instantly
169
+ expected: list[str] = ["os.fork", "mp.fork", "mp.spawn"] * 2
170
+ expected += ["KIPE", "KIPE", "mp.spawn", "Dead", "0", fin]
171
+ self.assertEqual(results, expected)
172
+
173
+ def test_interthread(self) -> None:
174
+
175
+ scale: int = 4 # Higher runs faster, lower is more accurate
176
+ actions: list[Action] = []
177
+ type RV_T = C1 | C2 | Exception
178
+
179
+ @dataclass(frozen=True)
180
+ class Action:
181
+ msg: str
182
+ tid: int = field(default_factory=lambda: get_ident())
183
+ ts: float = field(default_factory=lambda: time.monotonic())
184
+
185
+ @staticmethod
186
+ def strs(x: list[Action]) -> list[str]:
187
+ start = x[0].ts
188
+ tids = list({i.tid for i in x})
189
+ return [f"{round(scale*(i.ts-start))} | Thread-{tids.index(i.tid)+1} | {i.msg}" for i in x]
190
+
191
+ def save_results(fn: Callable[[], C1 | C2], ret: list[RV_T]) -> None:
192
+ try:
193
+ ret.append(fn())
194
+ except Exception as e: # noqa: BLE001
195
+ ret.append(e)
196
+
197
+ def dispatch_functions(*fns: Callable[[], RV_T]) -> list[RV_T]:
198
+ assert fns
199
+ rv: list[list[RV_T]] = [[] for i in fns]
200
+ ts = [Thread(target=lambda y=i, z=k: save_results(y, z), daemon=True) for i, k in zip(fns, rv)]
201
+ for t in ts:
202
+ t.start()
203
+ time.sleep(2 / scale / len(fns))
204
+ end = time.monotonic() + 10 # Generous timeout
205
+ for t in ts:
206
+ t.join(max(0, end - time.monotonic()))
207
+ if any(i.is_alive() for i in ts):
208
+ raise RuntimeError("Threads did not die")
209
+ if any(len(i) != 1 for i in rv):
210
+ raise ValueError("dispatch_functions failed")
211
+ return [i[0] for i in rv]
212
+
213
+ class _Body:
214
+ def _init(self, other: type[C1 | C2], key: int, *nxt: int) -> Any:
215
+ name = f"{self.__class__.__name__}({key}), next={list(nxt)}"
216
+ actions.append(Action(f"{name} - start"))
217
+ time.sleep(2 / scale)
218
+ second = f"{other.__name__}({nxt[0]})" if nxt else "None"
219
+ try:
220
+ actions.append(Action(f"{name} - requesting {second}"))
221
+ if nxt:
222
+ _ = other(*nxt)
223
+ except:
224
+ actions.append(Action(f"{name} - err: {second}"))
225
+ raise
226
+ actions.append(Action(f"{name} - done"))
227
+
228
+ class C1(KeyedInstance, _Body):
229
+ def __init__(self, key: int, *nxt: int) -> None:
230
+ self._init(C2, key, *nxt)
231
+
232
+ class C2(KeyedInstance, _Body):
233
+ def __init__(self, key: int, *nxt: int) -> None:
234
+ self._init(C1, key, *nxt)
235
+
236
+ # Test circular dependency between threads
237
+ fail1, fail2 = dispatch_functions(lambda: C1(0, 0, 0), lambda: C2(0, 0))
238
+ expected: list[str] = [
239
+ "0 | Thread-1 | C1(0), next=[0, 0] - start",
240
+ "1 | Thread-2 | C2(0), next=[0] - start",
241
+ "2 | Thread-1 | C1(0), next=[0, 0] - requesting C2(0)", # Blocked by Thread-2
242
+ "3 | Thread-2 | C2(0), next=[0] - requesting C1(0)", # C2(0):T2 -> C1(0):T1 -> C2(0):T2, err
243
+ "3 | Thread-2 | C2(0), next=[0] - err: C1(0)", # T2 dies, releases C2(0)
244
+ "3 | Thread-1 | C2(0), next=[0] - start", # C1(0):T1 -> C2(0):T2 , ok
245
+ "5 | Thread-1 | C2(0), next=[0] - requesting C1(0)", # C1(0):T1 -> C2(0):T2 -> C1(0):T1, err
246
+ "5 | Thread-1 | C2(0), next=[0] - err: C1(0)", # T1 dies, releases C1(0)
247
+ "5 | Thread-1 | C1(0), next=[0, 0] - err: C2(0)", # release C2(0)
248
+ ]
249
+ self.assertEqual(Action.strs(actions), expected)
250
+ self.assertIsInstance(fail1, CircularConstructionError)
251
+ self.assertIsInstance(fail2, CircularConstructionError)
252
+ self.assertIsNot(fail1, fail2)
253
+
254
+ # Test simultaneous construction
255
+ actions.clear()
256
+ res = dispatch_functions(*[lambda i2=i: (C1, C2)[i2 % 2](i2 * 10, i2 * 10 + 1) for i in range(1, 4)])
257
+ expected = [
258
+ "0 | Thread-1 | C2(10), next=[11] - start",
259
+ "1 | Thread-2 | C1(20), next=[21] - start",
260
+ "1 | Thread-3 | C2(30), next=[31] - start",
261
+ "2 | Thread-1 | C2(10), next=[11] - requesting C1(11)",
262
+ "2 | Thread-1 | C1(11), next=[] - start",
263
+ "3 | Thread-2 | C1(20), next=[21] - requesting C2(21)",
264
+ "3 | Thread-2 | C2(21), next=[] - start",
265
+ "3 | Thread-3 | C2(30), next=[31] - requesting C1(31)",
266
+ "3 | Thread-3 | C1(31), next=[] - start",
267
+ "4 | Thread-1 | C1(11), next=[] - requesting None",
268
+ "4 | Thread-1 | C1(11), next=[] - done",
269
+ "4 | Thread-1 | C2(10), next=[11] - done",
270
+ "5 | Thread-2 | C2(21), next=[] - requesting None",
271
+ "5 | Thread-2 | C2(21), next=[] - done",
272
+ "5 | Thread-2 | C1(20), next=[21] - done",
273
+ "5 | Thread-3 | C1(31), next=[] - requesting None",
274
+ "5 | Thread-3 | C1(31), next=[] - done",
275
+ "5 | Thread-3 | C2(30), next=[31] - done",
276
+ ]
277
+ self.assertEqual(Action.strs(actions), expected)
278
+ for itr, i in enumerate(res):
279
+ self.assertIsInstance(i, (C2, C1)[itr % 2])
280
+
281
+ # Test dependent construction time
282
+ actions.clear()
283
+ rv1, rv2 = dispatch_functions(lambda: C1(0, 0), lambda: C2(0, 10, 20))
284
+ expected = [
285
+ "0 | Thread-1 | C1(0), next=[0] - start",
286
+ "1 | Thread-2 | C2(0), next=[10, 20] - start",
287
+ "2 | Thread-1 | C1(0), next=[0] - requesting C2(0)", # Wait until C2(0):T2 is one
288
+ "3 | Thread-2 | C2(0), next=[10, 20] - requesting C1(10)",
289
+ "3 | Thread-2 | C1(10), next=[20] - start",
290
+ "5 | Thread-2 | C1(10), next=[20] - requesting C2(20)",
291
+ "5 | Thread-2 | C2(20), next=[] - start",
292
+ "7 | Thread-2 | C2(20), next=[] - requesting None",
293
+ "7 | Thread-2 | C2(20), next=[] - done", # Release C2(0)
294
+ "7 | Thread-2 | C1(10), next=[20] - done",
295
+ "7 | Thread-2 | C2(0), next=[10, 20] - done",
296
+ "7 | Thread-1 | C1(0), next=[0] - done",
297
+ ]
298
+ self.assertEqual(Action.strs(actions), expected)
299
+ self.assertIs(rv1, C1(0))
300
+ self.assertIs(rv2, C2(0))
301
+
302
+
303
+ if __name__ == "__main__":
304
+ unittest.main()
@@ -1,17 +1,22 @@
1
1
  # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring,unused-variable
2
2
  from unittest.mock import MagicMock, patch
3
+ from typing import Any
3
4
  import unittest
4
5
 
5
6
  from zstdlib.prompt import prompt_until, prompt_for, yn_prompt
6
7
 
7
8
 
8
- mock_input = lambda *x: patch("builtins.input", side_effect=x)
9
- mock_print = lambda: patch("builtins.print")
9
+ def mock_input(*x: str | type[BaseException]) -> Any:
10
+ return patch("builtins.input", side_effect=x)
11
+
12
+
13
+ def mock_print() -> Any:
14
+ return patch("builtins.print")
10
15
 
11
16
 
12
17
  def want_have(mock_p: MagicMock, msg: str, n: int) -> tuple[list[str], list[str]]:
13
18
  if any(len(i.args) != 1 or i.kwargs for i in mock_p.call_args_list):
14
- return False
19
+ raise ValueError("Unexpected print output")
15
20
  return [i.args[0] for i in mock_p.call_args_list], [msg] * n
16
21
 
17
22
 
@@ -53,7 +58,7 @@ class TestPromptUntil(unittest.TestCase):
53
58
 
54
59
 
55
60
  class TestPromptFor(unittest.TestCase):
56
- out = "Type continue "
61
+ out = "Continue? [continue] "
57
62
 
58
63
  def test_basic(self) -> None:
59
64
  with mock_print() as stdout, mock_input("test", "test", "cOntinue") as stdout:
@@ -69,8 +74,9 @@ class TestPromptFor(unittest.TestCase):
69
74
  self.assertFalse(prompt_for(eof=True))
70
75
  self.assertEqual(*want_have(stdout, self.out, 2))
71
76
 
77
+
72
78
  class TestYNPrompt(unittest.TestCase):
73
- out = "Yes or no? [yn] "
79
+ out = "Continue? [yn] "
74
80
 
75
81
  def test_basic(self) -> None:
76
82
  with mock_print() as stdout, mock_input("test", "yes", "y") as stdout:
@@ -80,13 +86,33 @@ class TestYNPrompt(unittest.TestCase):
80
86
  self.assertIs(yn_prompt(), False)
81
87
  self.assertEqual(*want_have(stdout, self.out, 3))
82
88
 
83
- def test_yes_no(self) -> None:
84
- out = "Yes or no? [yes/no] "
89
+ def test_not_short(self) -> None:
90
+ out = "Continue? [yes/no] "
85
91
  with mock_print() as stdout, mock_input("test", "y", "yes") as stdout:
86
- self.assertTrue(yn_prompt(yes_no=True))
92
+ self.assertTrue(yn_prompt(short=False))
87
93
  self.assertEqual(*want_have(stdout, out, 3))
88
94
  with mock_print() as stdout, mock_input("test", "n", "no") as stdout:
89
- self.assertFalse(yn_prompt(yes_no=True))
95
+ self.assertFalse(yn_prompt(short=False))
96
+ self.assertEqual(*want_have(stdout, out, 3))
97
+
98
+ def test_empty(self) -> None:
99
+ with mock_print() as stdout, mock_input("test", "") as stdout:
100
+ with self.assertRaises(StopIteration):
101
+ yn_prompt()
102
+ self.assertEqual(*want_have(stdout, self.out, 3))
103
+ with mock_print() as stdout, mock_input("test", "") as stdout:
104
+ self.assertFalse(yn_prompt(empty_ok=True))
105
+ self.assertEqual(*want_have(stdout, self.out, 2))
106
+
107
+ def test_empty_not_short(self) -> None:
108
+ out = "Continue? [yes/no] "
109
+ with mock_print() as stdout, mock_input("test", "") as stdout:
110
+ with self.assertRaises(StopIteration):
111
+ yn_prompt(short=False)
112
+ self.assertEqual(*want_have(stdout, out, 3))
113
+ with mock_print() as stdout, mock_input("test", "") as stdout:
114
+ with self.assertRaises(StopIteration):
115
+ yn_prompt(short=False, empty_ok=True)
90
116
  self.assertEqual(*want_have(stdout, out, 3))
91
117
 
92
118
  def test_eof(self) -> None:
@@ -63,15 +63,18 @@ class TestSingleton(unittest.TestCase):
63
63
  results = []
64
64
 
65
65
  # Helper functions that can help define thread tests
66
- timestamp = lambda: (datetime.now() - start[0]).total_seconds()
66
+ def timestamp() -> float:
67
+ return (datetime.now() - start[0]).total_seconds()
67
68
 
68
69
  def mk_cls(cls: type, name: str) -> None:
69
- fmt = lambda x: f"{timestamp():.1f}: {name} {x} {cls.__name__}()"
70
+ def fmt(x: str) -> str:
71
+ return f"{timestamp():.1f}: {name} {x} {cls.__name__}()"
72
+
70
73
  events.append(fmt("->"))
71
74
  results.append(cls())
72
75
  events.append(fmt("<-"))
73
76
 
74
- def simple(name: str, cls: type, delay: float) -> Callable:
77
+ def simple(name: str, cls: type, delay: float) -> Callable[[], None]:
75
78
  def _t() -> None:
76
79
  with lock: # Ensure all threads can start simultaneously
77
80
  pass
@@ -81,7 +84,7 @@ class TestSingleton(unittest.TestCase):
81
84
  return _t
82
85
 
83
86
  # Run all functions
84
- def run_all(*funcs: Callable) -> None:
87
+ def run_all(*funcs: Callable[[], None]) -> None:
85
88
  ts = [Thread(target=i) for i in funcs]
86
89
  events.clear()
87
90
  results.clear()
@@ -1,7 +1,8 @@
1
- __version__ = "0.10.6"
1
+ __version__ = "0.10.8"
2
2
 
3
+ from .keyed_instance import CircularConstructionError, KeyedInstance
4
+ from .prompt import prompt_until, prompt_for, yn_prompt
3
5
  from .exc_capture import ExcCapture, ExcDelay
4
- from .prompt import prompt_for, yn_prompt
5
6
  from .hybridmethod import hybridmethod
6
7
  from .not_set import NotSetType, NotSet
7
8
  from .frozen import Freezable, frozen
@@ -11,10 +12,12 @@ from .enum import Enum, auto
11
12
  from . import macos, lazy, log, io
12
13
 
13
14
  __all__ = (
15
+ "CircularConstructionError",
14
16
  "Enum",
15
17
  "ExcCapture",
16
18
  "ExcDelay",
17
19
  "Freezable",
20
+ "KeyedInstance",
18
21
  "NotSet",
19
22
  "NotSetType",
20
23
  "Singleton",
@@ -26,6 +29,7 @@ __all__ = (
26
29
  "log",
27
30
  "macos",
28
31
  "prompt_for",
32
+ "prompt_until",
29
33
  "signal_cm",
30
34
  "yn_prompt",
31
35
  )