/usr/share/pyshared/fudge/inspector.py is in python-fudge 1.0.3-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 | """Value inspectors that can be passed to :func:`fudge.Fake.with_args` for more
expressive argument matching.
As a mnemonic device,
an instance of the :class:`fudge.inspector.ValueInspector` is available as "arg" :
.. doctest::
>>> import fudge
>>> from fudge.inspector import arg
>>> image = fudge.Fake("image").expects("save").with_args(arg.endswith(".jpg"))
In other words, this declares that the first argument to ``image.save()``
should end with the suffix ".jpg"
.. doctest::
:hide:
>>> fudge.clear_expectations()
"""
import warnings
from fudge.util import fmt_val, fmt_dict_vals
__all__ = ['arg']
class ValueInspector(object):
"""Dispatches tests to inspect values.
"""
def any(self):
"""Match any value.
This is pretty much just a placeholder for when you
want to inspect multiple arguments but don't care about
all of them.
.. doctest::
>>> import fudge
>>> from fudge.inspector import arg
>>> db = fudge.Fake("db")
>>> db = db.expects("transaction").with_args(
... "insert", isolation_level=arg.any())
...
>>> db.transaction("insert", isolation_level="lock")
>>> fudge.verify()
This also passes:
.. doctest::
:hide:
>>> fudge.clear_calls()
.. doctest::
>>> db.transaction("insert", isolation_level="autocommit")
>>> fudge.verify()
.. doctest::
:hide:
>>> fudge.clear_expectations()
"""
return AnyValue()
def any_value(self):
"""**DEPRECATED**: use :func:`arg.any() <fudge.inspector.ValueInspector.any>`
"""
warnings.warn('arg.any_value() is deprecated in favor of arg.any()')
return self.any()
def contains(self, part):
"""Ensure that a value contains some part.
This is useful for when you only care that a substring or subelement
exists in a value.
.. doctest::
>>> import fudge
>>> from fudge.inspector import arg
>>> addressbook = fudge.Fake().expects("import_").with_args(
... arg.contains("Baba Brooks"))
...
>>> addressbook.import_("Bill Brooks; Baba Brooks; Henry Brooks;")
>>> fudge.verify()
.. doctest::
:hide:
>>> fudge.clear_expectations()
Since contains() just invokes the __in__() method, checking that a list
item is present works as expected :
.. doctest::
>>> colorpicker = fudge.Fake("colorpicker")
>>> colorpicker = colorpicker.expects("select").with_args(arg.contains("red"))
>>> colorpicker.select(["green","red","blue"])
>>> fudge.verify()
.. doctest::
:hide:
>>> fudge.clear_expectations()
"""
return Contains(part)
def endswith(self, part):
"""Ensure that a value ends with some part.
This is useful for when values with dynamic parts that are hard to replicate.
.. doctest::
>>> import fudge
>>> from fudge.inspector import arg
>>> tmpfile = fudge.Fake("tempfile").expects("mkname").with_args(
... arg.endswith(".tmp"))
...
>>> tmpfile.mkname("7AakkkLazUUKHKJgh908JKjlkh.tmp")
>>> fudge.verify()
.. doctest::
:hide:
>>> fudge.clear_expectations()
"""
return Endswith(part)
def has_attr(self, **attributes):
"""Ensure that an object value has at least these attributes.
This is useful for testing that an object has specific attributes.
.. doctest::
>>> import fudge
>>> from fudge.inspector import arg
>>> db = fudge.Fake("db").expects("update").with_args(arg.has_attr(
... first_name="Bob",
... last_name="James" ))
...
>>> class User:
... first_name = "Bob"
... last_name = "James"
... job = "jazz musician" # this is ignored
...
>>> db.update(User())
>>> fudge.verify()
In case of error, the other object's __repr__ will be invoked:
.. doctest::
:hide:
>>> fudge.clear_calls()
.. doctest::
>>> class User:
... first_name = "Bob"
...
... def __repr__(self):
... return repr(dict(first_name=self.first_name))
...
>>> db.update(User())
Traceback (most recent call last):
...
AssertionError: fake:db.update(arg.has_attr(first_name='Bob', last_name='James')) was called unexpectedly with args ({'first_name': 'Bob'})
.. doctest::
:hide:
>>> fudge.clear_expectations()
"""
return HasAttr(**attributes)
def passes_test(self, test):
"""Check that a value passes some test.
For custom assertions you may need to create your own callable
to inspect and verify a value.
.. doctest::
>>> def is_valid(s):
... if s in ('active','deleted'):
... return True
... else:
... return False
...
>>> import fudge
>>> from fudge.inspector import arg
>>> system = fudge.Fake("system")
>>> system = system.expects("set_status").with_args(arg.passes_test(is_valid))
>>> system.set_status("active")
>>> fudge.verify()
.. doctest::
:hide:
>>> fudge.clear_calls()
The callable you pass takes one argument, the value, and should return
True if it's an acceptable value or False if not.
.. doctest::
>>> system.set_status("sleep") # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AssertionError: fake:system.set_status(arg.passes_test(<function is_valid at...)) was called unexpectedly with args ('sleep')
.. doctest::
:hide:
>>> fudge.clear_expectations()
If it makes more sense to perform assertions in your test function then
be sure to return True :
>>> def is_valid(s):
... assert s in ('active','deleted'), (
... "Unexpected status value: %s" % s)
... return True
...
>>> import fudge
>>> from fudge.inspector import arg
>>> system = fudge.Fake("system")
>>> system = system.expects("set_status").with_args(arg.passes_test(is_valid))
>>> system.set_status("sleep")
Traceback (most recent call last):
...
AssertionError: Unexpected status value: sleep
.. doctest::
:hide:
>>> fudge.clear_expectations()
"""
return PassesTest(test)
def startswith(self, part):
"""Ensure that a value starts with some part.
This is useful for when values with dynamic parts that are hard to replicate.
.. doctest::
>>> import fudge
>>> from fudge.inspector import arg
>>> keychain = fudge.Fake("keychain").expects("accept_key").with_args(
... arg.startswith("_key"))
...
>>> keychain.accept_key("_key-18657yojgaodfty98618652olkj[oollk]")
>>> fudge.verify()
.. doctest::
:hide:
>>> fudge.clear_expectations()
"""
return Startswith(part)
arg = ValueInspector()
class ValueTest(object):
arg_method = None
__test__ = False # nose
def __eq__(self, other):
raise NotImplementedError()
def _repr_argspec(self):
raise NotImplementedError()
def __str__(self):
return self._repr_argspec()
def __unicode__(self):
return self._repr_argspec()
def __repr__(self):
return self._repr_argspec()
def _make_argspec(self, arg):
if self.arg_method is None:
raise NotImplementedError(
"%r must have set attribute arg_method" % self.__class__)
return "arg." + self.arg_method + "(" + arg + ")"
class Stringlike(ValueTest):
def __init__(self, part):
self.part = part
def _repr_argspec(self):
return self._make_argspec(fmt_val(self.part))
def stringlike(self, value):
if isinstance(value, (str, unicode)):
return value
else:
return str(value)
def __eq__(self, other):
check_stringlike = getattr(self.stringlike(other), self.arg_method)
return check_stringlike(self.part)
class Startswith(Stringlike):
arg_method = "startswith"
class Endswith(Stringlike):
arg_method = "endswith"
class HasAttr(ValueTest):
arg_method = "has_attr"
def __init__(self, **attributes):
self.attributes = attributes
def _repr_argspec(self):
return self._make_argspec(", ".join(sorted(fmt_dict_vals(self.attributes))))
def __eq__(self, other):
for name, value in self.attributes.items():
if not hasattr(other, name):
return False
if getattr(other, name) != value:
return False
return True
class AnyValue(ValueTest):
arg_method = "any"
def __eq__(self, other):
# will match anything:
return True
def _repr_argspec(self):
return self._make_argspec("")
class Contains(ValueTest):
arg_method = "contains"
def __init__(self, part):
self.part = part
def _repr_argspec(self):
return self._make_argspec(fmt_val(self.part))
def __eq__(self, other):
if self.part in other:
return True
else:
return False
class PassesTest(ValueTest):
arg_method = "passes_test"
def __init__(self, test):
self.test = test
def __eq__(self, other):
return self.test(other)
def _repr_argspec(self):
return self._make_argspec(repr(self.test))
|