Package tlib :: Package base :: Module SmartTester
[hide private]
[frames] | no frames]

Source Code for Module tlib.base.SmartTester

  1  __author__ = 'ggegiya1' 
  2   
  3   
4 -class TestFailure(AssertionError):
5 - def __init__(self, message):
6 super(TestFailure, self).__init__(message)
7 8
9 -class SmartTester:
10 - def __init__(self):
11 self.argument = None 12 self.extra_arguments = None 13 self.validation_function = None
14
15 - def assertThat(self, arg=None, *arguments):
16 ## if the argument is a validation function 17 ## then validation function result will be validated 18 if hasattr(arg, "__call__"): 19 self.validation_function = arg 20 self.extra_arguments = arguments 21 else: 22 self.argument = arg 23 return self
24
25 - def equalsTo(self, argument2):
26 """ 27 Embedded method to compare the passed argument to the self.argument 28 :param argument2: 29 :return: True if arguments are equal, else throw an error 30 """ 31 if self.argument == argument2: 32 return True 33 self.throw_error("%s and %s are not equal" 34 % (self._short(self.argument), 35 self._short( argument2)))
36
37 - def contains(self, argument2):
38 if (not hasattr(self.argument, "__iter__")) and (type(self.argument) not in [str]): 39 raise ValueError("The first argument is not iterable") 40 if argument2 in self.argument: 41 return True 42 self.throw_error("The list [%s..] does not contain %s" 43 % (self._short(self.argument), 44 self._short(argument2)))
45
46 - def isTrue(self):
47 self.validate(True)
48
49 - def isFalse(self):
50 self.validate(False)
51
52 - def validate(self, expected=True):
53 if self.argument is not None: 54 if bool(self.argument) is expected: 55 return True 56 else: self.throw_error("%s is not %s" % (self._short(self.argument), expected)) 57 elif self.validation_function is not None: 58 test_status, test_report = self.validation_function(*self.extra_arguments) 59 if test_status is expected: return True 60 self.throw_error(test_report)
61
62 - def throw_error(self, message):
63 raise TestFailure("\r\n" * 2 + "-" * 40 + "\r\nTest Failed!!!\r\n" 64 + (message or "") 65 + "\r\n")
66
67 - def _short(self, arg, length=5):
68 if hasattr(arg, "__iter__"): 69 result = ", ".join([str(arg[i]) for i in xrange(0, min(len(arg), length))]) 70 else: 71 result = str(arg)[:80] 72 return result
73 74
75 -def equals(argument1, argument2):
76 if argument1 == argument2: 77 return True, "%s and %s are equal" % (argument1, argument2) 78 return False, "%s and %s are not equal" % (argument1, argument2)
79 80 81 82 #### just an example of usage
83 -class MyTester(SmartTester):
84 85 ## all those tests should fail 86
87 - def my_test_1(self):
88 self.assertThat([1,4,5,6,7,9,0]).contains(2)
89
90 - def my_test_2(self):
91 self.assertThat(2).equalsTo(3)
92
93 - def my_test_3(self):
94 self.assertThat(equals, 2, 2).isFalse()
95
96 - def my_test_4(self):
97 self.assertThat(False).isTrue()
98
99 - def my_test_5(self):
100 self.assertThat(equals, 2, 3).isTrue()
101