Debian Codegraph @

sure/__init__.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # <sure - utility belt for automated testing in python>
3 # Copyright (C) <2010-2023> Gabriel Falcão <[email protected]>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 from __future__ import unicode_literals
18
19 import re
20 import os
21 import sys
22
23 import difflib
24 import inspect
25 import traceback
26
27 from functools import wraps, partial
28 from datetime import datetime
29
30 from six import string_types, text_type, PY2, get_function_code
31 from six.moves import reduce
32
33 from sure.old import AssertionHelper
34 from sure.old import Iterable
35 from sure.old import builtins
36
37 from sure.core import DeepComparison
38 from sure.core import DeepExplanation
39 from sure.core import _get_file_name
40 from sure.core import _get_line_number
41 from sure.core import safe_repr
42 from sure.core import anything # noqa
43
44 from sure.magic import is_cpython, patchable_builtin
45 from sure.registry import context as _registry
46
47
48 if not PY2:
49 basestring = str
50
51 version = "1.4.11"
52
53
54 not_here_error = (
55 "you have tried to access the attribute %r from the context "
56 "(aka VariablesBag), but there is no such attribute assigned to it. "
57 "Maybe you misspelled it ? Well, here are the options: %s"
58 )
59
60
61 original_obj_attrs = dir(object)
62
63
64 class VariablesBag(dict):
65 __varnames__ = None
66 __sure_actions_ran__ = None
67 __sure_action_results__ = None
68 __sure_providers_of__ = None
69
70 def __init__(self, *args, **kw):
71 self.__varnames__ = []
72 self.__sure_actions_ran__ = []
73 self.__sure_action_results__ = []
74 self.__sure_providers_of__ = {}
75 return super(VariablesBag, self).__init__(*args, **kw)
76
77 def __setattr__(self, attr, value):
78 if attr not in dir(VariablesBag):
79 self[attr] = value
80 self.__varnames__.append(attr)
81 return super(VariablesBag, self).__setattr__(attr, value)
82
83 def __getattr__(self, attr):
84 try:
85 return super(VariablesBag, self).__getattribute__(attr)
86 except AttributeError:
87 if attr not in dir(VariablesBag):
88 raise AssertionError(
89 not_here_error
90 % (
91 attr,
92 safe_repr(self.__varnames__),
93 )
94 )
95
96
97 def ensure_type(caller_name, cast, obj):
98 try:
99 return cast(obj)
100 except TypeError:
101 raise AssertionError("{0} tried to ")
102
103
104 class CallBack(object):
105 context_error = (
106 "the function %s defined at %s line %d, is being "
107 "decorated by either @that_with_context or @scenario, so it should "
108 "take at least 1 parameter, which is the test context"
109 )
110
111 def __init__(self, cb, args, kwargs):
112 self.callback = cb
113 self.args = args or []
114 self.kwargs = kwargs or {}
115 self.callback_name = cb.__name__
116 self.callback_filename = os.path.split(get_function_code(cb).co_filename)[-1]
117 self.callback_lineno = get_function_code(cb).co_firstlineno + 1
118
119 def apply(self, *optional_args):
120 args = list(optional_args)
121 args.extend(self.args)
122 try:
123 return self.callback(*args, **self.kwargs)
124 except Exception:
125 exc_klass, exc_value, tb = sys.exc_info()
126 err = traceback.format_exc().splitlines()[-1]
127 err = err.replace("{0}:".format(exc_klass.__name__), "").strip()
128
129 if err.startswith(self.callback_name) and (
130 "takes no arguments (1 given)" in err) or \
131 "takes 0 positional arguments but 1 was given" in err:
132 raise TypeError(
133 self.context_error
134 % (
135 self.callback_name,
136 self.callback_filename,
137 self.callback_lineno,
138 )
139 )
140 raise
141
142
143 def that_with_context(setup=None, teardown=None):
144 def dec(func):
145 @wraps(func)
146 def wrap(*args, **kw):
147 context = VariablesBag()
148
149 if callable(setup):
150 cb = CallBack(setup, args, kw)
151 cb.apply(context)
152
153 elif isinstance(setup, Iterable):
154 for s in setup:
155 cb = CallBack(s, args, kw)
156 cb.apply(context)
157
158 test = CallBack(func, args, kw)
159 try:
160 res = test.apply(context)
161 finally:
162 if callable(teardown):
163 cb = CallBack(teardown, args, kw)
164 cb.apply(context)
165
166 elif isinstance(teardown, Iterable):
167 for s in teardown:
168 cb = CallBack(s, args, kw)
169 cb.apply(context)
170
171 return res
172
173 return wrap
174
175 return dec
176
177
178 scenario = that_with_context
179
180
181 def within(**units):
182 assert len(units) == 1, "use within(number=unit). e.g.: within(one=second)"
183
184 word, unit = list(units.items())[0]
185 value = word_to_number(word)
186
187 convert_from, convert_to = UNITS[unit]
188 timeout = convert_from(value)
189 exc = []
190
191 def dec(func):
192 def wrap(*args, **kw):
193 start = datetime.utcnow()
194
195 try:
196 func(start, *args, **kw)
197 except TypeError as e:
198 if PY2:
199 # PY2 has different error message
200 fmt = "{0}() takes no arguments"
201 else:
202 fmt = "{0}() takes 0 positional arguments but 1 was given"
203 err = text_type(e)
204 if fmt.format(func.__name__) in err:
205 func(*args, **kw)
206 else:
207 exc.append(traceback.format_exc())
208
209 except Exception as e:
210 exc.append(traceback.format_exc())
211
212 end = datetime.utcnow()
213 delta = end - start
214 took = convert_to(delta.microseconds)
215 print(took, timeout)
216 assert took < timeout, "%s did not run within %s %s" % (
217 func.__name__,
218 word,
219 unit,
220 )
221 if exc:
222 raise AssertionError(exc.pop(0))
223
224 wrap.__name__ = func.__name__
225 wrap.__doc__ = func.__doc__
226 wrap.__dict__ = func.__dict__
227 return wrap
228
229 return dec
230
231
232 UNITS = {
233 "minutes": (
234 lambda from_num: from_num / 60.0,
235 lambda to_num: to_num * 6000000,
236 ),
237 "seconds": (
238 lambda from_num: from_num,
239 lambda to_num: to_num / 100000,
240 ),
241 "miliseconds": (
242 lambda from_num: from_num * 1000,
243 lambda to_num: to_num / 100,
244 ),
245 "microseconds": (
246 lambda from_num: from_num * 100000,
247 lambda to_num: to_num,
248 ),
249 }
250
251 milisecond = miliseconds = "miliseconds"
252 microsecond = microseconds = "microseconds"
253 second = seconds = "seconds"
254 minute = minutes = "minutes"
255
256
257 def word_to_number(word):
258 basic = {
259 "one": 1,
260 "two": 2,
261 "three": 3,
262 "four": 4,
263 "five": 5,
264 "six": 6,
265 "seven": 7,
266 "eight": 8,
267 "nine": 9,
268 "ten": 10,
269 "eleven": 11,
270 "twelve": 12,
271 }
272 try:
273 return basic[word]
274 except KeyError:
275 raise AssertionError(
276 "sure supports only literal numbers from one to twelve, "
277 'you tried the word "twenty"'
278 )
279
280
281 def action_for(context, provides=None, depends_on=None):
282 if not provides:
283 provides = []
284
285 if not depends_on:
286 depends_on = []
287
288 def register_providers(func, attr):
289 if re.search(r"^[{]\d+[}]$", attr):
290 return # ignore dynamically declared provides
291
292 if not attr in context.__sure_providers_of__:
293 context.__sure_providers_of__[attr] = []
294
295 context.__sure_providers_of__[attr].append(func)
296
297 def register_dynamic_providers(func, attr, args, kwargs):
298 found = re.search(r"^[{](\d+)[}]$", attr)
299 if not found:
300 return # ignore dynamically declared provides
301
302 index = int(found.group(1))
303 assert index < len(args), (
304 "the dynamic provider index: {%d} is bigger than %d, which is "
305 "the length of the positional arguments passed to %s"
306 % (index, len(args), func.__name__)
307 )
308
309 attr = args[index]
310
311 if not attr in context.__sure_providers_of__:
312 context.__sure_providers_of__[attr] = []
313
314 context.__sure_providers_of__[attr].append(func)
315
316 def ensure_providers(func, attr, args, kwargs):
317 found = re.search(r"^[{](\d+)[}]$", attr)
318 if found:
319 index = int(found.group(1))
320 attr = args[index]
321
322 assert attr in context, (
323 'the action "%s" was supposed to provide the attribute "%s" '
324 "into the context, but it did not. Please double check its "
325 "implementation" % (func.__name__, attr)
326 )
327
328 dependency_error_lonely = (
329 'the action "%s" defined at %s:%d '
330 'depends on the attribute "%s" to be available in the'
331 " context. It turns out that there are no actions providing "
332 "that. Please double-check the implementation"
333 )
334
335 dependency_error_hints = (
336 'the action "%s" defined at %s:%d '
337 'depends on the attribute "%s" to be available in the context.'
338 " You need to call one of the following actions beforehand:\n"
339 )
340
341 def check_dependencies(func):
342 action = func.__name__
343 filename = _get_file_name(func)
344 lineno = _get_line_number(func)
345
346 for dependency in depends_on:
347 if dependency in context.__sure_providers_of__:
348 providers = context.__sure_providers_of__[dependency]
349 err = dependency_error_hints % (
350 action,
351 filename,
352 lineno,
353 dependency,
354 )
355 err += "\n".join(
356 [
357 " -> %s at %s:%d"
358 % (p.__name__, _get_file_name(p), _get_line_number(p))
359 for p in providers
360 ]
361 )
362
363 else:
364 err = dependency_error_lonely % (
365 action,
366 filename,
367 lineno,
368 dependency,
369 )
370
371 assert dependency in context, err
372
373 def decorate_and_absorb(func):
374 [register_providers(func, attr) for attr in provides]
375
376 @wraps(func)
377 def wrapper(*args, **kw):
378 [register_dynamic_providers(func, attr, args, kw) for attr in provides]
379 context.__sure_actions_ran__.append((func, args, kw))
380 check_dependencies(func)
381 result = func(*args, **kw)
382 [ensure_providers(func, attr, args, kw) for attr in provides]
383 context.__sure_action_results__.append(result)
384 return context
385
386 setattr(context, func.__name__, wrapper)
387 return wrapper
388
389 return decorate_and_absorb
390
391
392 def work_in_progress(func):
393 @wraps(func)
394 def wrapper(*args, **kwargs):
395 _registry["is_running"] = True
396 ret = func(*args, **kwargs)
397 _registry["is_running"] = False
398 return ret
399
400 return wrapper
401
402
403 def assertionmethod(func):
404 @wraps(func)
405 def wrapper(self, *args, **kw):
406 try:
407 value = func(self, *args, **kw)
408 except AssertionError as e:
409 raise AssertionError(e)
410
411 msg = "{0}({1}) failed".format(
412 func.__name__,
413 ", ".join(map(safe_repr, args)),
414 ", ".join(["{0}={1}".format(k, safe_repr(kw[k])) for k in kw]),
415 )
416 if PY2:
417 msg = text_type(msg)
418
419 assert value, msg
420 return value
421
422 return wrapper
423
424
425 def assertionproperty(func):
426 return builtins.property(assertionmethod(func))
427
428
429 POSITIVES = [
430 "should",
431 "does",
432 "do",
433 "must",
434 "when",
435 ]
436
437 NEGATIVES = [
438 "shouldnt",
439 "dont",
440 "do_not",
441 "doesnt",
442 "does_not",
443 "doesnot",
444 "should_not",
445 "shouldnot",
446 ]
447
448
449 class IdentityAssertion(object):
450 def __init__(self, assertion_builder):
451 self._ab = assertion_builder
452
453 def __call__(self, other):
454 if self._ab.negative:
455 assert (
456 self._ab.obj is not other
457 ), "{0} should not be the same object as {1}, but it is".format(
458 self._ab.obj, other
459 )
460 return True
461 assert (
462 self._ab.obj is other
463 ), "{0} should be the same object as {1}, but it is not".format(
464 self._ab.obj, other
465 )
466 return True
467
468 def __getattr__(self, name):
469 return getattr(self._ab, name)
470
471
472 class AssertionBuilder(object):
473 def __init__(
474 self, name=None, negative=False, obj=None, callable_args=None, callable_kw=None
475 ):
476 self._name = name
477 self.negative = negative
478
479 self.obj = obj
480 self._callable_args = callable_args or []
481 self._callable_kw = callable_kw or {}
482 self._that = AssertionHelper(self.obj)
483
484 def __call__(self, obj):
485
486 self.obj = obj
487
488 if isinstance(obj, self.__class__):
489 self.obj = obj.obj
490 self._callable_args = obj._callable_args
491 self._callable_kw = obj._callable_kw
492
493 self._that = AssertionHelper(self.obj)
494 return self
495
496 def __getattr__(self, attr):
497 special_case = False
498 special_case = attr in (POSITIVES + NEGATIVES)
499
500 negative = attr in NEGATIVES
501
502 if special_case:
503 return AssertionBuilder(
504 attr,
505 negative=negative,
506 obj=self.obj,
507 callable_args=self._callable_args,
508 callable_kw=self._callable_kw,
509 )
510
511 return super(AssertionBuilder, self).__getattribute__(attr)
512
513 @assertionproperty
514 def callable(self):
515 if self.negative:
516 assert not callable(
517 self.obj
518 ), "expected `{0}` to not be callable but it is".format(safe_repr(self.obj))
519 else:
520 assert callable(self.obj), "expected {0} to be callable".format(
521 safe_repr(self.obj)
522 )
523
524 return True
525
526 @assertionproperty
527 def be(self):
528 return IdentityAssertion(self)
529
530 being = be
531
532 @assertionproperty
533 def not_be(self):
534 return IdentityAssertion(self.should_not)
535
536 not_being = not_be
537
538 @assertionproperty
539 def not_have(self):
540 return self.should_not
541
542 @assertionproperty
543 def to_not(self):
544 return self.should_not
545
546 @assertionproperty
547 def to(self):
548 return self
549
550 which = to
551
552 @assertionproperty
553 def when(self):
554 return self
555
556 @assertionproperty
557 def have(self):
558 return self
559
560 @assertionproperty
561 def with_value(self):
562 return self
563
564 def property(self, name):
565 has_it = hasattr(self.obj, name)
566 if self.negative:
567 assert (
568 not has_it
569 ), "%r should not have the property `%s`, " "but it is %r" % (
570 self.obj,
571 name,
572 getattr(self.obj, name),
573 )
574 return True
575
576 assert has_it, "%r should have the property `%s` but does not" % (
577 self.obj,
578 name,
579 )
580 return expect(getattr(self.obj, name))
581
582 def key(self, name):
583 has_it = name in self.obj
584 if self.negative:
585 assert not has_it, "%r should not have the key `%s`, " "but it is %r" % (
586 self.obj,
587 name,
588 self.obj[name],
589 )
590 return True
591
592 assert has_it, "%r should have the key `%s` but does not" % (self.obj, name)
593
594 return expect(self.obj[name])
595
596 @assertionproperty
597 def empty(self):
598 representation = safe_repr(self.obj)
599 length = len(self.obj)
600 if self.negative:
601 assert length > 0, "expected `{0}` to not be empty".format(representation)
602 else:
603 assert (
604 length == 0
605 ), "expected `{0}` to be empty but it has {1} items".format(
606 representation, length
607 )
608
609 return True
610
611 @assertionproperty
612 def ok(self):
613 if self.negative:
614 msg = "expected `{0}` to be falsy".format(self.obj)
615 assert not bool(self.obj), msg
616 else:
617 msg = "expected `{0}` to be truthy".format(self.obj)
618 assert bool(self.obj), msg
619
620 return True
621
622 truthy = ok
623 true = ok
624
625 @assertionproperty
626 def falsy(self):
627 if self.negative:
628 msg = "expected `{0}` to be truthy".format(self.obj)
629 assert bool(self.obj), msg
630 else:
631 msg = "expected `{0}` to be falsy".format(self.obj)
632 assert not bool(self.obj), msg
633
634 return True
635
636 false = falsy
637
638 @assertionproperty
639 def none(self):
640 if self.negative:
641 assert self.obj is not None, r"expected `{0}` to not be None".format(
642 self.obj
643 )
644 else:
645 assert self.obj is None, r"expected `{0}` to be None".format(self.obj)
646
647 return True
648
649 @assertionmethod
650 def within_range(self, start, end):
651 start = ensure_type("within_range", int, start)
652 end = ensure_type("within_range", int, end)
653 subject = ensure_type("within_range", int, self.obj)
654 is_within_range = subject >= start and subject <= end
655
656 if self.negative:
657 if is_within_range:
658 raise AssertionError(
659 "expected {0} to NOT be within {1} and {2}".format(
660 subject, start, end
661 )
662 )
663 return not is_within_range
664
665 else:
666 if not is_within_range:
667 raise AssertionError(
668 "expected {0} to be within {1} and {2}".format(subject, start, end)
669 )
670 return is_within_range
671
672 @assertionmethod
673 def within(self, first, *rest):
674 if isinstance(first, Iterable):
675 collection_should = AssertionHelper(first)
676 if self.negative:
677 return collection_should.does_not_contain(self.obj)
678 else:
679 return collection_should.contains(self.obj)
680
681 elif len(rest) == 1:
682 return self.within_range(first, rest[0])
683 else:
684 if self.negative:
685 ppath = "{0}.should_not.be.within".format(self.obj)
686 else:
687 ppath = "{0}.should.be.within".format(self.obj)
688
689 raise AssertionError(
690 (
691 "{0}({1}, {2}) must be called with either a iterable:\n"
692 "{0}([1, 2, 3, 4])\n"
693 "or with a range of numbers:"
694 "{0}(1, 3000)"
695 ).format(ppath, first, ", ".join([repr(x) for x in rest]))
696 )
697
698 @assertionmethod
699 def equal(self, what, epsilon=None):
700 """compares given object ``X`` with an expected ``Y`` object.
701
702 It primarily assures that the compared objects are absolute equal ``==``.
703
704 :param what: the expected value
705 :param epsilon: a delta to leverage upper-bound floating point permissiveness
706 """
707
708 try:
709 comparison = DeepComparison(self.obj, what, epsilon).compare()
710 error = False
711 except AssertionError as e:
712 error = e
713 comparison = None
714
715 if isinstance(comparison, DeepExplanation):
716 error = comparison.get_assertion(self.obj, what)
717
718 if self.negative:
719 if error:
720 return True
721
722 msg = "%s should differ from %s, but is the same thing"
723 raise AssertionError(msg % (safe_repr(self.obj), safe_repr(what)))
724
725 else:
726 if not error:
727 return True
728 raise error
729
730 eql = equal
731 equals = equal
732 equal_to = equal
733
734 @assertionmethod
735 def different_of(self, what):
736 differ = difflib.Differ()
737
738 source = self.obj.strip().splitlines(True)
739 destination = what.strip().splitlines(True)
740 result = differ.compare(source, destination)
741 difference = "".join(result)
742 if self.negative:
743 if self.obj != what:
744 assert not difference, "Difference:\n\n{0}".format(difference)
745 else:
746 if self.obj == what:
747 raise AssertionError(
748 "{0} should be different of {1}".format(self.obj, what)
749 )
750
751 return True
752
753 @assertionmethod
754 def an(self, klass):
755 if isinstance(klass, type):
756 class_name = klass.__name__
757 elif isinstance(klass, string_types):
758 class_name = klass.strip()
759 else:
760 class_name = text_type(klass)
761
762 is_vowel = class_name[0] in "aeiou"
763
764 if isinstance(klass, string_types):
765 if "." in klass:
766 items = klass.split(".")
767 first = items.pop(0)
768 if not items:
769 items = [first]
770 first = "_abcoll"
771 else:
772 if sys.version_info <= (3, 0, 0):
773 first = "__builtin__"
774 else:
775 first = "builtins"
776 items = [klass]
777
778 klass = reduce(getattr, items, __import__(first))
779
780 suffix = is_vowel and "n" or ""
781
782 if self.negative:
783 assert not isinstance(
784 self.obj, klass
785 ), "expected `{0}` to not be a{1} {2}".format(self.obj, suffix, class_name)
786
787 else:
788 assert isinstance(self.obj, klass), "expected `{0}` to be a{1} {2}".format(
789 self.obj, suffix, class_name
790 )
791 return True
792
793 a = an
794
795 @assertionmethod
796 def greater_than(self, dest):
797 if self.negative:
798 msg = "expected `{0}` to not be greater than `{1}`".format(self.obj, dest)
799
800 assert not self.obj > dest, msg
801
802 else:
803 msg = "expected `{0}` to be greater than `{1}`".format(self.obj, dest)
804 assert self.obj > dest, msg
805
806 return True
807
808 @assertionmethod
809 def greater_than_or_equal_to(self, dest):
810 if self.negative:
811 msg = "expected `{0}` to not be greater than or equal to `{1}`".format(
812 self.obj, dest
813 )
814
815 assert not self.obj >= dest, msg
816
817 else:
818 msg = "expected `{0}` to be greater than or equal to `{1}`".format(
819 self.obj, dest
820 )
821 assert self.obj >= dest, msg
822
823 return True
824
825 @assertionmethod
826 def lower_than(self, dest):
827 if self.negative:
828 msg = "expected `{0}` to not be lower than `{1}`".format(self.obj, dest)
829
830 assert not self.obj < dest, msg
831
832 else:
833 msg = "expected `{0}` to be lower than `{1}`".format(self.obj, dest)
834 assert self.obj < dest, msg
835
836 return True
837
838 @assertionmethod
839 def lower_than_or_equal_to(self, dest):
840 if self.negative:
841 msg = "expected `{0}` to not be lower than or equal to `{1}`".format(
842 self.obj, dest
843 )
844
845 assert not self.obj <= dest, msg
846
847 else:
848 msg = "expected `{0}` to be lower than or equal to `{1}`".format(
849 self.obj, dest
850 )
851 assert self.obj <= dest, msg
852
853 return True
854
855 @assertionmethod
856 def below(self, num):
857 if self.negative:
858 msg = "{0} should not be below {1}".format(self.obj, num)
859 assert not self.obj < num, msg
860 else:
861 msg = "{0} should be below {1}".format(self.obj, num)
862 assert self.obj < num, msg
863
864 return True
865
866 @assertionmethod
867 def above(self, num):
868 if self.negative:
869 msg = "{0} should not be above {1}".format(self.obj, num)
870 assert not self.obj > num, msg
871 else:
872 msg = "{0} should be above {1}".format(self.obj, num)
873 assert self.obj > num, msg
874 return True
875
876 @assertionmethod
877 def length_of(self, num):
878 if self.negative:
879 return self._that.len_is_not(num)
880
881 return self._that.len_is(num)
882
883 def called_with(self, *args, **kw):
884 self._callable_args = args
885 self._callable_kw = kw
886 return self
887
888 called = builtins.property(called_with)
889
890 @assertionmethod
891 def throw(self, *args, **kw):
892 _that = AssertionHelper(
893 self.obj, with_args=self._callable_args, and_kwargs=self._callable_kw
894 )
895
896 if self.negative:
897 msg = (
898 "{0} called with args {1} and kwargs {2} should "
899 "not raise {3} but raised {4}"
900 )
901
902 exc = args and args[0] or Exception
903 try:
904 self.obj(*self._callable_args, **self._callable_kw)
905 return True
906 except Exception as e:
907 err = msg.format(
908 self.obj,
909 self._that._callable_args,
910 self._that._callable_kw,
911 exc,
912 e,
913 )
914 raise AssertionError(err)
915
916 return _that.raises(*args, **kw)
917
918 thrown = throw
919 raised = thrown
920
921 @assertionmethod
922 def return_value(self, value):
923 return_value = self.obj(*self._callable_args, **self._callable_kw)
924 return this(return_value).should.equal(value)
925
926 returned_the_value = return_value
927
928 @assertionmethod
929 def look_like(self, value):
930 if self.negative:
931 try:
932 self._that.looks_like(value)
933 except AssertionError:
934 return True
935 else:
936 msg = "%r should not look like %r but does"
937 raise AssertionError(msg % (self.obj, value))
938
939 return self._that.looks_like(value)
940
941 @assertionmethod
942 def contain(self, what):
943 obj = self.obj
944 if self.negative:
945 return expect(what).to.not_be.within(obj)
946 else:
947 return expect(what).to.be.within(obj)
948
949 @assertionmethod
950 def match(self, regex, *args):
951 obj_repr = repr(self.obj)
952 assert isinstance(
953 self.obj, basestring
954 ), "{0} should be a string in order to compare using .match()".format(obj_repr)
955 matched = re.search(regex, self.obj, *args)
956
957 modifiers_map = {
958 re.I: "i",
959 re.L: "l",
960 re.M: "m",
961 re.S: "s",
962 re.U: "u",
963 }
964 modifiers = "".join([modifiers_map.get(x, "") for x in args])
965 regex_representation = "/{0}/{1}".format(regex, modifiers)
966
967 if self.negative:
968 assert (
969 matched is None
970 ), "{0} should not match the regular expression {1}".format(
971 obj_repr, regex_representation
972 )
973
974 else:
975 assert (
976 matched is not None
977 ), "{0} doesn't match the regular expression {1}".format(
978 obj_repr, regex_representation
979 )
980
981 return True
982
983
984 this = AssertionBuilder("this")
985 the = AssertionBuilder("the")
986 it = AssertionBuilder("it")
987 these = AssertionBuilder("these")
988 those = AssertionBuilder("those")
989 expect = AssertionBuilder("expect")
990
991
992 def assertion(func):
993 """Extend sure with a custom assertion method."""
994 func = assertionmethod(func)
995 setattr(AssertionBuilder, func.__name__, func)
996 return func
997
998
999 def chain(func):
1000 """Extend sure with a custom chaining method."""
1001 setattr(AssertionBuilder, func.__name__, func)
1002 return func
1003
1004
1005 def chainproperty(func):
1006 """Extend sure with a custom chain property."""
1007 func = assertionproperty(func)
1008 setattr(AssertionBuilder, func.fget.__name__, func)
1009 return func
1010
1011
1012 class ensure(object):
1013 """
1014 Contextmanager to ensure that the given assertion message
1015 is printed upon a raised ``AssertionError`` exception.
1016
1017 The ``args`` and ``kwargs`` are used to format
1018 the message using ``format()``.
1019 """
1020
1021 def __init__(self, msg, *args, **kwargs):
1022 self.msg = msg
1023 self.args = args
1024 self.kwargs = kwargs
1025
1026 def __enter__(self):
1027 return self
1028
1029 def __exit__(self, exc_type, exc_value, traceback):
1030 """
1031 Catch all ``AsertionError`` exceptions and reraise
1032 them with the message provided to the context manager.
1033 """
1034 if exc_type is not AssertionError:
1035 return
1036
1037 msg = self.msg.format(*self.args, **self.kwargs)
1038 raise AssertionError(msg)
1039
1040
1041 allows_new_syntax = not os.getenv("SURE_DISABLE_NEW_SYNTAX")
1042
1043
1044 def do_enable():
1045 def make_safe_property(method, name, should_be_property=True):
1046 if not should_be_property:
1047 return method(None)
1048
1049 def deleter(method, self, *args, **kw):
1050 if isinstance(self, type):
1051 # if the attribute has to be deleted from a class object
1052 # we cannot use ``del self.__dict__[name]`` directly because we cannot
1053 # modify a mappingproxy object. Thus, we have to delete it in our
1054 # proxy __dict__.
1055 overwritten_object_handlers.pop((id(self), method.__name__), None)
1056 else:
1057 # if the attribute has to be deleted from an instance object
1058 # we are able to directly delete it from the object's __dict__.
1059 self.__dict__.pop(name, None)
1060
1061 def setter(method, self, other):
1062 if isinstance(self, type):
1063 # if the attribute has to be set to a class object
1064 # we cannot use ``self.__dict__[name] = other`` directly because we cannot
1065 # modify a mappingproxy object. Thus, we have to set it in our
1066 # proxy __dict__.
1067 overwritten_object_handlers[(id(self), method.__name__)] = other
1068 else:
1069 # if the attribute has to be set to an instance object
1070 # we are able to directly set it in the object's __dict__.
1071 self.__dict__[name] = other
1072
1073 return builtins.property(
1074 fget=method,
1075 fset=partial(setter, method),
1076 fdel=partial(deleter, method),
1077 )
1078
1079 def build_assertion_property(name, is_negative, prop=True):
1080 """Build assertion property
1081
1082 This is the assertion property which is usually patched
1083 to the built-in ``object`` and ``NoneType``.
1084 """
1085
1086 def method(self):
1087 # check if the given object already has an attribute with the
1088 # given name. If yes return it instead of patching it.
1089 try:
1090 if name in self.__dict__:
1091 return self.__dict__[name]
1092 except AttributeError:
1093 # we do not have an object with __dict__, thus
1094 # it's safe to just continue and patch the `name`.
1095 pass
1096
1097 overwritten_object_handler = overwritten_object_handlers.get(
1098 (id(self), name), None
1099 )
1100 if overwritten_object_handler:
1101 return overwritten_object_handler
1102
1103 builder = AssertionBuilder(name, negative=is_negative)
1104 instance = builder(self)
1105 callable_args = getattr(self, "_callable_args", ())
1106 if callable_args:
1107 instance._callable_args = callable_args
1108 callable_kw = getattr(self, "_callable_kw", {})
1109 if callable_kw:
1110 instance._callable_kw = callable_kw
1111 return instance
1112
1113 method.__name__ = str(name)
1114 return make_safe_property(method, name, prop)
1115
1116 object_handler = patchable_builtin(object)
1117 # We have to keep track of all objects which
1118 # should overwrite a ``POSITIVES`` or ``NEGATIVES``
1119 # property. If we wouldn't do that in the
1120 # make_safe_property.setter method we would loose
1121 # the newly assigned object reference.
1122 overwritten_object_handlers = {}
1123
1124 # None does not have a tp_dict associated to its PyObject, so this
1125 # is the only way we could make it work like we expected.
1126 none = patchable_builtin(None.__class__)
1127
1128 for name in POSITIVES:
1129 object_handler[name] = build_assertion_property(name, is_negative=False)
1130 none[name] = build_assertion_property(name, is_negative=False, prop=False)
1131
1132 for name in NEGATIVES:
1133 object_handler[name] = build_assertion_property(name, is_negative=True)
1134 none[name] = build_assertion_property(name, is_negative=True, prop=False)
1135
1136
1137 old_dir = dir
1138
1139
1140 def enable():
1141 @wraps(builtins.dir)
1142 def _new_dir(*obj):
1143 if not obj:
1144 frame = inspect.currentframe()
1145 return sorted(frame.f_back.f_locals.keys())
1146
1147 if len(obj) > 1:
1148 raise TypeError(
1149 "dir expected at most 1 arguments, got {0}".format(len(obj))
1150 )
1151 patched = []
1152 try:
1153 import pytest
1154 except ImportError:
1155 pytest = None
1156
1157 if not pytest:
1158 try:
1159 patched = [
1160 x
1161 for x in old_dir(obj[0])
1162 if isinstance(getattr(obj[0], x, None), AssertionBuilder)
1163 ]
1164 except Exception:
1165 pass
1166 return sorted(set(old_dir(obj[0])).difference(set()))
1167
1168 builtins.dir = _new_dir
1169 do_enable()
1170
1171
1172 if is_cpython and allows_new_syntax:
1173 enable()