assertpy2 2.0.0__py3-none-any.whl
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.
- assertpy2/__init__.py +25 -0
- assertpy2/assertpy.py +468 -0
- assertpy2/base.py +435 -0
- assertpy2/collection.py +217 -0
- assertpy2/contains.py +386 -0
- assertpy2/date.py +219 -0
- assertpy2/dict.py +255 -0
- assertpy2/dynamic.py +113 -0
- assertpy2/exception.py +128 -0
- assertpy2/extracting.py +233 -0
- assertpy2/file.py +276 -0
- assertpy2/helpers.py +273 -0
- assertpy2/numeric.py +555 -0
- assertpy2/py.typed +0 -0
- assertpy2/snapshot.py +217 -0
- assertpy2/string.py +413 -0
- assertpy2-2.0.0.dist-info/METADATA +227 -0
- assertpy2-2.0.0.dist-info/RECORD +20 -0
- assertpy2-2.0.0.dist-info/WHEEL +4 -0
- assertpy2-2.0.0.dist-info/licenses/LICENSE +28 -0
assertpy2/snapshot.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
# Copyright (c) 2015-2019, Activision Publishing, Inc.
|
|
2
|
+
# All rights reserved.
|
|
3
|
+
#
|
|
4
|
+
# Redistribution and use in source and binary forms, with or without modification,
|
|
5
|
+
# are permitted provided that the following conditions are met:
|
|
6
|
+
#
|
|
7
|
+
# 1. Redistributions of source code must retain the above copyright notice, this
|
|
8
|
+
# list of conditions and the following disclaimer.
|
|
9
|
+
#
|
|
10
|
+
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
11
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
12
|
+
# and/or other materials provided with the distribution.
|
|
13
|
+
#
|
|
14
|
+
# 3. Neither the name of the copyright holder nor the names of its contributors
|
|
15
|
+
# may be used to endorse or promote products derived from this software without
|
|
16
|
+
# specific prior written permission.
|
|
17
|
+
#
|
|
18
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
19
|
+
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
20
|
+
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
21
|
+
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
|
22
|
+
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
23
|
+
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
24
|
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
|
25
|
+
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
26
|
+
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
27
|
+
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import datetime
|
|
32
|
+
import inspect
|
|
33
|
+
import json
|
|
34
|
+
import os
|
|
35
|
+
import sys
|
|
36
|
+
from typing import TYPE_CHECKING
|
|
37
|
+
|
|
38
|
+
if TYPE_CHECKING:
|
|
39
|
+
from typing_extensions import Self
|
|
40
|
+
|
|
41
|
+
__tracebackhide__ = True
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class SnapshotMixin:
|
|
45
|
+
"""Snapshot mixin.
|
|
46
|
+
|
|
47
|
+
Take a snapshot of a python data structure, store it on disk in JSON format, and automatically
|
|
48
|
+
compare the latest data to the stored data on every test run.
|
|
49
|
+
|
|
50
|
+
Functional testing (which snapshot testing falls under) is very much blackbox testing. When
|
|
51
|
+
something goes wrong, it's hard to pinpoint the issue, because functional tests typically
|
|
52
|
+
provide minimal *isolation* as compared to unit tests. On the plus side, snapshots typically
|
|
53
|
+
do provide enormous *leverage* as a few well-placed snapshot tests can strongly verify that an
|
|
54
|
+
application is working. Similar coverage would otherwise require dozens if not hundreds of
|
|
55
|
+
unit tests.
|
|
56
|
+
|
|
57
|
+
**On-disk Format**
|
|
58
|
+
|
|
59
|
+
Snapshots are stored in a readable JSON format. For example::
|
|
60
|
+
|
|
61
|
+
assert_that({'a': 1, 'b': 2, 'c': 3}).snapshot()
|
|
62
|
+
|
|
63
|
+
Would be stored as::
|
|
64
|
+
|
|
65
|
+
{
|
|
66
|
+
"a": 1,
|
|
67
|
+
"b": 2,
|
|
68
|
+
"c": 3
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
The JSON formatting support most python data structures (dict, list, object, etc), but not custom
|
|
72
|
+
binary data.
|
|
73
|
+
|
|
74
|
+
**Updating**
|
|
75
|
+
|
|
76
|
+
It's easy to update your snapshots...just delete them all and re-run the test suite to regenerate all snapshots.
|
|
77
|
+
|
|
78
|
+
Note:
|
|
79
|
+
Snapshots require Python 3.x
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def snapshot(self, id=None, path="__snapshots") -> Self:
|
|
83
|
+
"""Asserts that val is identical to the on-disk snapshot stored previously.
|
|
84
|
+
|
|
85
|
+
On the first run of a test before the snapshot file has been saved, a snapshot is created,
|
|
86
|
+
stored to disk, and the test *always* passes. But on all subsequent runs, val is compared
|
|
87
|
+
to the on-disk snapshot, and the test fails if they don't match.
|
|
88
|
+
|
|
89
|
+
Snapshot artifacts are stored in the ``__snapshots`` directory by default, and should be
|
|
90
|
+
committed to source control alongside any code changes.
|
|
91
|
+
|
|
92
|
+
Snapshots are identified by test filename plus line number by default.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
id: the item or items expected to be contained
|
|
96
|
+
path: the item or items expected to be contained
|
|
97
|
+
|
|
98
|
+
Examples:
|
|
99
|
+
Usage::
|
|
100
|
+
|
|
101
|
+
assert_that(None).snapshot()
|
|
102
|
+
assert_that(True).snapshot()
|
|
103
|
+
assert_that(1).snapshot()
|
|
104
|
+
assert_that(123.4).snapshot()
|
|
105
|
+
assert_that('foo').snapshot()
|
|
106
|
+
assert_that([1, 2, 3]).snapshot()
|
|
107
|
+
assert_that({'a': 1, 'b': 2, 'c': 3}).snapshot()
|
|
108
|
+
assert_that({'a', 'b', 'c'}).snapshot()
|
|
109
|
+
assert_that(1 + 2j).snapshot()
|
|
110
|
+
assert_that(someobj).snapshot()
|
|
111
|
+
|
|
112
|
+
By default, snapshots are identified by test filename plus line number. Alternately, you can specify a custom identifier using the ``id`` arg::
|
|
113
|
+
|
|
114
|
+
assert_that({'a': 1, 'b': 2, 'c': 3}).snapshot(id='foo-id')
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
By default, snapshots are stored in the ``__snapshots`` directory. Alternately, you can specify a custom path using the ``path`` arg::
|
|
118
|
+
|
|
119
|
+
assert_that({'a': 1, 'b': 2, 'c': 3}).snapshot(path='my-custom-folder')
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
AssertionBuilder: returns this instance to chain to the next assertion
|
|
123
|
+
|
|
124
|
+
Raises:
|
|
125
|
+
AssertionError: if val does **not** equal to on-disk snapshot
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
class _Encoder(json.JSONEncoder):
|
|
129
|
+
def default(self, o):
|
|
130
|
+
if isinstance(o, set):
|
|
131
|
+
return {"__type__": "set", "__data__": list(o)}
|
|
132
|
+
elif isinstance(o, complex):
|
|
133
|
+
return {"__type__": "complex", "__data__": [o.real, o.imag]}
|
|
134
|
+
elif isinstance(o, datetime.datetime):
|
|
135
|
+
return {"__type__": "datetime", "__data__": o.strftime("%Y-%m-%d %H:%M:%S")}
|
|
136
|
+
elif "__dict__" in dir(o) and type(o) is not type:
|
|
137
|
+
return {
|
|
138
|
+
"__type__": "instance",
|
|
139
|
+
"__class__": o.__class__.__name__,
|
|
140
|
+
"__module__": o.__class__.__module__,
|
|
141
|
+
"__data__": o.__dict__,
|
|
142
|
+
}
|
|
143
|
+
return json.JSONEncoder.default(self, o)
|
|
144
|
+
|
|
145
|
+
class _Decoder(json.JSONDecoder):
|
|
146
|
+
def __init__(self):
|
|
147
|
+
json.JSONDecoder.__init__(self, object_hook=self.object_hook)
|
|
148
|
+
|
|
149
|
+
def object_hook(self, d):
|
|
150
|
+
if "__type__" in d and "__data__" in d:
|
|
151
|
+
if d["__type__"] == "set":
|
|
152
|
+
return set(d["__data__"])
|
|
153
|
+
elif d["__type__"] == "complex":
|
|
154
|
+
return complex(d["__data__"][0], d["__data__"][1])
|
|
155
|
+
elif d["__type__"] == "datetime":
|
|
156
|
+
return datetime.datetime.strptime(d["__data__"], "%Y-%m-%d %H:%M:%S")
|
|
157
|
+
elif d["__type__"] == "instance":
|
|
158
|
+
module_name = d["__module__"]
|
|
159
|
+
if module_name not in sys.modules:
|
|
160
|
+
return d
|
|
161
|
+
mod = sys.modules[module_name]
|
|
162
|
+
klass = getattr(mod, d["__class__"], None)
|
|
163
|
+
if klass is None:
|
|
164
|
+
return d
|
|
165
|
+
inst = klass.__new__(klass)
|
|
166
|
+
inst.__dict__ = d["__data__"]
|
|
167
|
+
return inst
|
|
168
|
+
return d
|
|
169
|
+
|
|
170
|
+
def _save(name, val):
|
|
171
|
+
with open(name, "w") as fp:
|
|
172
|
+
json.dump(val, fp, indent=2, separators=(",", ": "), sort_keys=True, cls=_Encoder)
|
|
173
|
+
|
|
174
|
+
def _load(name):
|
|
175
|
+
with open(name) as fp:
|
|
176
|
+
return json.load(fp, cls=_Decoder)
|
|
177
|
+
|
|
178
|
+
def _name(path, name):
|
|
179
|
+
try:
|
|
180
|
+
return os.path.join(path, "snap-%s.json" % name.replace(" ", "_").lower())
|
|
181
|
+
except (TypeError, AttributeError):
|
|
182
|
+
raise ValueError("failed to create snapshot filename, either bad path or bad name") from None
|
|
183
|
+
|
|
184
|
+
if id:
|
|
185
|
+
# custom id
|
|
186
|
+
snapname = _name(path, id)
|
|
187
|
+
else:
|
|
188
|
+
# make id from filename and line number
|
|
189
|
+
f = inspect.currentframe()
|
|
190
|
+
fpath = os.path.basename(f.f_back.f_code.co_filename)
|
|
191
|
+
fname = os.path.splitext(fpath)[0]
|
|
192
|
+
lineno = str(f.f_back.f_lineno)
|
|
193
|
+
snapname = _name(path, fname)
|
|
194
|
+
|
|
195
|
+
if not os.path.exists(path):
|
|
196
|
+
os.makedirs(path)
|
|
197
|
+
|
|
198
|
+
if os.path.isfile(snapname):
|
|
199
|
+
# snap exists, so load
|
|
200
|
+
snap = _load(snapname)
|
|
201
|
+
|
|
202
|
+
if id:
|
|
203
|
+
# custom id, so test
|
|
204
|
+
return self.is_equal_to(snap)
|
|
205
|
+
else:
|
|
206
|
+
if lineno in snap:
|
|
207
|
+
# found sub-snap, so test
|
|
208
|
+
return self.is_equal_to(snap[lineno])
|
|
209
|
+
else:
|
|
210
|
+
# lineno not in snap, so create sub-snap and pass
|
|
211
|
+
snap[lineno] = self.val
|
|
212
|
+
_save(snapname, snap)
|
|
213
|
+
else:
|
|
214
|
+
# no snap, so create and pass
|
|
215
|
+
_save(snapname, self.val if id else {lineno: self.val})
|
|
216
|
+
|
|
217
|
+
return self
|
assertpy2/string.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
# Copyright (c) 2015-2019, Activision Publishing, Inc.
|
|
2
|
+
# All rights reserved.
|
|
3
|
+
#
|
|
4
|
+
# Redistribution and use in source and binary forms, with or without modification,
|
|
5
|
+
# are permitted provided that the following conditions are met:
|
|
6
|
+
#
|
|
7
|
+
# 1. Redistributions of source code must retain the above copyright notice, this
|
|
8
|
+
# list of conditions and the following disclaimer.
|
|
9
|
+
#
|
|
10
|
+
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
11
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
12
|
+
# and/or other materials provided with the distribution.
|
|
13
|
+
#
|
|
14
|
+
# 3. Neither the name of the copyright holder nor the names of its contributors
|
|
15
|
+
# may be used to endorse or promote products derived from this software without
|
|
16
|
+
# specific prior written permission.
|
|
17
|
+
#
|
|
18
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
19
|
+
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
20
|
+
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
21
|
+
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
|
22
|
+
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
23
|
+
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
24
|
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
|
25
|
+
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
26
|
+
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
27
|
+
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import collections.abc
|
|
32
|
+
import re
|
|
33
|
+
from typing import TYPE_CHECKING
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
from typing_extensions import Self
|
|
37
|
+
|
|
38
|
+
__tracebackhide__ = True
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class StringMixin:
|
|
42
|
+
"""String assertions mixin."""
|
|
43
|
+
|
|
44
|
+
def is_equal_to_ignoring_case(self, other) -> Self:
|
|
45
|
+
"""Asserts that val is a string and is case-insensitive equal to other.
|
|
46
|
+
|
|
47
|
+
Checks actual is equal to expected using the ``==`` operator and ``str.lower()``.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
other: the expected value
|
|
51
|
+
|
|
52
|
+
Examples:
|
|
53
|
+
Usage::
|
|
54
|
+
|
|
55
|
+
assert_that('foo').is_equal_to_ignoring_case('FOO')
|
|
56
|
+
assert_that('FOO').is_equal_to_ignoring_case('foo')
|
|
57
|
+
assert_that('fOo').is_equal_to_ignoring_case('FoO')
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
AssertionBuilder: returns this instance to chain to the next assertion
|
|
61
|
+
|
|
62
|
+
Raises:
|
|
63
|
+
AssertionError: if actual is **not** case-insensitive equal to expected
|
|
64
|
+
"""
|
|
65
|
+
if not isinstance(self.val, str):
|
|
66
|
+
raise TypeError("val is not a string")
|
|
67
|
+
if not isinstance(other, str):
|
|
68
|
+
raise TypeError("given arg must be a string")
|
|
69
|
+
if self.val.lower() != other.lower():
|
|
70
|
+
return self.error("Expected <%s> to be case-insensitive equal to <%s>, but was not." % (self.val, other))
|
|
71
|
+
return self
|
|
72
|
+
|
|
73
|
+
def contains_ignoring_case(self, *items) -> Self:
|
|
74
|
+
"""Asserts that val is string and contains the given item or items.
|
|
75
|
+
|
|
76
|
+
Walks val and checks for item or items using the ``==`` operator and ``str.lower()``.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
*items: the item or items expected to be contained
|
|
80
|
+
|
|
81
|
+
Examples:
|
|
82
|
+
Usage::
|
|
83
|
+
|
|
84
|
+
assert_that('foo').contains_ignoring_case('F', 'oO')
|
|
85
|
+
assert_that(['a', 'B']).contains_ignoring_case('A', 'b')
|
|
86
|
+
assert_that({'a': 1, 'B': 2}).contains_ignoring_case('A', 'b')
|
|
87
|
+
assert_that({'a', 'B'}).contains_ignoring_case('A', 'b')
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
AssertionBuilder: returns this instance to chain to the next assertion
|
|
91
|
+
|
|
92
|
+
Raises:
|
|
93
|
+
AssertionError: if val does **not** contain the case-insensitive item or items
|
|
94
|
+
"""
|
|
95
|
+
if len(items) == 0:
|
|
96
|
+
raise ValueError("one or more args must be given")
|
|
97
|
+
if isinstance(self.val, str):
|
|
98
|
+
if len(items) == 1:
|
|
99
|
+
if not isinstance(items[0], str):
|
|
100
|
+
raise TypeError("given arg must be a string")
|
|
101
|
+
if items[0].lower() not in self.val.lower():
|
|
102
|
+
return self.error(
|
|
103
|
+
"Expected <%s> to case-insensitive contain item <%s>, but did not." % (self.val, items[0])
|
|
104
|
+
)
|
|
105
|
+
else:
|
|
106
|
+
missing = []
|
|
107
|
+
for i in items:
|
|
108
|
+
if not isinstance(i, str):
|
|
109
|
+
raise TypeError("given args must all be strings")
|
|
110
|
+
if i.lower() not in self.val.lower():
|
|
111
|
+
missing.append(i)
|
|
112
|
+
if missing:
|
|
113
|
+
return self.error(
|
|
114
|
+
"Expected <%s> to case-insensitive contain items %s, but did not contain %s."
|
|
115
|
+
% (self.val, self._fmt_items(items), self._fmt_items(missing))
|
|
116
|
+
)
|
|
117
|
+
elif isinstance(self.val, collections.abc.Iterable):
|
|
118
|
+
missing = []
|
|
119
|
+
for i in items:
|
|
120
|
+
if not isinstance(i, str):
|
|
121
|
+
raise TypeError("given args must all be strings")
|
|
122
|
+
found = False
|
|
123
|
+
for v in self.val:
|
|
124
|
+
if not isinstance(v, str):
|
|
125
|
+
raise TypeError("val items must all be strings")
|
|
126
|
+
if i.lower() == v.lower():
|
|
127
|
+
found = True
|
|
128
|
+
break
|
|
129
|
+
if not found:
|
|
130
|
+
missing.append(i)
|
|
131
|
+
if missing:
|
|
132
|
+
return self.error(
|
|
133
|
+
"Expected <%s> to case-insensitive contain items %s, but did not contain %s."
|
|
134
|
+
% (self.val, self._fmt_items(items), self._fmt_items(missing))
|
|
135
|
+
)
|
|
136
|
+
else:
|
|
137
|
+
raise TypeError("val is not a string or iterable")
|
|
138
|
+
return self
|
|
139
|
+
|
|
140
|
+
def starts_with(self, prefix) -> Self:
|
|
141
|
+
"""Asserts that val is string or iterable and starts with prefix.
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
prefix: the prefix
|
|
145
|
+
|
|
146
|
+
Examples:
|
|
147
|
+
Usage::
|
|
148
|
+
|
|
149
|
+
assert_that('foo').starts_with('fo')
|
|
150
|
+
assert_that(['a', 'b', 'c']).starts_with('a')
|
|
151
|
+
assert_that((1, 2, 3)).starts_with(1)
|
|
152
|
+
assert_that(((1, 2), (3, 4), (5, 6))).starts_with((1, 2))
|
|
153
|
+
|
|
154
|
+
Returns:
|
|
155
|
+
AssertionBuilder: returns this instance to chain to the next assertion
|
|
156
|
+
|
|
157
|
+
Raises:
|
|
158
|
+
AssertionError: if val does **not** start with prefix
|
|
159
|
+
"""
|
|
160
|
+
if prefix is None:
|
|
161
|
+
raise TypeError("given prefix arg must not be none")
|
|
162
|
+
if isinstance(self.val, str):
|
|
163
|
+
if not isinstance(prefix, str):
|
|
164
|
+
raise TypeError("given prefix arg must be a string")
|
|
165
|
+
if len(prefix) == 0:
|
|
166
|
+
raise ValueError("given prefix arg must not be empty")
|
|
167
|
+
if not self.val.startswith(prefix):
|
|
168
|
+
return self.error("Expected <%s> to start with <%s>, but did not." % (self.val, prefix))
|
|
169
|
+
elif isinstance(self.val, collections.abc.Iterable):
|
|
170
|
+
if len(self.val) == 0:
|
|
171
|
+
raise ValueError("val must not be empty")
|
|
172
|
+
first = next(iter(self.val))
|
|
173
|
+
if first != prefix:
|
|
174
|
+
return self.error("Expected %s to start with <%s>, but did not." % (self.val, prefix))
|
|
175
|
+
else:
|
|
176
|
+
raise TypeError("val is not a string or iterable")
|
|
177
|
+
return self
|
|
178
|
+
|
|
179
|
+
def ends_with(self, suffix) -> Self:
|
|
180
|
+
"""Asserts that val is string or iterable and ends with suffix.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
suffix: the suffix
|
|
184
|
+
|
|
185
|
+
Examples:
|
|
186
|
+
Usage::
|
|
187
|
+
|
|
188
|
+
assert_that('foo').ends_with('oo')
|
|
189
|
+
assert_that(['a', 'b', 'c']).ends_with('c')
|
|
190
|
+
assert_that((1, 2, 3)).ends_with(3)
|
|
191
|
+
assert_that(((1, 2), (3, 4), (5, 6))).ends_with((5, 6))
|
|
192
|
+
|
|
193
|
+
Returns:
|
|
194
|
+
AssertionBuilder: returns this instance to chain to the next assertion
|
|
195
|
+
|
|
196
|
+
Raises:
|
|
197
|
+
AssertionError: if val does **not** end with suffix
|
|
198
|
+
"""
|
|
199
|
+
if suffix is None:
|
|
200
|
+
raise TypeError("given suffix arg must not be none")
|
|
201
|
+
if isinstance(self.val, str):
|
|
202
|
+
if not isinstance(suffix, str):
|
|
203
|
+
raise TypeError("given suffix arg must be a string")
|
|
204
|
+
if len(suffix) == 0:
|
|
205
|
+
raise ValueError("given suffix arg must not be empty")
|
|
206
|
+
if not self.val.endswith(suffix):
|
|
207
|
+
return self.error("Expected <%s> to end with <%s>, but did not." % (self.val, suffix))
|
|
208
|
+
elif isinstance(self.val, collections.abc.Iterable):
|
|
209
|
+
if len(self.val) == 0:
|
|
210
|
+
raise ValueError("val must not be empty")
|
|
211
|
+
items = list(self.val)
|
|
212
|
+
if items[-1] != suffix:
|
|
213
|
+
return self.error("Expected %s to end with <%s>, but did not." % (self.val, suffix))
|
|
214
|
+
else:
|
|
215
|
+
raise TypeError("val is not a string or iterable")
|
|
216
|
+
return self
|
|
217
|
+
|
|
218
|
+
def matches(self, pattern) -> Self:
|
|
219
|
+
"""Asserts that val is string and matches the given regex pattern.
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
pattern (str): the regular expression pattern, as raw string (aka prefixed with ``r``)
|
|
223
|
+
|
|
224
|
+
Examples:
|
|
225
|
+
Usage::
|
|
226
|
+
|
|
227
|
+
assert_that('foo').matches(r'\\w')
|
|
228
|
+
assert_that('123-456-7890').matches(r'\\d{3}-\\d{3}-\\d{4}')
|
|
229
|
+
|
|
230
|
+
Match is partial unless anchored, so these assertion pass::
|
|
231
|
+
|
|
232
|
+
assert_that('foo').matches(r'\\w')
|
|
233
|
+
assert_that('foo').matches(r'oo')
|
|
234
|
+
assert_that('foo').matches(r'\\w{2}')
|
|
235
|
+
|
|
236
|
+
To match the entire string, just use an anchored regex pattern where ``^`` and ``$``
|
|
237
|
+
match the start and end of line and ``\\A`` and ``\\Z`` match the start and end of string::
|
|
238
|
+
|
|
239
|
+
assert_that('foo').matches(r'^\\w{3}$')
|
|
240
|
+
assert_that('foo').matches(r'\\A\\w{3}\\Z')
|
|
241
|
+
|
|
242
|
+
And regex flags, such as ``re.MULTILINE`` and ``re.DOTALL``, can only be applied via
|
|
243
|
+
*inline modifiers*, such as ``(?m)`` and ``(?s)``::
|
|
244
|
+
|
|
245
|
+
s = '''bar
|
|
246
|
+
foo
|
|
247
|
+
baz'''
|
|
248
|
+
|
|
249
|
+
# using multiline (?m)
|
|
250
|
+
assert_that(s).matches(r'(?m)^foo$')
|
|
251
|
+
|
|
252
|
+
# using dotall (?s)
|
|
253
|
+
assert_that(s).matches(r'(?s)b(.*)z')
|
|
254
|
+
|
|
255
|
+
Returns:
|
|
256
|
+
AssertionBuilder: returns this instance to chain to the next assertion
|
|
257
|
+
|
|
258
|
+
Raises:
|
|
259
|
+
AssertionError: if val does **not** match pattern
|
|
260
|
+
|
|
261
|
+
Tip:
|
|
262
|
+
Regular expressions are tricky. Be sure to use raw strings (aka prefixed with ``r``).
|
|
263
|
+
Also, note that the :meth:`matches` assertion passes for partial matches (as does the
|
|
264
|
+
underlying ``re.match`` method). So, if you need to match the entire string, you must
|
|
265
|
+
include anchors in the regex pattern.
|
|
266
|
+
"""
|
|
267
|
+
if not isinstance(self.val, str):
|
|
268
|
+
raise TypeError("val is not a string")
|
|
269
|
+
if not isinstance(pattern, str):
|
|
270
|
+
raise TypeError("given pattern arg must be a string")
|
|
271
|
+
if len(pattern) == 0:
|
|
272
|
+
raise ValueError("given pattern arg must not be empty")
|
|
273
|
+
if re.search(pattern, self.val) is None:
|
|
274
|
+
return self.error("Expected <%s> to match pattern <%s>, but did not." % (self.val, pattern))
|
|
275
|
+
return self
|
|
276
|
+
|
|
277
|
+
def does_not_match(self, pattern) -> Self:
|
|
278
|
+
"""Asserts that val is string and does not match the given regex pattern.
|
|
279
|
+
|
|
280
|
+
Args:
|
|
281
|
+
pattern (str): the regular expression pattern, as raw string (aka prefixed with ``r``)
|
|
282
|
+
|
|
283
|
+
Examples:
|
|
284
|
+
Usage::
|
|
285
|
+
|
|
286
|
+
assert_that('foo').does_not_match(r'\\d+')
|
|
287
|
+
assert_that('123').does_not_match(r'\\w+')
|
|
288
|
+
|
|
289
|
+
Returns:
|
|
290
|
+
AssertionBuilder: returns this instance to chain to the next assertion
|
|
291
|
+
|
|
292
|
+
Raises:
|
|
293
|
+
AssertionError: if val **does** match pattern
|
|
294
|
+
|
|
295
|
+
See Also:
|
|
296
|
+
:meth:`matches` - for more about regex patterns
|
|
297
|
+
"""
|
|
298
|
+
if not isinstance(self.val, str):
|
|
299
|
+
raise TypeError("val is not a string")
|
|
300
|
+
if not isinstance(pattern, str):
|
|
301
|
+
raise TypeError("given pattern arg must be a string")
|
|
302
|
+
if len(pattern) == 0:
|
|
303
|
+
raise ValueError("given pattern arg must not be empty")
|
|
304
|
+
if re.search(pattern, self.val) is not None:
|
|
305
|
+
return self.error("Expected <%s> to not match pattern <%s>, but did." % (self.val, pattern))
|
|
306
|
+
return self
|
|
307
|
+
|
|
308
|
+
def is_alpha(self) -> Self:
|
|
309
|
+
"""Asserts that val is non-empty string and all characters are alphabetic (using ``str.isalpha()``).
|
|
310
|
+
|
|
311
|
+
Examples:
|
|
312
|
+
Usage::
|
|
313
|
+
|
|
314
|
+
assert_that('foo').is_alpha()
|
|
315
|
+
|
|
316
|
+
Returns:
|
|
317
|
+
AssertionBuilder: returns this instance to chain to the next assertion
|
|
318
|
+
|
|
319
|
+
Raises:
|
|
320
|
+
AssertionError: if val is **not** alphabetic
|
|
321
|
+
"""
|
|
322
|
+
if not isinstance(self.val, str):
|
|
323
|
+
raise TypeError("val is not a string")
|
|
324
|
+
if len(self.val) == 0:
|
|
325
|
+
raise ValueError("val is empty")
|
|
326
|
+
if not self.val.isalpha():
|
|
327
|
+
return self.error("Expected <%s> to contain only alphabetic chars, but did not." % self.val)
|
|
328
|
+
return self
|
|
329
|
+
|
|
330
|
+
def is_digit(self) -> Self:
|
|
331
|
+
"""Asserts that val is non-empty string and all characters are digits (using ``str.isdigit()``).
|
|
332
|
+
|
|
333
|
+
Examples:
|
|
334
|
+
Usage::
|
|
335
|
+
|
|
336
|
+
assert_that('1234567890').is_digit()
|
|
337
|
+
|
|
338
|
+
Returns:
|
|
339
|
+
AssertionBuilder: returns this instance to chain to the next assertion
|
|
340
|
+
|
|
341
|
+
Raises:
|
|
342
|
+
AssertionError: if val is **not** digits
|
|
343
|
+
"""
|
|
344
|
+
if not isinstance(self.val, str):
|
|
345
|
+
raise TypeError("val is not a string")
|
|
346
|
+
if len(self.val) == 0:
|
|
347
|
+
raise ValueError("val is empty")
|
|
348
|
+
if not self.val.isdigit():
|
|
349
|
+
return self.error("Expected <%s> to contain only digits, but did not." % self.val)
|
|
350
|
+
return self
|
|
351
|
+
|
|
352
|
+
def is_lower(self) -> Self:
|
|
353
|
+
"""Asserts that val is non-empty string and all characters are lowercase (using ``str.lower()``).
|
|
354
|
+
|
|
355
|
+
Examples:
|
|
356
|
+
Usage::
|
|
357
|
+
|
|
358
|
+
assert_that('foo').is_lower()
|
|
359
|
+
|
|
360
|
+
Returns:
|
|
361
|
+
AssertionBuilder: returns this instance to chain to the next assertion
|
|
362
|
+
|
|
363
|
+
Raises:
|
|
364
|
+
AssertionError: if val is **not** lowercase
|
|
365
|
+
"""
|
|
366
|
+
if not isinstance(self.val, str):
|
|
367
|
+
raise TypeError("val is not a string")
|
|
368
|
+
if len(self.val) == 0:
|
|
369
|
+
raise ValueError("val is empty")
|
|
370
|
+
if self.val != self.val.lower():
|
|
371
|
+
return self.error("Expected <%s> to contain only lowercase chars, but did not." % self.val)
|
|
372
|
+
return self
|
|
373
|
+
|
|
374
|
+
def is_upper(self) -> Self:
|
|
375
|
+
"""Asserts that val is non-empty string and all characters are uppercase (using ``str.upper()``).
|
|
376
|
+
|
|
377
|
+
Examples:
|
|
378
|
+
Usage::
|
|
379
|
+
|
|
380
|
+
assert_that('FOO').is_upper()
|
|
381
|
+
|
|
382
|
+
Returns:
|
|
383
|
+
AssertionBuilder: returns this instance to chain to the next assertion
|
|
384
|
+
|
|
385
|
+
Raises:
|
|
386
|
+
AssertionError: if val is **not** uppercase
|
|
387
|
+
"""
|
|
388
|
+
if not isinstance(self.val, str):
|
|
389
|
+
raise TypeError("val is not a string")
|
|
390
|
+
if len(self.val) == 0:
|
|
391
|
+
raise ValueError("val is empty")
|
|
392
|
+
if self.val != self.val.upper():
|
|
393
|
+
return self.error("Expected <%s> to contain only uppercase chars, but did not." % self.val)
|
|
394
|
+
return self
|
|
395
|
+
|
|
396
|
+
def is_unicode(self) -> Self:
|
|
397
|
+
"""Asserts that val is a unicode string.
|
|
398
|
+
|
|
399
|
+
Examples:
|
|
400
|
+
Usage::
|
|
401
|
+
|
|
402
|
+
assert_that(u'foo').is_unicode() # python 2
|
|
403
|
+
assert_that('foo').is_unicode() # python 3
|
|
404
|
+
|
|
405
|
+
Returns:
|
|
406
|
+
AssertionBuilder: returns this instance to chain to the next assertion
|
|
407
|
+
|
|
408
|
+
Raises:
|
|
409
|
+
AssertionError: if val is **not** a unicode string
|
|
410
|
+
"""
|
|
411
|
+
if not isinstance(self.val, str):
|
|
412
|
+
return self.error("Expected <%s> to be unicode, but was <%s>." % (self.val, type(self.val).__name__))
|
|
413
|
+
return self
|