coincidence
Helper functions for pytest.
Docs |
|
---|---|
Tests |
|
PyPI |
|
Anaconda |
|
Activity |
|
QA |
|
Other |
Installation
python3 -m pip install coincidence --user
First add the required channels
conda config --add channels https://conda.anaconda.org/conda-forge
conda config --add channels https://conda.anaconda.org/domdfcoding
Then install
conda install coincidence
python3 -m pip install git+https://github.com/python-coincidence/coincidence@master --user
API Reference
coincidence
Helper functions for pytest.
Data:
|
Functions:
|
Prints the start time of the pytest session. |
-
PEP_563
= False Type:
bool
True
if the current Python version implements PEP 563 – Postponed Evaluation of Annotations.Note
This is currently set to
False
until the future of typing PEPs has been determined. No released versions of Python currently have PEP 563 enabled by default.Changed in version 0.6.0: Temporarily set to
False
regardless of version.
coincidence.fixtures
Pytest fixtures.
To enable the fixtures add the following to conftest.py
in your test directory:
pytest_plugins = ("coincidence", )
See the pytest documentation for more information.
Functions:
|
Pytest fixture to pretend the current datetime is 2:20 AM on 13th October 2020. |
|
Parametrized pytest fixture which returns the current filesystem path separator and skips the test for the other. |
|
Pytest fixture which returns a temporary directory in the form of a |
-
fixture
fixed_datetime
[source] Scope: function
Pytest fixture to pretend the current datetime is 2:20 AM on 13th October 2020.
See also
The
with_fixed_datetime()
contextmanager.Attention
The monkeypatching only works when datetime is used and imported like:
import datetime print(datetime.datetime.now())
Using
from datetime import datetime
won’t work.- Return type
-
fixture
path_separator
[source] Scope: function
Parametrized pytest fixture which returns the current filesystem path separator and skips the test for the other.
This is useful when the test output differs on platforms with
\
as the path separator, such as windows.New in version 0.4.0.
- Return type
-
fixture
tmp_pathplus
[source] Scope: function
Pytest fixture which returns a temporary directory in the form of a
PathPlus
object.The directory is unique to each test function invocation, created as a sub directory of the base temporary directory.
Use it as follows:
pytest_plugins = ("coincidence", ) def test_something(tmp_pathplus: PathPlus): assert True
- Return type
coincidence.params
pytest.mark.parametrize decorators.
Functions:
|
Returns a pytest.mark.parametrize decorator which provides a list of numbers between |
|
Returns a pytest.mark.parametrize decorator which provides permutations of whitespace. |
|
Returns a pytest.mark.parametrize decorator which provides a list of strings, integers and booleans, and the boolean representations of them. |
|
Specify a parameter in pytest.mark.parametrize calls or parametrized fixtures. |
|
Return a list of parametrized version numbers. |
-
count
(stop, start=0, step=1)[source] Returns a pytest.mark.parametrize decorator which provides a list of numbers between
start
andstop
with an interval ofstep
.The single parametrized argument is
count
.
-
whitespace_perms
(ratio=0.5)[source] Returns a pytest.mark.parametrize decorator which provides permutations of whitespace.
For this function whitespace is only
␣\n\t\r
.Not all permutations are returned, as there are a lot of them; instead a random selection of the permutations is returned. By default ½ of the permutations are returned, but this can be configured using the
ratio
argument.The single parametrized argument is
char
.- Parameters
ratio (
float
) – The ratio of the number of permutations to select to the total number of permutations. Default0.5
.- Return type
MarkDecorator
-
testing_boolean_values
(extra_truthy=(), extra_falsy=(), ratio=1)[source] Returns a pytest.mark.parametrize decorator which provides a list of strings, integers and booleans, and the boolean representations of them.
The parametrized arguments are
boolean_string
for the input value, andexpected_boolean
for the expected output.Optionally, a random selection of the values can be returned using the
ratio
argument.
-
param
(*values, marks=(), id=None, idx=None, key=None)[source] Specify a parameter in pytest.mark.parametrize calls or parametrized fixtures.
Examples:
@pytest.mark.parametrize("test_input, expected", [ ("3+5", 8), param("6*9", 42, marks=pytest.mark.xfail), param("2**2", 4, idx=0), param("3**2", 9, id="3^2"), param("sqrt(9)", 3, key=itemgetter(0)), ]) def test_eval(test_input, expected): assert eval (test_input) == expected
New in version 0.4.0.
- Parameters
*values (
~_T
) – Variable args of the values of the parameter set, in order.marks (
Union
[MarkDecorator
,Collection
[Union
[MarkDecorator
,Mark
]]]) – A single mark or a list of marks to be applied to this parameter set. Default()
.id (
Optional
[str
]) – The id to attribute to this parameter set. DefaultNone
.idx (
Optional
[int
]) – The index of the value in*values
to use as the id. DefaultNone
.key (
Optional
[Callable
[[Tuple
[~_T
, …]],str
]]) – A callable which is givenvalues
(as atuple
) and returns the value to use as the id. DefaultNone
.
- Return type
ParameterSet
- Overloads
-
parametrized_versions
(*versions, reasons=())[source] Return a list of parametrized version numbers.
Examples:
@pytest.mark.parametrize( "version", parametrized_versions( 3.6, 3.7, 3.8, reason="Output differs on each version.", ), ) def test_something(version: str): pass
@pytest.fixture( params=parametrized_versions( 3.6, 3.7, 3.8, reason="Output differs on each version.", ), ) def version(request): return request.param def test_something(version: str): pass
New in version 0.4.0.
- Parameters
- Return type
List
[ParameterSet
]
coincidence.regressions
Regression test helpers.
To enable the fixtures in this module add the following to conftest.py
in your test directory:
pytest_plugins = ("coincidence", )
Classes:
|
Subclass of |
|
Subclass of |
|
Functions:
|
Pytest fixture for performing regression tests on lists, dictionaries and namedtuples. |
|
Pytest fixture for performing regression tests on strings, bytes and files. |
|
Check the given data against that in the reference file. |
|
Check the content of the given text file against the reference file. |
-
class
AdvancedDataRegressionFixture
(datadir, original_datadir, request)[source] Bases:
DataRegressionFixture
Subclass of
DataRegressionFixture
with support for additional types.The following types and their subclasses are supported:
collections.abc.Mapping
,typing.Mapping
(includingdict
andtyping.Dict
)collections.abc.Sequence
,typing.Sequence
(includinglist
,typing.Tuple
etc.)types.MappingProxyType
(cannot be subclassed)_pytest.capture.CaptureResult
(the type ofcapsys.readouterr()
)Any type which implements the
SupportsAsDict
protocol (includingcollections.namedtuple()
andtyping.NamedTuple
)
-
check
(data_dict, basename=None, fullpath=None)[source] Checks
data
against a previously recorded version, or generates a new file.- Parameters
data_dict (
Union
[Sequence
,SupportsAsDict
,Mapping
,MappingProxyType
,CaptureResult
])basename (
Optional
[str
]) – The basename of the file to test/record. If not given the name of the test is used. DefaultNone
.fullpath (
Optional
[str
]) – The complete path to use as a reference file. This option will ignoredatadir
fixture when reading expected files, but will still use it to write obtained files. Useful if a reference file is located in the session data dir, for example. DefaultNone
.
Note
basename
andfullpath
are exclusive.
-
class
AdvancedFileRegressionFixture
(datadir, original_datadir, request)[source] Bases:
FileRegressionFixture
Subclass of
FileRegressionFixture
with UTF-8 by default and some extra methods.New in version 0.2.0.
Methods:
check
(contents[, encoding, extension, …])Checks the contents against a previously recorded version, or generates a new file.
check_bytes
(contents, **kwargs)Checks the bytes contents against a previously recorded version, or generates a new file.
check_file
(filename[, extension, newline])Check the content of the given text file against the reference file.
-
check
(contents, encoding='UTF-8', extension='.txt', newline=None, basename=None, fullpath=None, binary=False, obtained_filename=None, check_fn=None)[source] Checks the contents against a previously recorded version, or generates a new file.
- Parameters
contents (
Union
[str
,StringList
])extension (
str
) – The extension of the reference file. Default'.txt'
.**kwargs – Additional keyword arguments passed to
pytest_regressions.file_regression.FileRegressionFixture.check()
.
See also
-
check_bytes
(contents, **kwargs)[source] Checks the bytes contents against a previously recorded version, or generates a new file.
- Parameters
contents (
bytes
)**kwargs – Additional keyword arguments passed to
pytest_regressions.file_regression.FileRegressionFixture.check()
.
-
check_file
(filename, extension=None, newline='\n', **kwargs)[source] Check the content of the given text file against the reference file.
- Parameters
extension (
Optional
[str
]) – The extension of the reference file. IfNone
the extension is determined fromfilename
. DefaultNone
.newline (
Optional
[str
]) – Controls how universal newlines mode works. Seeopen()
. Default'\n'
.**kwargs – Additional keyword arguments passed to
pytest_regressions.file_regression.FileRegressionFixture.check()
.
See also
-
-
protocol
SupportsAsDict
[source] Bases:
Protocol
typing.Protocol
for classes likecollections.namedtuple()
andtyping.NamedTuple
which implement an_asdict()
method.This protocol is runtime checkable.
Classes that implement this protocol must have the following methods / attributes:
-
fixture
advanced_data_regression
[source] Scope: function
Pytest fixture for performing regression tests on lists, dictionaries and namedtuples.
- Return type
-
fixture
advanced_file_regression
[source] Scope: function
Pytest fixture for performing regression tests on strings, bytes and files.
New in version 0.2.0.
- Return type
-
check_file_regression
(data, file_regression, extension='.txt', **kwargs)[source] Check the given data against that in the reference file.
- Parameters
data (
Union
[str
,StringList
])file_regression (
FileRegressionFixture
) – The file regression fixture for the test.extension (
str
) – The extension of the reference file. Default'.txt'
.**kwargs – Additional keyword arguments passed to
pytest_regressions.file_regression.FileRegressionFixture.check()
.
- Return type
-
check_file_output
(filename, file_regression, extension=None, newline='\n', **kwargs)[source] Check the content of the given text file against the reference file.
- Parameters
file_regression (
FileRegressionFixture
) – The file regression fixture for the test.extension (
Optional
[str
]) – The extension of the reference file. IfNone
the extension is determined fromfilename
. DefaultNone
.newline (
Optional
[str
]) – Controls how universal newlines mode works. Seeopen()
. Default'\n'
.**kwargs – Additional keyword arguments passed to
pytest_regressions.file_regression.FileRegressionFixture.check()
.
- Return type
coincidence.selectors
Pytest decorators for selectively running tests.
Functions:
|
Factory function to return a |
|
Factory function to return a |
|
Factory function to return a |
|
Factory function to return a |
|
Factory function to return a |
|
Factory function to return a |
|
Factory function to return a |
|
Factory function to return a |
|
Factory function to return a |
|
Factory function to return a |
|
Factory function to return a |
|
Factory function to return a |
|
Factory function to return a |
|
Factory function to return decorators such as |
-
min_version
(version, reason=None)[source] Factory function to return a
@pytest.mark.skipif
decorator which will skip a test if the current Python version is less than the required one.
-
max_version
(version, reason=None)[source] Factory function to return a
@pytest.mark.skipif
decorator which will skip a test if the current Python version is greater than the required one.
-
only_version
(version, reason=None)[source] Factory function to return a
@pytest.mark.skipif
decorator which will skip a test if the current Python version not the required one.
-
not_windows
(reason='Not required on Windows') Factory function to return a
@pytest.mark.skipif
decorator which will skip a test if the current platform is Windows.- Parameters
reason (
str
) – The reason to display when skipping. Default'Not required on Windows'
.- Return type
MarkDecorator
-
only_windows
(reason='Only required on Windows') Factory function to return a
@pytest.mark.skipif
decorator which will skip a test unless the current platform is Windows.- Parameters
reason (
str
) – The reason to display when skipping. Default'Only required on Windows'
.- Return type
MarkDecorator
-
not_pypy
(reason='Not required on PyPy') Factory function to return a
@pytest.mark.skipif
decorator which will skip a test if the current Python implementation is PyPy.- Parameters
reason (
str
) – The reason to display when skipping. Default'Not required on PyPy'
.- Return type
MarkDecorator
-
only_pypy
(reason='Only required on PyPy') Factory function to return a
@pytest.mark.skipif
decorator which will skip a test unless the current Python implementation is PyPy.- Parameters
reason (
str
) – The reason to display when skipping. Default'Only required on PyPy'
.- Return type
MarkDecorator
-
not_macos
(reason='Not required on macOS') Factory function to return a
@pytest.mark.skipif
decorator which will skip a test if the current platform is macOS.- Parameters
reason (
str
) – The reason to display when skipping. Default'Not required on macOS'
.- Return type
MarkDecorator
-
only_macos
(reason='Only required on macOS') Factory function to return a
@pytest.mark.skipif
decorator which will skip a test unless the current platform is macOS.- Parameters
reason (
str
) – The reason to display when skipping. Default'Only required on macOS'
.- Return type
MarkDecorator
-
not_docker
(reason='Not required on Docker') Factory function to return a
@pytest.mark.skipif
decorator which will skip a test if running on Docker.- Parameters
reason (
str
) – The reason to display when skipping. Default'Not required on Docker'
.- Return type
MarkDecorator
-
not_linux
(reason='Not required on Linux') Factory function to return a
@pytest.mark.skipif
decorator which will skip a test if the current platform is Linux.New in version 0.2.0.
- Parameters
reason (
str
) – The reason to display when skipping. Default'Not required on Linux'
.- Return type
MarkDecorator
-
only_linux
(reason='Only required on Linux') Factory function to return a
@pytest.mark.skipif
decorator which will skip a test unless the current platform is Linux.New in version 0.2.0.
- Parameters
reason (
str
) – The reason to display when skipping. Default'Only required on Linux'
.- Return type
MarkDecorator
-
only_docker
(reason='Only required on Docker') Factory function to return a
@pytest.mark.skipif
decorator which will skip a test unless running on Docker.- Parameters
reason (
str
) – The reason to display when skipping. Default'Only required on Docker'
.- Return type
MarkDecorator
-
platform_boolean_factory
(condition, platform, versionadded=None, *, module=None)[source] Factory function to return decorators such as
not_pypy()
andonly_windows()
.
coincidence.utils
Test helper utilities.
Functions:
|
Returns an iterator of strings, integers and booleans which should be considered |
|
Returns an iterator of strings, integers and booleans which should be considered |
Returns whether the current Python instance is running in Docker. |
|
|
Context manager to set a fixed datetime for the duration of the |
-
generate_truthy_values
(extra_truthy=(), ratio=1)[source] Returns an iterator of strings, integers and booleans which should be considered
True
.Optionally, a random selection of the values can be returned using the
ratio
argument.
-
generate_falsy_values
(extra_falsy=(), ratio=1)[source] Returns an iterator of strings, integers and booleans which should be considered
False
.Optionally, a random selection of the values can be returned using the
ratio
argument.
-
with_fixed_datetime
(fixed_datetime)[source] Context manager to set a fixed datetime for the duration of the
with
block.- Parameters
fixed_datetime (
datetime
)
See also
The
fixed_datetime
fixture.Attention
The monkeypatching only works when datetime is used and imported like:
import datetime print(datetime.datetime.now())
Using
from datetime import datetime
won’t work.- Return type
Changelog
0.6.0
coincidence.PEP_563()
is temporarily set to False
for all versions until the future of typing PEPs has been determined.
No released versions of Python currently have PEP 563 enabled by default.
0.5.0
coincidence.regressions.AdvancedDataRegressionFixture()
– Add support forpathlib
anddomdf_python_tools.paths.PathPlus
.
0.4.3
Bugs Fixed
coincidence.utils.with_fixed_datetime()
– Correctly handle monkeypatching of datetime in PyPy.
0.4.1
Bugs Fixed
coincidence.PEP_563()
– Is nowTrue
on Python >=3.11, per the deferral of PEP 563.
0.3.1
Bugs Fixed
coincidence.regressions
– Ensure the custom YAML representers are only configured if PyYAML can be imported.
0.3.0
coincidence.regressions.AdvancedDataRegressionFixture
Handle
toml.decoder.InlineTableDict
thetoml
module is available.Improve handling of custom subclasses, especially for nested types.
0.2.3
Bugs Fixed
Disabled the entry point as it was resulting in a confused plugin loading order and did not work.
The way of enabling the plugin reverts to:
# conftest.py
pytest_plugins = ("coincidence", )
0.2.0
Switched to whey as the build backend.
Added support for PyPy 3.7
(reverted in 0.2.3)Added an entry point for pytest to avoid the need to enable the plugin in conftest.
0.1.2
coincidence.regressions.AdvancedDataRegressionFixture.check()
– Add support for_pytest.capture.CaptureResult
.
0.1.1
coincidence.regressions.AdvancedDataRegressionFixture
– Add a fake version when PyYAML cannot be imported.
0.1.0
Initial release.
Downloading source code
The coincidence
source code is available on GitHub,
and can be accessed from the following URL: https://github.com/python-coincidence/coincidence
If you have git
installed, you can clone the repository with the following command:
git clone https://github.com/python-coincidence/coincidence
Cloning into 'coincidence'...
remote: Enumerating objects: 47, done.
remote: Counting objects: 100% (47/47), done.
remote: Compressing objects: 100% (41/41), done.
remote: Total 173 (delta 16), reused 17 (delta 6), pack-reused 126
Receiving objects: 100% (173/173), 126.56 KiB | 678.00 KiB/s, done.
Resolving deltas: 100% (66/66), done.

Downloading a ‘zip’ file of the source code
Building from source
The recommended way to build coincidence
is to use tox:
tox -e build
The source and wheel distributions will be in the directory dist
.
If you wish, you may also use pep517.build or another PEP 517-compatible build tool.
License
coincidence
is licensed under the MIT License
A short and simple permissive license with conditions only requiring preservation of copyright and license notices. Licensed works, modifications, and larger works may be distributed under different terms and without source code.
Permissions | Conditions | Limitations |
---|---|---|
|
|
Copyright (c) 2021 Dominic Davis-Foster
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
View the Function Index or browse the Source Code.