Skip to content

Sde202 testing

Pytest vs Unittest

pytest and unittest are both popular testing frameworks in Python, but they have some differences in their approach and features.

unittest:

unittest is part of Python's standard library and follows the xUnit style of testing, which originated from JUnit. It provides a more traditional and structured way of writing tests, with test cases organized into classes that subclass unittest.TestCase. Test methods within these classes must start with the word "test". unittest provides a set of assertion methods (assertEqual(), assertTrue(), etc.) for validating expected outcomes.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import unittest

def add(x, y):
    return x + y

class TestAddFunction(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(1, 2), 3)
        self.assertEqual(add(-1, 1), 0)

if __name__ == '__main__':
    unittest.main()

pytest:

pytest is a third-party testing framework that offers a more flexible and concise way of writing tests compared to unittest. It automatically discovers and runs test functions and methods based on naming conventions and directory structures. pytest supports fixtures, which are functions that provide setup and teardown logic for tests, making it easier to manage test dependencies and setup code. Additionally, pytest offers various plugins for extending its functionality.

Example:

1
2
3
4
5
6
def add(x, y):
    return x + y

def test_add():
    assert add(1, 2) == 3
    assert add(-1, 1) == 0

Differences:

  • Flexibility: pytest offers more flexibility and simplicity in test writing compared to unittest. Test functions in pytest don't need to be within classes or follow specific naming conventions.
  • Fixture Support: pytest has robust support for fixtures, allowing for better setup and teardown logic management.
  • Assertions: While both frameworks offer assertion methods, pytest uses Python's built-in assert statement for assertions, leading to more readable test code.
  • Plugins: pytest has a rich ecosystem of plugins that extend its functionality, allowing for features like code coverage, parallel testing, and more.##

In summary, while unittest is part of the Python standard library and provides a more structured approach to testing, pytest offers greater flexibility, simplicity, and extensibility, making it a popular choice for many Python developers.