Skip to content

Instantly share code, notes, and snippets.

@icedraco
Created April 27, 2021 01:07
Show Gist options
  • Save icedraco/59a42261e39a4f3f2eaedb77c1da2d40 to your computer and use it in GitHub Desktop.
Save icedraco/59a42261e39a4f3f2eaedb77c1da2d40 to your computer and use it in GitHub Desktop.
toy example + unit test by its side
class MyNumber:
def __init__(self, n: int):
self.__n = n
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.value})"
def __str__(self) -> str:
return str(self.value)
@property
def value(self) -> int:
return self.__n
def add(self, delta: int):
self.__n += delta
def mul(self, times: int):
self.__n *= times
def div(self, by: int):
self.__n /= by
def main() -> int:
# this is not printed when this module is imported, or tested below
print("Main activated!")
return 0
if __name__ == '__main__':
raise SystemExit(main())
# Test: python3 -m unittest mynumber_test.py
import unittest
from mynumber import MyNumber
class MyNumberTest(unittest.TestCase):
def setUp(self):
# This is triggered before each test
self.num = MyNumber(0)
def tearDown(self):
# This is triggered after each test
pass
def testCannotDivideByZero(self):
with self.assertRaises(ZeroDivisionError):
self.num.div(0)
# if we reach here, the test fails
def testAdd(self):
self.num.add(1)
self.num.add(666)
self.assertEqual(self.num.value, 667)
def testSubtract(self):
self.num.add(-2)
self.assertEqual(self.num.value, -2)
def testStrValue(self):
self.assertEqual(str(MyNumber(666)), '666')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment