Testing and project · Lesson 24 of 25
Testing and project setup
Normal cases, boundaries, expected errors and an isolated environment.
8 minutes1 games
Split your program into small functions and test known inputs: a normal case, a boundary and invalid input. unittest is in the standard library. Locally create an environment with python -m venv .venv and install dependencies with python -m pip after activating it. These terminal commands do not belong in this Python editor.
Python
import unittest
def is_even(n):
return n % 2 == 0
class TestEven(unittest.TestCase):
def test_even(self):
self.assertTrue(is_even(4))
def test_zero(self):
self.assertTrue(is_even(0))
def test_odd(self):
self.assertFalse(is_even(3))
result = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(TestEven).run(result)
print(result.testsRun, result.wasSuccessful())| Tool | Use |
|---|---|
حالة عادية / Normal | An even number: 4 |
حد فاصل / Boundary | Zero |
حالة عكسية / Opposite | An odd number: 3 |
Exercise
Implement safe_divide: return None for a zero divisor, otherwise divide. Print both cases.
Expected output:
3.0 None
Python
Learn more from
Played 0 of 1 games
Sign in to save your progress and earn XP.