Compare PyTest, unittest, and nose frameworks by automating a simple test case
Preconditions (3)
✅ Expected Result: All three frameworks run the test and report a pass for add(2, 3) == 5
import unittest def add(a, b): return a + b # unittest test case class TestAddUnittest(unittest.TestCase): def test_add(self): self.assertEqual(add(2, 3), 5) # nose test case # Nose uses unittest style tests or simple functions # Here is a simple function test for nose def test_add_nose(): assert add(2, 3) == 5 # pytest test case # Pytest can run unittest and nose tests but here is a pytest style test def test_add_pytest(): assert add(2, 3) == 5 if __name__ == '__main__': # Run unittest tests unittest.main(exit=False) # Nose and pytest tests are usually run from command line: # Run nose: nosetests <filename>.py # Run pytest: pytest <filename>.py
This script defines a simple add function to test.
It includes three test styles:
unittest.TestCase with assertEqual.assert statement.assert.The unittest.main() call runs unittest tests when the script runs directly.
For nose and pytest, tests are run from the command line using their respective commands.
This setup helps compare how each framework runs and reports the same test.
Now add data-driven testing with 3 different input pairs for the add function using pytest parametrize
def test_sum():
assert sum([1, 2, 3]) == 6
assert sum([1, 2, 3]) == 7import unittest
class TestMath(unittest.TestCase):
def test_add(self):
assert 1 + 1 == 2Pass the test and this pattern moves unknown