python-ulid 4.0.1__tar.gz → 4.2.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.
Files changed (37) hide show
  1. {python_ulid-4.0.1 → python_ulid-4.2.0}/.github/workflows/lint-and-test.yml +4 -2
  2. {python_ulid-4.0.1 → python_ulid-4.2.0}/.gitignore +2 -0
  3. {python_ulid-4.0.1 → python_ulid-4.2.0}/.pre-commit-config.yaml +1 -1
  4. {python_ulid-4.0.1 → python_ulid-4.2.0}/.readthedocs.yml +2 -0
  5. {python_ulid-4.0.1 → python_ulid-4.2.0}/CHANGELOG.rst +57 -0
  6. {python_ulid-4.0.1 → python_ulid-4.2.0}/CONTRIBUTING.md +12 -3
  7. {python_ulid-4.0.1 → python_ulid-4.2.0}/PKG-INFO +62 -5
  8. {python_ulid-4.0.1 → python_ulid-4.2.0}/README.rst +57 -2
  9. {python_ulid-4.0.1 → python_ulid-4.2.0}/docs/source/api.rst +10 -0
  10. {python_ulid-4.0.1 → python_ulid-4.2.0}/docs/source/conf.py +6 -3
  11. {python_ulid-4.0.1 → python_ulid-4.2.0}/docs/source/index.rst +4 -0
  12. {python_ulid-4.0.1 → python_ulid-4.2.0}/pyproject.toml +27 -18
  13. python_ulid-4.2.0/tests/test_cli.py +174 -0
  14. python_ulid-4.2.0/tests/test_sqlalchemy.py +235 -0
  15. {python_ulid-4.0.1 → python_ulid-4.2.0}/tests/test_ulid.py +172 -3
  16. {python_ulid-4.0.1 → python_ulid-4.2.0}/ulid/__init__.py +45 -24
  17. {python_ulid-4.0.1 → python_ulid-4.2.0}/ulid/__main__.py +15 -6
  18. python_ulid-4.2.0/ulid/_version.py +24 -0
  19. {python_ulid-4.0.1 → python_ulid-4.2.0}/ulid/base32.py +3 -1
  20. python_ulid-4.2.0/ulid/sqlalchemy.py +132 -0
  21. python_ulid-4.2.0/uv.lock +1212 -0
  22. python_ulid-4.0.1/tests/test_cli.py +0 -81
  23. python_ulid-4.0.1/uv.lock +0 -1038
  24. {python_ulid-4.0.1 → python_ulid-4.2.0}/.envrc +0 -0
  25. {python_ulid-4.0.1 → python_ulid-4.2.0}/.github/workflows/publish.yml +0 -0
  26. {python_ulid-4.0.1 → python_ulid-4.2.0}/.ruff_defaults.toml +0 -0
  27. {python_ulid-4.0.1 → python_ulid-4.2.0}/AGENTS.md +0 -0
  28. {python_ulid-4.0.1 → python_ulid-4.2.0}/CONTEXT.md +0 -0
  29. {python_ulid-4.0.1 → python_ulid-4.2.0}/LICENSE +0 -0
  30. {python_ulid-4.0.1 → python_ulid-4.2.0}/docs/Makefile +0 -0
  31. {python_ulid-4.0.1 → python_ulid-4.2.0}/docs/requirements.txt +0 -0
  32. {python_ulid-4.0.1 → python_ulid-4.2.0}/docs/source/changelog.rst +0 -0
  33. {python_ulid-4.0.1 → python_ulid-4.2.0}/logo.png +0 -0
  34. {python_ulid-4.0.1 → python_ulid-4.2.0}/tests/__init__.py +0 -0
  35. {python_ulid-4.0.1 → python_ulid-4.2.0}/tests/test_base32.py +0 -0
  36. {python_ulid-4.0.1 → python_ulid-4.2.0}/ulid/constants.py +0 -0
  37. {python_ulid-4.0.1 → python_ulid-4.2.0}/ulid/py.typed +0 -0
@@ -47,7 +47,7 @@ jobs:
47
47
  name: Run tests
48
48
  strategy:
49
49
  matrix:
50
- python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
50
+ python-version: ["3.11", "3.12", "3.13", "3.14", "3.15"]
51
51
  steps:
