Created
April 27, 2021 00:14
-
-
Save icedraco/edb51b766c1f7d9f6c36e7bde682d0ce to your computer and use it in GitHub Desktop.
Unit tests inside operational code (disgusting, but works)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Run: python3 mynumber.py | |
# Test: python3 -m unittest mynumber.py | |
import unittest | |
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 | |
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') | |
def main() -> int: | |
print("Main activated!") | |
return 0 | |
if __name__ == '__main__': | |
raise SystemExit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment