Pytest fixture to generate unique values.
You will need the following prerequisites to use pytest-unique:
- Python 3.9, 3.10, 3.11, 3.12, 3.13
To install pytest-unique:
$ pip install pytest-unique
You can use the unique
fixture by passing it as a test argument:
def test_integer(unique):
assert unique("integer") > 0
Here are some of the plugins available by default:
bytes
with invalid UTF8 characters.digits
with just numbers.email
with a unique username.float
with a whole part and a decimal part.integer
withbase
andmod
arguments.password
withlowercase
,uppercase
,digits
andpunctuation
arguments.text
withprefix
,suffix
andseparator
arguments.
The unique
fixture can be extended with custom plugins:
from datetime import datetime, timezone
def unique_datetime(unique)
"""Return a datetime unique to this factory instance."""
timestamp = unique("integer")
return datetime.fromtimestamp(timestamp, timezone.utc)
Then, add it to the pyproject.toml
file of your project:
[tool.poetry.plugins."pytest_unique"]
datetime = "your_project.unique:unique_datetime"
You can then use the plugin like all other plugins:
from datetime import datetime
def test_datetime(unique):
assert isinstance(unique("datetime"), datetime)
The unique
fixture cannot be used as parameters in parameterized tests
by virtue of being a fixture. The reason it is a fixture rather than a
function is that unique values are generated from an instance of a counter
that returns sequential values. This makes it possible to see the order
in which values were generated which can be useful when troubleshooting.