API Reference¶
Callables¶
- class pychoir.WhenPassedTo(callable_: Callable[[Any], Any])¶
Matchers that check how a value behaves when passed to a callable.
- Parameters:
callable – The callable to pass the value to.
- Usage:
>>> from pychoir import WhenPassedTo >>> "foo" == WhenPassedTo(int).raises(ValueError) True >>> "5" == WhenPassedTo(int).does_not_raise() True >>> "5" == WhenPassedTo(int).returns(5) True
Comparisons¶
- class pychoir.EqualTo(value: Any)¶
A somewhat redundant matcher checking for equality. Most Matchers can take values and/or Matchers and you should prefer bare values to wrapping them in EqualTo.
A notable exception is when used with & and | operators with a bare value on the left-most position
- Parameters:
value – The value to compare against.
- Usage:
>>> from pychoir import All, EqualTo, IsInstance >>> [1, 1, 1] == All(EqualTo(1)) # Bad, do not do this True >>> [1, 1, 1] == All(1) # Good, do this instead True >>> 1 == EqualTo(1) & IsInstance(int) # Needed here, but see below True >>> 1 == IsInstance(int) & 1 # Bare value works here True
- class pychoir.GreaterThan(threshold: Any)¶
A Matcher checking that compared value is greater than the given value.
- Parameters:
threshold – The value to compare against.
- Usage:
>>> from pychoir import GreaterThan >>> [2] == [GreaterThan(2)] False >>> [3] == [GreaterThan(2)] True
- class pychoir.GreaterThanOrEqualTo(threshold: Any)¶
A Matcher checking that compared value is greater than or equal to the given value.
- Parameters:
threshold – The value to compare against.
- Usage:
>>> from pychoir import GreaterThanOrEqualTo >>> 2 == GreaterThanOrEqualTo(2) True >>> 1 == GreaterThanOrEqualTo(2) False
- class pychoir.LessThan(threshold: Any)¶
A Matcher checking that compared value is less than the given value.
- Parameters:
threshold – The value to compare against.
- Usage:
>>> from pychoir import LessThan >>> 2 == LessThan(2) False >>> 1 == LessThan(2) True
- class pychoir.LessThanOrEqualTo(threshold: Any)¶
A Matcher checking that compared value is less than or equal to the given value.
- Parameters:
threshold – The value to compare against.
- Usage:
>>> from pychoir import LessThanOrEqualTo >>> 2 == LessThanOrEqualTo(2) True >>> 3 == LessThanOrEqualTo(2) False
- class pychoir.NotEqualTo(value: Any)¶
A Matcher checking that compared value is not equal to the given value.
- Parameters:
value – The value to compare against.
- Usage:
>>> from pychoir import NotEqualTo >>> 1 == NotEqualTo(2) True >>> 1 == NotEqualTo(1) False
- pychoir.GT¶
alias of
GreaterThan
- pychoir.GTE¶
alias of
GreaterThanOrEqualTo
- pychoir.LTE¶
alias of
LessThanOrEqualTo
- pychoir.NE¶
alias of
NotEqualTo
Containers¶
- class pychoir.All(*matchers: Matchable)¶
A Matcher checking that all values in a container match passed Matchables.
- Parameters:
matchers – The value(s) and/or Matcher(s) to compare against.
- Usage:
>>> from pychoir import All, IsInstance >>> 'aaa' == All('a') True >>> [1, 2, 3] == All(IsInstance(int)) True
- class pychoir.AreNot(*matchers: Matchable)¶
A Matcher checking that none of the values in a container match passed Matchables.
- Parameters:
matchers – The value(s) and/or Matcher(s) to compare against.
- Usage:
>>> from pychoir import AreNot, IsInstance >>> 'abc' == AreNot('a', 'b') False >>> [1, 2, 3] == AreNot(IsInstance(str)) True
- class pychoir.Contains(value: Any)¶
A Matcher checking that a container contains the passed value.
- Parameters:
value – The value to find in the container.
- Usage:
>>> from pychoir import Contains >>> 'abc' == Contains('a') True >>> [1, 2, 3] == Contains(4) False
- class pychoir.ContainsAllOf(*values: Any)¶
A Matcher checking that a container contains at least the passed values.
Plural of
Contains
.- Parameters:
values – The value(s) to find in the container.
- Usage:
>>> from pychoir import ContainsAllOf >>> 'abc' == ContainsAllOf('a', 'b') True >>> [1, 2, 3] == ContainsAllOf(3, 4) False
- class pychoir.ContainsAnyOf(*values: Any)¶
A Matcher checking that a container contains at least one of the passed values.
- Parameters:
values – The value(s) to find in the container.
- Usage:
>>> from pychoir import ContainsAnyOf >>> 'abc' == ContainsAnyOf('a', 'b') True >>> [1, 2, 3] == ContainsAnyOf(3, 4) True
- class pychoir.ContainsNoneOf(*values: Any)¶
A Matcher checking that a container contains none of the passed values.
- Parameters:
values – The value(s) to find in the container.
- Usage:
>>> from pychoir import ContainsNoneOf >>> 'abc' == ContainsNoneOf('a', 'b') False >>> [1, 2, 3] == ContainsNoneOf(4) True
- class pychoir.DictContainsAllOf(value: Mapping[Any, Any])¶
A Matcher checking that a Mapping contains at least the passed Mapping. Usually this means that the passed dict is a subset of the one compared against. Keys expected to be absent can be set as
NotPresent
.- Parameters:
value – The Mapping to find in the Mapping compared against.
- Usage:
>>> from pychoir import DictContainsAllOf, NotPresent >>> {'a': 1, 'b': 2, 'd': 3} == DictContainsAllOf({'a': 1, 'c': NotPresent}) True >>> {'a': 1, 'c': 2, 'd': 3} == DictContainsAllOf({'a': 1, 'c': NotPresent}) False
- class pychoir.HasLength(matcher: Matchable)¶
A Matcher checking that the len() of the compared value matches the passed Matchable.
- Parameters:
matcher – The value or Matcher to compare against.
- Usage:
>>> from pychoir import GreaterThan, HasLength >>> 'foo' == HasLength(3) True >>> 'foo' == HasLength(GreaterThan(2)) True
- class pychoir.InAnyOrder(values: Iterable[Matchable])¶
A Matcher checking that an Iterable contains exactly the passed items, in any order.
The Iterable can be for example a list, tuple or set. Items can be Matchers and do not need to be hashable.
- Parameters:
values – An Iterable containing the expected items, in any order.
- Usage:
>>> from pychoir import InAnyOrder, IsEven, IsOdd >>> [1, 2, 3, 3] == InAnyOrder([3, 2, 3, 1]) True >>> [1, 2, 3] == InAnyOrder([3, 3, 2, 1]) # missing one 3 False >>> [1, 2, 3, 3] == InAnyOrder([3, 2, 1]) # one 3 too many False >>> [1, 2, 3] == InAnyOrder((1, 2, 3)) # type of the Iterable does not matter True >>> [{'a': 1}, {'b': 2}] == InAnyOrder([{'b': IsEven()}, {'a': IsOdd()}]) True
- class pychoir.IsEmpty(name: DefaultType | str | None = DefaultType.DEFAULT)¶
A Matcher checking that the len() of the compared value is 0.
- Usage:
>>> from pychoir import All, IsEmpty, Not >>> ('', [], {}, set(), tuple()) == All(IsEmpty()) True >>> {'not': 'empty'} == Not(IsEmpty()) True
- class pychoir.IsNotPresentOr(matcher: Matchable)¶
A Matcher checking that a value is either
NotPresent
or matches the passed matcher. Usually used for example withDictContainsAllOf
.- Parameters:
matcher – The Mapping to find in the Mapping compared against.
- Usage:
>>> from pychoir import DictContainsAllOf, IsNotPresentOr >>> {'a': 2} == DictContainsAllOf({'a': IsNotPresentOr(2)}) True >>> {} == DictContainsAllOf({'a': IsNotPresentOr(2)}) True
- class pychoir.SetEquals(values: Iterable[Any])¶
A Matcher checking that an Iterable has the expected items, duplicates ignored. Faster than
InAnyOrder
but less pedantic about duplicates and requires hashable items.The Iterable can be for example a list, tuple or set. Items must be hashable.
- Parameters:
values – An Iterable containing the expected items, in any order.
- Usage:
>>> from pychoir import SetEquals >>> [1, 2, 3, 3] == SetEquals([3, 2, 1]) True >>> [1, 2] == SetEquals([3, 2, 1]) False
- containers.NotPresent = NotPresent¶
- class pychoir.First(how_many: int = 1)¶
A Higher Order Matcher checking that the first how_many values match given matchers. The matcher is applied to the slice extracted from the passed
Sequence
.- Parameters:
how_many – The number of values to slice from the start of the sequence being compared.
- Usage:
>>> from pychoir import First, All, GreaterThan >>> (1, 2, 3) == First(2)((1, 2)) True >>> (1, 2, 3) == First()(1) True
- class pychoir.Last(how_many: int = 1)¶
A Higher Order Matcher checking that the last how_many values match given matchers. The matcher is applied to the slice extracted from the passed
Sequence
.- Parameters:
how_many – The number of values to slice from the end of the sequence being compared.
- Usage:
>>> from pychoir import Last, All, LessThan >>> (1, 2, 3) == Last(2)((2, 3)) True >>> (1, 2, 3) == Last()(3) True
- containers.Slice = <pychoir.containers._SliceFactory object>¶
- class pychoir.containers._SliceFactory¶
A Higher Order Matcher checking that the sliced values match given matchers. The matcher is applied to the slice extracted from the passed
Sequence
.- Usage:
>>> from pychoir import Slice, And, IsInstance >>> (1, 2, 3) == Slice[1:3]((2, 3)) True >>> (1, 2, 3) == Slice[2](And(IsInstance(int), 3)) True
Core¶
- class pychoir.Matchable(*args, **kwargs)¶
Type for a value that can be matched against using the
==
operator (has the__eq__
method). In the pychoir API, you can typically pass Matcher s and/or normal values where Matchable s are expected.- __eq__(other: MatchedType) bool ¶
Return self==value.
- class pychoir.Matcher(name: DefaultType | str | None = DefaultType.DEFAULT)¶
The baseclass for all Matchers.
- Parameters:
name –
Only for Matchers whose class name does not match the call that creates them. This applies, for example, to Matchers created by
Transformer
s.For example
_First(Matcher)
(that is created byFirst(Transformer)
) uses this to make its name'First'
instead of'_First'
in its textual representation.
- __and__(other: Matchable) Matcher ¶
Combines several matchers in a similar fashion as
And
- Usage:
>>> from pychoir import IsInstance >>> 5 == IsInstance(int) & 5 True >>> 5.0 == IsInstance(int) & 5 False
- __or__(other: Matchable) Matcher ¶
Combines several matchers in a similar fashion as
Or
- Usage:
>>> from pychoir import StartsWith >>> 'foo' == StartsWith('foo') | StartsWith('bar') True >>> 'bar' == StartsWith('foo') | StartsWith('bar') True >>> 'baz' == StartsWith('foo') | StartsWith('bar') False
- final __repr__() str ¶
Textual representation of the Matcher.
Contains info about failures and failed values
- abstract _description() str ¶
Returns a textual representation of the Matcher’s parameters.
For example in
"EqualTo('foo')"
the'foo'
is returned by_description()
.To be implemented by all Matchers.
- abstract _matches(other: MatchedType) bool ¶
Returns True when Matcher matches, False otherwise.
- Parameters:
other – The value being compared.
To be implemented by all Matchers.
- final _reset_nested_failures() None ¶
For resetting failure state of child matchers in case of passing due to other Matchers.
For example in
Or
, it is enough that one child Matcher passes. The matchers tried up to that point should not report failure. After a Matcher reports a success, nested failures get reset automatically.It is unlikely that you should ever call this from your tests or custom Matchers yourself.
- final as_(type_: Type[T]) T ¶
Change the static type of the Matcher to make it pass type checking.
- final nested_match(matcher: Matcher | Matchable, other: MatchedType, expect_mismatch: bool = False) bool ¶
For evaluating Matchables (or calling Matchers) from inside a Matcher.
Takes care of passing all necessary context and updating state when matching.
- Parameters:
matcher – The value or Matcher to compare against.
other – The value being compared.
expect_mismatch – Set to True when expecting a mismatch (for example in
Not
).
- pychoir.that(value: MatchedType) MatcherWrapper ¶
A helper for syntactically sugar coating matches instead of using ==.
- Parameters:
value – The value to pass into the Matcher in MatcherWrapper.matches()
- Returns:
A
MatcherWrapper
- Usage:
>>> from pychoir import that, GreaterThan >>> assert that(3).matches(GreaterThan(2)) ... >>> assert that(1).matches(GreaterThan(2)) Traceback (most recent call last): ... AssertionError
Existential¶
- class pychoir.Anything(name: DefaultType | str | None = DefaultType.DEFAULT)¶
A Matcher that matches anything.
- Usage:
>>> from pychoir import Anything >>> None == Anything() True >>> {'a': None} == {'a': Anything()} True >>> {'b': 1} == {'a': Anything()} False
- class pychoir.In(allowed_values: Iterable[Any])¶
A Matcher checking that the compared value is in the passed iterable.
- Usage:
>>> from string import ascii_lowercase >>> from pychoir import In >>> 'a' == In(ascii_lowercase) True >>> 'A' == In(ascii_lowercase) False
- class pychoir.Is(value: Any)¶
A Matcher checking that the compared value
is
the passed value.In Python
is
is used to check whether two objects are the same object in memory.- Parameters:
value – The value to compare against.
- Usage:
>>> from pychoir import Is >>> None == Is(None) True >>> [] == Is([]) False
- class pychoir.IsFalsy(name: DefaultType | str | None = DefaultType.DEFAULT)¶
A Matcher checking that the compared value is falsy when used as a condition.
In other words, checks whether
if value: ... else: ...
would go to the else branch.- Usage:
>>> from pychoir import IsFalsy >>> '' == IsFalsy() True >>> 5 == IsFalsy() False
- class pychoir.IsNoneOr(*matchers: Matchable)¶
A Matcher checking that the compared value
is None
or equal to the passed value.This is useful for checking
Optional
values.- Parameters:
matchers – The value(s) and/or matcher(s) to compare against.
- Usage:
>>> from pychoir import IsNoneOr >>> None == IsNoneOr(5) True >>> 5 == IsNoneOr(5) True >>> 4 == IsNoneOr(5) False
- class pychoir.IsTruthy(name: DefaultType | str | None = DefaultType.DEFAULT)¶
A Matcher checking that the compared value is truthy when used as a condition.
In other words, checks whether
if value: ... else: ...
would go to the if branch.- Usage:
>>> from pychoir import IsTruthy >>> '' == IsTruthy() False >>> 5 == IsTruthy() True
Integration¶
- class pychoir.Matches(*matchers: _MatcherLike[T])¶
- pychoir.MatcherLike¶
alias of
_MatcherLike
[T
]
Logical¶
- class pychoir.And(*matchers: Matchable)¶
A Matcher checking that the compared value matches all the passed
Matchable
s.Consider using the
&
operator (Matcher.__and__()
) instead:StartsWith('a') & HasLength(3)
.- Parameters:
matchers – The value(s) and/or matcher(s) to compare against.
- Usage:
>>> from pychoir import And, IsInstance, HasLength, StartsWith >>> 5 == And(IsInstance(int), 5) True >>> 'abc' == And(StartsWith('a'), HasLength(3)) True >>> 4 == And(IsInstance(int), 5) False
- class pychoir.Not(*matchers: Matchable)¶
A Matcher checking that the compared value matches none of the passed
Matchable
s.- Parameters:
matchers – The value(s) and/or matcher(s) to compare against.
- Usage:
>>> from pychoir import Not, IsInstance, StartsWith >>> 5 == Not(IsInstance(str)) True >>> 'abc' == Not(StartsWith('abc'), StartsWith('def')) False >>> 4 == Not(IsInstance(str), 5) True
- class pychoir.Or(*matchers: Matchable)¶
A Matcher checking that the compared value matches at least one of the passed
Matchable
s.Consider using the
|
operator (Matcher.__or__()
) instead:StartsWith('a') | StartsWith('b')
.- Parameters:
matchers – The value(s) and/or matcher(s) to compare against.
- Usage:
>>> from pychoir import Or, IsInstance, StartsWith >>> 5 == Or(IsInstance(int), 5) True >>> 'abc' == Or(StartsWith('abc'), StartsWith('def')) True >>> '4' == Or(IsInstance(int), 5) False
- class pychoir.ResultsTrueFor(*conditions: Callable[[Any], bool])¶
A Matcher checking that the compared value results
True
when given to the passed function(s).- Parameters:
conditions – The functions to check against.
- Usage:
>>> from pychoir import ResultsTrueFor >>> 5 == ResultsTrueFor(bool) True >>> 'abc' == ResultsTrueFor(lambda x: x[2] == 'c') True
Numeric¶
- class pychoir.IsEven(name: DefaultType | str | None = DefaultType.DEFAULT)¶
A Matcher checking that the value compared against it is even.
- Usage:
>>> from pychoir import IsEven >>> 4 == IsEven() True >>> 5 == IsEven() False
- class pychoir.IsOdd(name: DefaultType | str | None = DefaultType.DEFAULT)¶
A Matcher checking that the value compared against it is odd.
- Usage:
>>> from pychoir import IsOdd >>> 5 == IsOdd() True >>> 4 == IsOdd() False
- class pychoir.IsPositive(name: DefaultType | str | None = DefaultType.DEFAULT)¶
A Matcher checking that the value compared against it is positive.
- Usage:
>>> from pychoir import IsPositive >>> 1 == IsPositive() True >>> 0 == IsPositive() False
- class pychoir.IsNonNegative(name: DefaultType | str | None = DefaultType.DEFAULT)¶
A Matcher checking that the value compared against it is non-negative.
- Usage:
>>> from pychoir import IsPositive >>> 1 == IsNonNegative() True >>> 0 == IsNonNegative() True >>> -1 == IsNonNegative() False
- class pychoir.IsNegative(name: DefaultType | str | None = DefaultType.DEFAULT)¶
A Matcher checking that the value compared against it is negative.
- Usage:
>>> from pychoir import IsNegative >>> -1 == IsNegative() True >>> 0 == IsNegative() False
Strings¶
- class pychoir.EndsWith(end: str)¶
A Matcher checking that the compared string
.endswith()
the passed string.- Parameters:
end – The string the compared value is expected to end with.
- Usage:
>>> from pychoir import EndsWith >>> 'foobar' == EndsWith('bar') True >>> 'foofoo' == EndsWith('bar') False
- class pychoir.MatchesRegex(regex: str | Pattern)¶
A Matcher checking that the compared string matches the passed regular expression.
- Parameters:
regex – The regular expression (as a string or a
re.Pattern
).
- Usage:
>>> import re >>> from pychoir import MatchesRegex >>> 'foobar' == MatchesRegex(r'^f.obar') True >>> 'foofoo' == MatchesRegex(re.compile(r'^b[ao]r$')) False
- class pychoir.StartsWith(start: str)¶
A Matcher checking that the compared string
.startswith()
the passed string.- Parameters:
start – The string the compared value is expected to start with.
- Usage:
>>> from pychoir import StartsWith >>> 'foobar' == StartsWith('foo') True >>> 'barbar' == StartsWith('foo') False
Types¶
- class pychoir.ConvertsTo(type_: Type[Any])¶
A Matcher checking that the compared value can be converted into the passed type.
- Parameters:
type – The type to which conversion shall be attempted.
- Usage:
>>> from pychoir import ConvertsTo >>> '5' == ConvertsTo(int) True >>> '5.2' == ConvertsTo(int) False
- class pychoir.IsInstance(*types: Type[Any])¶
A Matcher checking that the compared object’s type matches the passed one.
- Parameters:
types – The expected type(s) of compared values.
- Usage:
>>> from pychoir import IsInstance >>> 5 == IsInstance(int) True >>> 'foobar' == IsInstance(int) False >>> 'foobar' == IsInstance(int, str) True
- pychoir.OfType¶
alias of
IsInstance