52
52
  - uses: actions/checkout@v7
53
53
  - name: Install uv
@@ -57,6 +57,8 @@ jobs:
57
57
 
58
58
  - name: Test
59
59
  run: uv run poe test
60
+ env:
61
+ COVERAGE_FILE: .coverage.${{ matrix.python-version }}
60
62
 
61
63
  - name: Upload coverage data
62
64
  uses: actions/upload-artifact@v7
@@ -98,4 +100,4 @@ jobs:
98
100
  runs-on: ubuntu-latest
99
101
  steps:
100
102
  - uses: actions/checkout@v7
101
- - uses: hynek/build-and-inspect-python-package@v2
103
+ - uses: hynek/build-and-inspect-python-package@67230f7b8410ae0052b39c1efc89d89fff43ff10 # v3.0.2
@@ -15,3 +15,5 @@ __pycache__
15
15
  /dist/
16
16
  /build/
17
17
  /docs/build
18
+
19
+ /ulid/_version.py
@@ -1,6 +1,6 @@
1
1
  repos:
2
2
  - repo: https://github.com/astral-sh/ruff-pre-commit
3
- rev: v0.15.4
3
+ rev: v0.17.5
4
4
  hooks:
5
5
  - id: ruff-check
6
6
  - id: ruff-format
@@ -13,3 +13,5 @@ python:
13
13
  - requirements: docs/requirements.txt
14
14
  - method: pip
15
15
  path: .
16
+ extra_requirements:
17
+ - sqlalchemy
@@ -5,6 +5,60 @@ Changelog
5
5
 
6
6
  Versions follow `Semantic Versioning <http://www.semver.org>`_
7
7
 
8
+ `Unreleased`_
9
+ -------------
10
+
11
+ `4.2.0`_ - 2026-11-17
12
+ ---------------------
13
+ Added
14
+ ~~~~~
15
+ * Added support for Python 3.15.
16
+ * :class:`~ulid.sqlalchemy.ULIDType`, a SQLAlchemy column type for :class:`.ULID` values that can
17
+ also be used with SQLModel. It stores values as UUID by default, or as binary or string. Install
18
+ it with the new ``sqlalchemy`` extra (``pip install python-ulid[sqlalchemy]``).
19
+
20
+ Fixed
21
+ ~~~~~
22
+ * The :class:`.ULID` constructor now accepts :class:`bytes` and bytes-like values (``bytearray``
23
+ and ``memoryview``), which are stored as immutable :class:`bytes`. A 16-character string or an
24
+ integer was previously accepted and produced an object whose ``str()`` failed or that was
25
+ unhashable, so other types now raise :exc:`TypeError`
26
+ `@KuljeetSinghXDA <https://github.com/KuljeetSinghXDA>`_.
27
+ * Pydantic validation of unsupported values such as ``dict``, ``float`` or an out-of-range
28
+ ``int`` now raises ``pydantic.ValidationError`` instead of leaking :exc:`TypeError` or
29
+ :exc:`OverflowError` `@KuljeetSinghXDA <https://github.com/KuljeetSinghXDA>`_.
30
+ * :meth:`.ULID.parse` now treats any integer in the unsigned 128-bit range as a full ULID
31
+ integer, instead of guessing from the number of decimal digits. Previously only integers with
32
+ exactly 37 digits were accepted, so ``ULID.parse(int(ulid))`` failed for most ULIDs
33
+ `@KuljeetSinghXDA <https://github.com/KuljeetSinghXDA>`_.
34
+ * :meth:`.ULID.from_datetime` and :meth:`.ULID.from_timestamp` no longer land one millisecond early
35
+ when a value on an exact millisecond multiplies to just below that integer as a float
36
+ `@arieleven <https://github.com/arieleven>`_.
37
+ * :meth:`.ULID.from_datetime` and :meth:`.ULID.from_timestamp` raise a :exc:`ValueError` for values
38
+ before the Unix epoch instead of a bare :exc:`OverflowError`.
39
+ * :meth:`.ULID.from_int` raises a :exc:`ValueError` for integers outside the unsigned 128-bit
40
+ range instead of a bare :exc:`OverflowError`.
41
+ * The ``ulid`` command line tool reports invalid input as a short error message with exit status
42
+ 2 instead of a Python traceback.
43
+ * ``import ulid`` no longer fails when the package metadata is missing, e.g. in applications frozen
44
+ with cx_Freeze or PyInstaller. The version is now written into the package at build time.
45
+
46
+ `4.1.0`_ - 2026-10-27
47
+ ---------------------
48
+ Changed
49
+ ~~~~~~~
50
+ * Dropped support for Python 3.10.
51
+
52
+ Fixed
53
+ ~~~~~
54
+ * The ``typing-extensions`` dependency is now also installed on Python 3.11, where it is required
55
+ for ``typing_extensions.override``.
56
+ * Print generated and converted values when using ``python -m ulid``, matching the
57
+ ``ulid`` console command `@tongwentao <https://github.com/tongwentao>`_.
58
+ * :meth:`.ULID.from_str` accepts lower case strings again, as the ULID spec defines the string
59
+ representation as case insensitive. Lower case input has been rejected since 2.6.0
60
+ `@reyhaan07 <https://github.com/reyhaan07>`_.
61
+
8
62
  `4.0.1`_ - 2026-07-20
