python testing
appearently in python to run test files they must be named test*.py
Testing Options
printing values
unittest module
assert keyword
The easiest way to test on an interview is using assert.
on Leetcode for example:
s = Solution()
my_data = [1,2,3,4]
assert(s.functionName(my_data) == *some_value)
Assert Keyword
x = "hello"
#if condition returns True, then nothing happens:
assert x == "hello"
#if condition returns False, AssertionError is raised:
if condition is true, execution continues (nothing happens)
assert x == "goodbye"Â Â Â Â Â #, "x should be 'hello'"Â Â Â Â #adds assertion message when exception is raised
unittest built in python module
1Â Â Import unittest from the standard library
2Â Â Create a class called TestSum that inherits from the TestCase class
3Â Â Convert the test functions into methods by adding self as the first argument
4Â Â Change the assertions to use the self.assertEqual() method on the TestCase class
5Â Â Change the command-line entry point to call unittest.main()
the name of test methods should start with test_
to run:
if name == 'main':
  unittest.main()
or in the command line:
python -m unittest <test_module1>.py test_module2.py
assertion methods are:
assertEqual(a, b) # assert that a == b
assertTrue(result) # assert that bool(result) is True)
assertFalse(result) # assert that bool(result) is False)
assertRaises(exception, function, *args, **kwargs)Â # function should raise exception