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: intro https://www.youtube.com/watch?v=6tNS--WetLI
- pytest:
- 101 introductory https://www.youtube.com/watch?v=etosV2IWBF0
- 201 more details https://www.youtube.com/watch?v=fv259R38gqc
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 |
|
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 |
|
Differences:
- Flexibility:
pytest
offers more flexibility and simplicity in test writing compared tounittest
. Test functions inpytest
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-inassert
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.