9
63
  ---------------------
10
64
  Changed
@@ -265,6 +319,9 @@ Changed
265
319
  * The package now has no external dependencies.
266
320
  * The test-coverage has been raised to 100%.
267
321
 
322
+ .. _Unreleased: https://github.com/mdomke/python-ulid/compare/4.2.0...HEAD
323
+ .. _4.2.0: https://github.com/mdomke/python-ulid/compare/4.1.0...4.2.0
324
+ .. _4.1.0: https://github.com/mdomke/python-ulid/compare/4.0.1...4.1.0
268
325
  .. _4.0.1: https://github.com/mdomke/python-ulid/compare/4.0.0...4.0.1
269
326
  .. _4.0.0: https://github.com/mdomke/python-ulid/compare/3.2.1...4.0.0
270
327
  .. _3.2.1: https://github.com/mdomke/python-ulid/compare/3.2.0...3.2.1
@@ -33,7 +33,7 @@ If you have [Flox](https://flox.dev/) installed, setting up your environment is
33
33
  If Flox is not an option, you can set up your environment manually. We use [uv](https://github.com/astral-sh/uv) for fast, robust package and dependency management.
34
34
 
35
35
  1. **Prerequisites**:
36
- - **Python**: `>= 3.10`
36
+ - **Python**: `>= 3.11`
37
37
  - **uv**: Install via `curl -LsSf https://astral.sh/uv/install.sh | sh` (or your preferred package manager)
38
38
 
39
39
  2. **Fork and clone** the repository:
@@ -99,6 +99,16 @@ If you want to run all checks against your staged or unstaged files manually:
99
99
  uv run prek run --all-files
100
100
  ```
101
101
 
102
+ ### Troubleshooting: `cannot import name '_version' from 'ulid'`
103
+
104
+ The package version is written to `ulid/_version.py` when the package is built or installed, and the
105
+ file is not tracked by Git. If it is missing (e.g. after `git clean -X`), `import ulid` fails. Reinstall
106
+ the package into your environment to regenerate it:
107
+
108
+ ```bash
109
+ uv sync --reinstall-package python-ulid
110
+ ```
111
+
102
112
  ---
103
113
 
104
114
  ## 🎨 Coding Standards
@@ -110,8 +120,7 @@ To maintain a clean, readable, and highly maintainable codebase, we enforce the
110
120
  - **Static Analysis**: Our configuration has `disallow_untyped_defs = true` set for Mypy and uses strict `pyrefly` checks. Untyped or partially-typed code will fail the lint pipelines.
111
121
  - **Example**:
112
122
  ```python
113
- def generate_ulid(timestamp: float | None = None) -> ULID:
114
- ...
123
+ def generate_ulid(timestamp: float | None = None) -> ULID: ...
115
124
  ```
116
125
 
117
126
  ### 2. Ruff Formatting & Linting
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: python-ulid
3
- Version: 4.0.1
3
+ Version: 4.2.0
4
4
  Summary: Universally unique lexicographically sortable identifier
5
5
  Project-URL: Homepage, https://github.com/mdomke/python-ulid
6
6
  Project-URL: Documentation, https://python-ulid.readthedocs.io
@@ -18,16 +18,18 @@ Classifier: License :: OSI Approved :: MIT License
18
18
  Classifier: Operating System :: MacOS :: MacOS X
19
19
  Classifier: Operating System :: POSIX :: Linux
20
20
  Classifier: Programming Language :: Python
21
- Classifier: Programming Language :: Python :: 3.10
22
21
  Classifier: Programming Language :: Python :: 3.11
23
22
  Classifier: Programming Language :: Python :: 3.12
24
23
  Classifier: Programming Language :: Python :: 3.13
25
24
  Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Programming Language :: Python :: 3.15
26
26
  Classifier: Topic :: Software Development :: Libraries
27
- Requires-Python: >=3.10
28
- Requires-Dist: typing-extensions; python_version < '3.11'
27
+ Requires-Python: >=3.11
28
+ Requires-Dist: typing-extensions; python_version < '3.12'
29
29
  Provides-Extra: pydantic
30
30
  Requires-Dist: pydantic>=2.0; extra == 'pydantic'
31
+ Provides-Extra: sqlalchemy
32
+ Requires-Dist: sqlalchemy>=2.0; extra == 'sqlalchemy'
31
33
  Description-Content-Type: text/x-rst
32
34
 
33
35
 
@@ -75,6 +77,12 @@ to include Pydantic support install the optional dependency like so
75
77
 
76
78
  $ pip install python-ulid[pydantic]
77
79
 
80
+ and for the SQLAlchemy column type
81
+
82
+ .. code-block:: bash
83
+
84
+ $ pip install python-ulid[sqlalchemy]
85
+
78
86
  .. installation-end
79
87
 
80
88
  .. usage-begin
@@ -150,6 +158,55 @@ The ``ULID`` class can be directly used for the popular data validation library
150
158
 
151
159
  .. pydantic-end
152
160
 
161
+ .. sqlalchemy-begin
162
+
163
+ SQLAlchemy and SQLModel integration
164
+ -----------------------------------
165
+
166
+ The ``ULIDType`` column type stores ``ULID`` values with
167
+ `SQLAlchemy <https://www.sqlalchemy.org/>`_ (version 2.0 or newer). Values are bound from
168
+ ``ULID``, ``UUID``, ``bytes``, ``int`` or any string representation and always loaded as ``ULID``.
169
+ Pass ``default=ULID`` to generate a new identifier for every inserted row
170
+
171
+ .. code-block:: python
172
+
173
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
174
+ from ulid import ULID
175
+ from ulid.sqlalchemy import ULIDType
176
+
177
+
178
+ class Base(DeclarativeBase):
179
+ pass
180
+
181
+
182
+ class Item(Base):
183
+ __tablename__ = "items"
184
+
185
+ id: Mapped[ULID] = mapped_column(ULIDType(), primary_key=True, default=ULID)
186
+ name: Mapped[str]
187
+
188
+ By default the value is stored as a UUID: a native ``UUID`` column where the database has one
189
+ (e.g. PostgreSQL) and ``CHAR(32)`` otherwise. Use ``ULIDType(storage="binary")`` for a
190
+ ``BINARY(16)`` column or ``ULIDType(storage="string")`` for the 26 character ULID string in a
191
+ ``CHAR(26)`` column. All storages keep the database sort order identical to the ULID order, except
192
+ the native ``UNIQUEIDENTIFIER`` type on SQL Server.
193
+
194
+ `SQLModel <https://sqlmodel.tiangolo.com/>`_ models can use ``ULID`` as a field type directly,
195
+ since it is a Pydantic type. Only the column type has to be passed explicitly
196
+
197
+ .. code-block:: python
198
+
199
+ from sqlmodel import Field, SQLModel
200
+ from ulid import ULID
201
+ from ulid.sqlalchemy import ULIDType
202
+
203
+
204
+ class Hero(SQLModel, table=True):
205
+ id: ULID = Field(default_factory=ULID, primary_key=True, sa_type=ULIDType)
206
+ name: str
207
+
208
+ .. sqlalchemy-end
209
+
153
210
  .. monotonic-begin
154
211
 
155
212
  Monotonic Support
@@ -24,8 +24,8 @@
24
24
  <a href="https://python-ulid.readthedocs.io">
25
25
  <img src="https://readthedocs.org/projects/python-ulid/badge/?version=latest&style=flat-square" />
26
26
  </a>
27
- <a href="https://black.readthedocs.io/en/stable/index.html">
28
- <img src="https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square" />
27
+ <a href="https://github.com/astral-sh/ruff">
28
+ <img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&style=flat-square" />
29
29
  </a>
30
30
  </p>
31
31
 
@@ -76,6 +76,12 @@ to include Pydantic support install the optional dependency like so
76
76
 
77
77
  $ pip install python-ulid[pydantic]
78
78
 
79
+ and for the SQLAlchemy column type
80
+
81
+ .. code-block:: bash
82
+
83
+ $ pip install python-ulid[sqlalchemy]
84
+
79
85
  .. installation-end
80
86
 
81
87
  .. usage-begin
@@ -151,6 +157,55 @@ The ``ULID`` class can be directly used for the popular data validation library
151
157
 
152
158
  .. pydantic-end
153
159
 
160
+ .. sqlalchemy-begin
161
+
162
+ SQLAlchemy and SQLModel integration
163
+ -----------------------------------
164
+
165
+ The ``ULIDType`` column type stores ``ULID`` values with
166
+ `SQLAlchemy <https://www.sqlalchemy.org/>`_ (version 2.0 or newer). Values are bound from
167
+ ``ULID``, ``UUID``, ``bytes``, ``int`` or any string representation and always loaded as ``ULID``.
168
+ Pass ``default=ULID`` to generate a new identifier for every inserted row
169
+
170
+ .. code-block:: python
171
+
172
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
173
+ from ulid import ULID
174
+ from ulid.sqlalchemy import ULIDType
175
+
176
+
177
+ class Base(DeclarativeBase):
178
+ pass
179
+
180
+
181
+ class Item(Base):
182
+ __tablename__ = "items"
183
+
184
+ id: Mapped[ULID] = mapped_column(ULIDType(), primary_key=True, default=ULID)
185
+ name: Mapped[str]
186
+
187
+ By default the value is stored as a UUID: a native ``UUID`` column where the database has one
188
+ (e.g. PostgreSQL) and ``CHAR(32)`` otherwise. Use ``ULIDType(storage="binary")`` for a
189
+ ``BINARY(16)`` column or ``ULIDType(storage="string")`` for the 26 character ULID string in a
190
+ ``CHAR(26)`` column. All storages keep the database sort order identical to the ULID order, except
191
+ the native ``UNIQUEIDENTIFIER`` type on SQL Server.
192
+
193
+ `SQLModel <https://sqlmodel.tiangolo.com/>`_ models can use ``ULID`` as a field type directly,
194
+ since it is a Pydantic type. Only the column type has to be passed explicitly
195
+
196
+ .. code-block:: python
197
+
198
+ from sqlmodel import Field, SQLModel
199
+ from ulid import ULID
200
+ from ulid.sqlalchemy import ULIDType
201
+
202
+
203
+ class Hero(SQLModel, table=True):
204
+ id: ULID = Field(default_factory=ULID, primary_key=True, sa_type=ULIDType)
205
+ name: str
206
+
207
+ .. sqlalchemy-end
208
+
154
209
  .. monotonic-begin
155
210
 
156
211
  Monotonic Support
@@ -50,3 +50,13 @@ satisfying the :class:`MonotonicityPolicy` protocol can be used; stateful polici
50
50
 
51
51
  .. autoclass:: PureRandomPolicy
52
52
  :members:
53
+
54
+
55
+ SQLAlchemy
56
+ ----------
57
+
58
+ .. module:: ulid.sqlalchemy
59
+
60
+ Requires the optional ``sqlalchemy`` dependency (``pip install python-ulid[sqlalchemy]``).
61
+
62
+ .. autoclass:: ULIDType
@@ -1,7 +1,7 @@
1
1
  import os
2
2
  import sys
3
3
  from datetime import datetime
4
- from datetime import timezone
4
+ from datetime import UTC
5
5
 
6
6
 
7
7
  sys.path.insert(0, os.path.abspath("../.."))
@@ -9,7 +9,7 @@ sys.path.insert(0, os.path.abspath("../.."))
9
9
  import ulid
10
10
 
11
11
 
12
- copyright = f"{datetime.now(timezone.utc).year}, Martin Domke"
12
+ copyright = f"{datetime.now(UTC).year}, Martin Domke"
13
13
  author = "Martin Domke"
14
14
  master_doc = "index"
15
15
  source_suffix = {".rst": "restructuredtext", ".md": "restructuredtext"}
@@ -78,4 +78,7 @@ autodoc_member_order = "groupwise"
78
78
  # ----------------------------------------------
79
79
 
80
80
  # Example configuration for intersphinx: refer to the Python standard library.
81
- intersphinx_mapping = {"python": ("https://docs.python.org/3", None)}
81
+ intersphinx_mapping = {
82
+ "python": ("https://docs.python.org/3", None),
83
+ "sqlalchemy": ("https://docs.sqlalchemy.org/en/20/", None),
84
+ }
@@ -20,6 +20,10 @@ Release v\ |release| (:ref:`What's new <changelog>`)
20
20
  :start-after: pydantic-begin
21
21
  :end-before: pydantic-end
22
22
 
23
+ .. include:: ../../README.rst
24
+ :start-after: sqlalchemy-begin
25
+ :end-before: sqlalchemy-end
26
+
23
27
  .. include:: ../../README.rst
24
28
  :start-after: monotonic-begin
25
29
  :end-before: monotonic-end
@@ -7,7 +7,7 @@ name = "python-ulid"
7
7
  description = "Universally unique lexicographically sortable identifier"
8
8
  dynamic = ["version", "readme"]
9
9
  license = "MIT"
10
- requires-python = ">=3.10"
10
+ requires-python = ">=3.11"
11
11
  authors = [
12
12
  { name = "Martin Domke", email = "mail@martindomke.net" },
13
13
  ]
@@ -19,15 +19,15 @@ classifiers = [
19
19
  "Operating System :: POSIX :: Linux",
20
20
  "Operating System :: MacOS :: MacOS X",
21
21
  "Programming Language :: Python",
22
- "Programming Language :: Python :: 3.10",
23
22
  "Programming Language :: Python :: 3.11",
24
23
  "Programming Language :: Python :: 3.12",
25
24
  "Programming Language :: Python :: 3.13",
26
25
  "Programming Language :: Python :: 3.14",
26
+ "Programming Language :: Python :: 3.15",
27
27
  "Topic :: Software Development :: Libraries",
28
28
  ]
29
29
  dependencies = [
30
- "typing-extensions; python_version < '3.11'",
30
+ "typing-extensions; python_version < '3.12'",
31
31
  ]
32
32
 
33
33
  [project.urls]
@@ -42,6 +42,9 @@ Repository = "https://github.com/mdomke/python-ulid"
42
42
  pydantic = [
43
43
  "pydantic>=2.0"
44
44
  ]
45
+ sqlalchemy = [
46
+ "sqlalchemy>=2.0",
47
+ ]
45
48
 
46
49
  [project.scripts]
47
50
  ulid = "ulid.__main__:entrypoint"
@@ -49,6 +52,9 @@ ulid = "ulid.__main__:entrypoint"
49
52
  [tool.hatch.version]
50
53
  source = "vcs"
51
54
 
55
+ [tool.hatch.build.hooks.vcs]
56
+ version-file = "ulid/_version.py"
57
+
52
58
  [tool.hatch.build.targets.wheel]
53
59
  packages = [
54
60
  "ulid",
@@ -60,7 +66,7 @@ exclude = [
60
66
 
61
67
  [tool.ruff]
62
68
  extend = ".ruff_defaults.toml"
63
- target-version = "py310"
69
+ target-version = "py311"
64
70
  line-length = 100
65
71
 
66
72
  [tool.ruff.format]
@@ -112,12 +118,13 @@ preset = "strict"
112
118
  project-excludes = ["docs"]
113
119
 
114
120
  [tool.poe.tasks]
115
- test = "uv run --extra pydantic coverage run -m pytest"
116
- check-code = "ruff check"
117
- check-fmt = "ruff format --check"
118
- check-types = "uv run --extra pydantic pyrefly check"
119
- check-docs = "doc8 docs/source"
120
- fmt = "ruff format"
121
+ test = "uv run --extra pydantic --extra sqlalchemy pytest --cov --cov-report=term-missing"
122
+ check-code = "uv run ruff check"
123
+ check-fmt = "uv run ruff format --check"
124
+ check-types = "uv run --extra pydantic --extra sqlalchemy pyrefly check"
125
+ check-docs = "uv run doc8 docs/source"
126
+ fmt = "uv run ruff format"
127
+ fix = "uv run ruff check --fix"
121
128
  build = "uv build"
122
129
  cov-combine = "coverage combine"
123
130
  cov-xml = "coverage xml"
@@ -146,17 +153,19 @@ max-line-length = 100
146
153
 
147
154
  [dependency-groups]
148
155
  dev = [
149
- "coverage==7.15.*",
150
- "freezegun==1.5.*",
151
- "poethepoet==0.48.*",
152
- "prek==0.4.*",
153
- "pyrefly==1.1.*",
154
- "pytest==9.1.*",
155
- "ruff==0.15.*",
156
+ "coverage",
157
+ "freezegun",
158
+ "poethepoet",
159
+ "prek",
160
+ "pyrefly",
161
+ "pytest",
162
+ "pytest-cov",
163
+ "ruff",
164
+ "sqlmodel",
156
165
  ]
157
166
  doc = [
158
167
  "doc8>=2.0.0",
159
- "sphinx==8.1.*",
168
+ "sphinx<9.0",
160
169
  ]
161
170
 
162
171
  [tool.hatch.metadata.hooks.fancy-pypi-readme]
@@ -0,0 +1,174 @@
1
+ import subprocess
2
+ import sys
3
+
4
+ import pytest
5
+
6
+ import ulid.__main__ as cli
7
+ from ulid import ULID
8
+
9
+
10
+ # Exit status argparse uses for invalid command-line input.
11
+ USAGE_ERROR = 2
12
+
13
+
14
+ @pytest.mark.parametrize(
15
+ "option", ["", "uuid", "uuid4", "uuid7", "hex", "int", "timestamp", "datetime"]
16
+ )
17
+ def test_parse_show(option: str):
18
+ ulid = ULID()
19
+ argv = ["show", f"--{option}", str(ulid)]
20
+ output = cli.main(argv)
21
+ if option == "uuid":
22
+ assert output == str(ulid.to_uuid())
23
+ elif option == "uuid4":
24
+ assert output == str(ulid.to_uuid4())
25
+ elif option == "uuid7":
26
+ assert output == str(ulid.to_uuid7(compliant=True))
27
+ elif option == "hex":
28
+ assert output == ulid.hex
29
+ elif option == "int":
30
+ assert output == str(int(ulid))
31
+ elif option == "timestamp":
32
+ assert output == str(ulid.timestamp)
33
+ elif option == "datetime":
34
+ assert output == ulid.datetime.isoformat()
35
+ else:
36
+ assert str(ulid) in output
37
+ assert ulid.hex in output
38
+ assert str(int(ulid)) in output
39
+ assert str(ulid.timestamp) in output
40
+ assert ulid.datetime.isoformat() in output
41
+
42
+
43
+ @pytest.mark.parametrize(
44
+ "option",
45
+ [
46
+ "",
47
+ "from-uuid",
48
+ "from-str",
49
+ "from-hex",
50
+ "from-int",
51
+ "from-timestamp",
52
+ "from-datetime",
53
+ ],
54
+ )
55
+ def test_build(option: str):
56
+ ulid = ULID()
57
+ value: str = ""
58
+ includes_randomness = True
59
+ includes_timestamp = True
60
+ if option.endswith("uuid"):
61
+ value = str(ulid.to_uuid())
62
+ elif option.endswith("str"):
63
+ value = str(ulid)
64
+ elif option.endswith("hex"):
65
+ value = ulid.hex
66
+ elif option.endswith("int"):
67
+ value = str(int(ulid))
68
+ elif option.endswith("timestamp"):
69
+ value = str(ulid.timestamp)
70
+ includes_randomness = False
71
+ elif option.endswith("datetime"):
72
+ value = ulid.datetime.isoformat()
73
+ includes_randomness = False
74
+ else:
75
+ includes_timestamp = False
76
+ includes_randomness = False
77
+
78
+ argv = ["build"]
79
+ if option:
80
+ argv += [f"--{option}", value]
81
+ output = cli.main(argv)
82
+
83
+ if includes_randomness and includes_timestamp:
84
+ assert output == str(ulid)
85
+
86
+ ulid_out = ULID.from_str(output)
87
+ if includes_timestamp:
88
+ assert ulid_out.datetime == ulid.datetime
89
+
90
+
91
+ @pytest.mark.parametrize(
92
+ ("args", "stdin", "expected"),
93
+ [
94
+ (["build", "--from-int", "0"], None, "00000000000000000000000000\n"),
95
+ (["build", "--from-int", "-"], "0\n", "00000000000000000000000000\n"),
96
+ (["show", "--int", "00000000000000000000000000"], None, "0\n"),
97
+ (["show", "--int", "-"], "00000000000000000000000000\n", "0\n"),
98
+ ],
99
+ )
100
+ def test_module_outputs_result(args: list[str], stdin: str | None, expected: str) -> None:
101
+ result = subprocess.run(
102
+ [sys.executable, "-m", "ulid", *args],
103
+ input=stdin,
104
+ capture_output=True,
105
+ text=True,
106
+ check=True,
107
+ timeout=10,
108
+ )
109
+ assert result.stdout == expected
110
+ assert result.stderr == ""
111
+
112
+
113
+ @pytest.mark.parametrize(
114
+ ("args", "message"),
115
+ [
116
+ (["build", "--from-int", "abc"], "invalid literal for int()"),
117
+ (["build", "--from-int=-1"], "Value is outside the 128-bit range of a ULID"),
118
+ (["build", "--from-str", "not-a-ulid"], "ULID has to be exactly 26 characters long."),
119
+ (["build", "--from-hex", "zz"], "non-hexadecimal number"),
120
+ (["build", "--from-timestamp=-1"], "Value is below minimum possible timestamp"),
121
+ (["build", "--from-datetime", "yesterday"], "Invalid isoformat string"),
122
+ (["build", "--from-uuid", "not-a-uuid"], "badly formed hexadecimal UUID string"),
123
+ (["show", "not-a-ulid"], "ULID has to be exactly 26 characters long."),
124
+ ],
125
+ )
126
+ def test_invalid_input_reports_error_without_traceback(
127
+ capsys: pytest.CaptureFixture[str], args: list[str], message: str
128
+ ) -> None:
129
+ with pytest.raises(SystemExit) as exc_info:
130
+ cli.main(args, prog="ulid")
131
+ assert exc_info.value.code == USAGE_ERROR
132
+ captured = capsys.readouterr()
133
+ assert captured.out == ""
134
+ assert captured.err.startswith("ulid: error: ")
135
+ assert message in captured.err
136
+ assert "Traceback" not in captured.err
137
+
138
+
139
+ def test_module_invalid_input_exits_with_error() -> None:
140
+ result = subprocess.run(
141
+ [sys.executable, "-m", "ulid", "show", "not-a-ulid"],
142
+ capture_output=True,
143
+ text=True,
144
+ check=False,
145
+ timeout=10,
146
+ )
147
+ assert result.returncode == USAGE_ERROR
148
+ assert result.stdout == ""
149
+ assert result.stderr.startswith("python -m ulid: error: ")
150
+ assert "Traceback" not in result.stderr
151
+
152
+
153
+ @pytest.mark.parametrize("args", [[], ["--help"]])
154
+ def test_module_help(args: list[str]) -> None:
155
+ result = subprocess.run(
156
+ [sys.executable, "-m", "ulid", *args],
157
+ capture_output=True,
158
+ text=True,
159
+ check=True,
160
+ timeout=10,
161
+ )
162
+ assert result.stdout.startswith("usage: python -m ulid")
163
+ assert not result.stdout.endswith("None\n")
164
+ assert result.stderr == ""
165
+
166
+
167
+ def test_console_entrypoint(
168
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
169
+ ) -> None:
170
+ monkeypatch.setattr(sys, "argv", ["ulid", "build", "--from-int", "0"])
171
+ cli.entrypoint()
172
+ captured = capsys.readouterr()
173
+ assert captured.out == "00000000000000000000000000\n"
174
+ assert captured.err == ""