Writing unit tests Test-driven development (TDD) is the best thing that has happened to software development this century. One of the most important aspects of TDD is the almost manic focus on unit testing. The TDD methodology uses the so-called test-first approach, where we first write a test that fails and then write the corresponding code to pass the test. The tests should document the developer's intent, but on a lower level than functional design. A suite of tests increases confidence by decreasing the probability of regression and facilitates refactoring. Unit tests are automated tests that test a small piece of code, usually a function or method. Python has the PyUnit API for unit testing. As NumPy users, we can make use of the convenience functions in the numpy.testing module as well. This module, as its name suggests, is dedicated to testing. Script.py: import numpy as np import unittest def factorial(n): if n == 0: return 1 if n < 0: raise ValueError("Don't be so negative") return np.arange(1, n+1).cumprod() class FactorialTest(unittest.TestCase): def test_factorial(self): #Test for the factorial of 3 that should pass. self.assertEqual(6, factorial(3)[-1]) np.testing.assert_equal(np.array([1, 2, 6]), factorial(3)) def test_zero(self): #Test for the factorial of 0 that should pass. self.assertEqual(1, factorial(0)) def test_negative(self): # Test for the factorial of negative numbers that should fail. # It should throw a ValueError, but we expect IndexError self.assertRaises(IndexError, factorial(-10)) if __name__ == '__main__': unittest.main() OUTPUT: (base) CMD>python script.py .E. ====================================================================== ERROR: test_negative (__main__.FactorialTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "script.py", line 24, in test_negative self.assertRaises(IndexError, factorial(-10)) File "script.py", line 8, in factorial raise ValueError("Don't be so negative") ValueError: Don't be so negative ---------------------------------------------------------------------- Ran 3 tests in 0.078s FAILED (errors=1) (base) CMD> (base) CMD>Testing functions available to us:
Tuesday, September 7, 2021
Factorial, NumPy and UnitTest
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment