TESTING• Testing isfinding out how well something works.How do you test whether a new table you bought is strong enough?(revealing capabilities by putting it under strain)Now, lets look a little more into software testing…
3.
WHAT ARE THEDIFFERENTTESTS?• Unit tests• Integration tests• Functional tests• Non function tests• UAT (User Acceptance)• Stress test• Regression testsAnd many more.. (100+ types)**We just use the first two
4.
UNIT TEST• Why?-To detect changes that may break a design contract- To reduces defects in the newly developed features- To verify the accuracy/functionality of a unit.Two popular ways to do it in pythonunittest pytestTo write better code.• How?By testing individual units/components of the app/software.A unit is the smallest testable part of any software.
5.
WHY PYTEST?• Popular•Concise• Has helpful assert messages• Powerful fixture• etc .. (Don’t ask me what more!)
6.
INSTALL & SETUP•To install pytest -pip install pytest• unittest module is part of python3• Coverage module –pip install coverageORpip install pytest-cov• Run tests –• pytest arg1 arg2 arg3• Run coverage –• coverage run -m pytest arg1 arg2 arg3OR• pytest --cov=src/ tests/
7.
PYTEST – TESTDISCOVERY• Collection starts from the cmd line args which maybe directories, files or test ids.• Recurse into directories• Files with *_test.py or test_*.py• Test prefixed test classes without an init method• test_ prefixed methods within them
8.
PYTEST – FEWOPTIONS• -r : short test summary infoand its variants,f - failedE - errors - skippedx - xfailedX - xpassedp - passedP - passed with output• Special characters for (de)selection of groups:a - all except pPA - allN - none, this can be used to display nothing (since fE is the default)• --pdb : PDB (Python Debugger) on failures
9.
• setUp() -to set up initial state for all test methods• tearDown() – to clean-up after a test method runs.• setUpClass()• tearDownClass()• run() – Define the order of running the test cases• skipTest(reason)• subTest(msg=None, **params)UNITTEST - Unit testing frameworkRead More: https://docs.python.org/3/library/unittest.html
10.
MOCKING & PATCHING•Mock and MagicMock objects create all attributes and methods as you access them andstore details of how they have been used.• The patch() decorator / context manager makes it easy to mock classes or objects in amodule under test.
11.
FIXTURES• pytest fixturesoffer dramatic improvements over the classic xUnit style of setup/teardownfunctions:• fixtures have explicit names and are activated by declaring their use from test functions, modules,classes or whole projects.• fixtures are implemented in a modular manner, as each fixture name triggers a fixturefunction which can itself use other fixtures.• fixture management scales from simple unit to complex functional testing, allowing to parametrizefixtures and tests according to configuration and component options, or to re-use fixtures acrossfunction, class, module or whole test session scopes.