Source

fudge / fudge / inspector.py

Full commit
  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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551

"""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', 'arg_not']

class ValueInspector(object):
    """Dispatches tests to inspect values.
    """

    invert_eq = False

    def _make_value_test(self, test_class, *args, **kwargs):
        if not self.invert_eq:
            return test_class(*args, **kwargs)
        class ValueTestInverter(test_class):
            def __repr__(wrapper_self):
                return "(NOT) %s" % test_class.__repr__(wrapper_self)
            def __eq__(wrapper_self, other):
                return not test_class.__eq__(wrapper_self, other)
        return ValueTestInverter(*args, **kwargs)

    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()

        The arg_not version will not match anything and is probably not very
        useful.

        .. doctest::

            >>> import fudge
            >>> from fudge.inspector import arg_not
            >>> query = fudge.Fake('query').expects_call().with_args(
            ...     arg_not.any()
            ... )
            >>> query('asdf')
            Traceback (most recent call last):
            ...
            AssertionError: fake:query((NOT) arg.any()) was called unexpectedly with args ('asdf')
            >>> query()
            Traceback (most recent call last):
            ...
            AssertionError: fake:query((NOT) arg.any()) was called unexpectedly with args ()

        .. doctest::
            :hide:

            >>> fudge.clear_expectations()

        """
        return self._make_value_test(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()',
                      DeprecationWarning, 3)
        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()

        arg_not.contains matches an argument not containing some element.

        .. doctest::

            >>> from fudge.inspector import arg_not
            >>> colorpicker = colorpicker.expects('select').with_args(arg_not.contains('blue'))
            >>> colorpicker.select('reddish')
            >>> colorpicker.select(['red', 'green'])
            >>> fudge.verify()

            >>> colorpicker.select('blue-green')
            Traceback (most recent call last):
            ...
            AssertionError: fake:colorpicker.select(arg.contains('red'))[0] was called unexpectedly with args ('blue-green')
            >>> colorpicker.select(['red', 'blue', 'green'])
            Traceback (most recent call last):
            ...
            AssertionError: fake:colorpicker.select((NOT) arg.contains('blue'))[1] was called unexpectedly with args (['red', 'blue', 'green'])

        .. doctest::
            :hide:

            >>> fudge.clear_expectations()

        """
        return self._make_value_test(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()

        The arg_not version works as expected, matching arguments that do not
        end with the given element.

        .. doctest::

            >>> from fudge.inspector import arg_not
            >>> query = fudge.Fake('query').expects_call().with_args(arg_not.endswith('Ringo'))
            >>> query('John, Paul, George and Steve')
            >>> fudge.verify()

        .. doctest::
            :hide:

            >>> fudge.clear_expectations()

        """
        return self._make_value_test(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'})

        When called as a method on arg_not, has_attr does the opposite, and
        ensures that the argument does not have the specified attributes.

        .. doctest::

            >>> from fudge.inspector import arg_not
            >>> class User:
            ...     first_name = 'Bob'
            ...     last_name = 'Dobbs'
            >>> query = fudge.Fake('query').expects_call().with_args(
            ...     arg_not.has_attr(first_name='James')
            ... )
            >>> query(User())
            >>> fudge.verify()

        .. doctest::
            :hide:

            >>> fudge.clear_expectations()

        """
        return self._make_value_test(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()

        Using the inverted version, arg_not.passes_test, asserts that the
        argument does not pass the provided test.

        .. doctest::

            >>> from fudge.inspector import arg_not
            >>> query = fudge.Fake('query').expects_call().with_args(
            ...     arg_not.passes_test(lambda x: x > 10)
            ... )
            >>> query(5)
            >>> fudge.verify()

        .. doctest::
            :hide:

            >>> fudge.clear_expectations()

        """
        return self._make_value_test(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()

        Using arg_not.startswith instead ensures that arguments do not start
        with that part.

        .. doctest::

            >>> from fudge.inspector import arg_not
            >>> query = fudge.Fake('query').expects_call().with_args(
            ...     arg_not.startswith('asdf')
            ... )
            >>> query('qwerty')
            >>> fudge.verify()

        .. doctest::
            :hide:

            >>> fudge.clear_expectations()

        """
        return self._make_value_test(Startswith, part)

class NotValueInspector(ValueInspector):
    """Inherits all the argument methods from ValueInspector, but inverts them
    to expect the opposite. See the ValueInspector method docstrings for
    examples.
    """

    invert_eq = True

    def __call__(self, thing):
        """This will match any value except the argument given.

        .. doctest::

            >>> import fudge
            >>> from fudge.inspector import arg, arg_not
            >>> query = fudge.Fake('query').expects_call().with_args(
            ...     arg.any(),
            ...     arg_not('foobar')
            ... )
            >>> query([1, 2, 3], 'asdf')
            >>> query('asdf', 'foobar')
            Traceback (most recent call last):
            ...
            AssertionError: fake:query(arg.any(), arg_not(foobar)) was called unexpectedly with args ('asdf', 'foobar')

        .. doctest::
            :hide:

            >>> fudge.clear_expectations()

        """
        return NotValue(thing)

arg = ValueInspector()
arg_not = NotValueInspector()

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))

class NotValue(ValueTest):
    def __init__(self, item):
        self.item = item

    def __eq__(self, other):
        return not self.item == other

    def _repr_argspec(self):
        return "arg_not(%s)" % self.item