-
Notifications
You must be signed in to change notification settings - Fork 0
Example of Unitest
Fitri edited this page Sep 9, 2021
·
1 revision
https://www.youtube.com/watch?v=1Lfv5tUGsn8&ab_channel=Socratica
from math import pi
def circle_area(r):
#return pi times r square
return pi*(r**2)- writing the unittest module within same dir as the main module:
.
├── themainmodule.py
└── themainmodule_test.py
0 directories, 2 files
- create special folder for test module only:
.
├── src
│ └── themainmodule.py
└── test
└── test_themainmodule.py
2 directories, 2 files
import unitttest
from math import pi
from themainmodule import circle_area
class TestCircleArea(unittest.TestCase):
def test_area(self):
self.assertAlmostEqual(circle_area(1), pi)
self.assertAlmostEqual(circle_area(0), 0)
self.assertAlmostEqual(circle_area(2.5) pi*2.5**2)$ python -m unittest themainmodule_test
Running from the module but within the dir so python can find the test file itself:
$ python -m unittest
Running from the themainmodule file directly:
$ python themainmodule.py
** need this snippet:
if __name__ == '__main__':
unittest.main()
def test_values(self):
#this error need to be raise else will fail
#parameter: error, function, function's parameter
self.assertRaises(ValueError, circle_area, -2)Without any exception set inside of the function, this unittest will fail, since when testing the -2 value, the function will just return the number instead of flag this the negative number is error, to fix this, we need to add the check inside of the circle_area function and raise error if number is negative.
def circle_area(r):
if r < 0:
raise ValueError('The number is negative')
#return pi times r square
return pi*(r**2)
python
Running the unittest again now will show passing unittest since error is raise when r value is negative.
### Raising the type error when inserted number is not integer:
### from the circle_area function:
```python
def circle_area(r):
if type(r) not in [float, int]:
raise TypeError('The provided radius is non int or float')
if r < 0:
raise ValueError('The number is negative')
#return pi times r square
return pi*(r**2)def test_types(self):
#check to make sure non int will raise error
self.assertRaises(TypeError, circle_area, 5j)
self.assertRaises(TypeError, circle_area, 'hi')
self.assertRaise(TypeError, cicle_area, True)There's many assert method inside of unittest module, to get specific help on what certain assert method does, is simply use the help method on the assert method.
import unittest
help(unittest.TestCase.assertEqual)