3. • Modify Code with Confidence
• Identify Bugs Early
• Improve System Design
https://alysivji.github.io/testing-101-introduction-to-testing.html#benefits-of-
testing
Why we should test code?
4. • python test framework.
• Advantages of pytest
• Easy to use
• Can run a specific test or subset of tests
• Skip tests
• Can run tests in parallel
What is pytest?
8. • An example of simple test
• Execution
# content of test_sample.py
def inc(x):
return x + 1
def test_answer():
assert int(3) == 5
$ pytest test_sample.py
9. • (venv) py.test test_sample.py
• (venv) py.test tests/test_sample.py
• (venv) py.test tests/
How to run test cases?
$ pytest -h
usage: pytest [options] [file_or_dir] [file_or_dir] [...]
positional arguments:
file_or_dir
14. Structure of the Repository
• Run test
project/
sample/
__init__.py
sample.py
tests/
test_sample.py
$ cd project
$ python –m pytest tests/test_sample.py
18. Test Fixture
• A software test fixture sets up the system for the testing process by
providing it with all the necessary code to initialize it, thereby satisfying
whatever preconditions there may be.
• Frequently fixtures are created by handling setUp() and tearDown() events of
the unit testing framework.
Four phases of a test:
1. Set-up
2. Exercise, interacting with the system under test
3. Verify, determining whether the expected outcome has been
obtained
4. Tear down, to return to the original state
19. • Fixtures are run pytest before the actual test functions.
• @pytest.fixture() decorator
• Purpose
• Setup and Teardown for the tests (e.g, database)
• Test set for the tests
pytest fixtures
21. # calculator.py
class Calculator(object):
"""Calculator class"""
def __init__(self):
pass
@staticmethod
def add(a, b):
return a + b
@staticmethod
def subtract(a, b):
return a - b
@staticmethod
def multiply(a, b):
return a * b
@staticmethod
def divide(a, b):
return a / b
22. # calculator.py
class Calculator(object):
"""Calculator class"""
def __init__(self):
pass
@staticmethod
def add(a, b):
return a + b
@staticmethod
def subtract(a, b):
return a - b
@staticmethod
def multiply(a, b):
return a * b
@staticmethod
def divide(a, b):
return a / b
# test_calculator.py
from src.calculator import add
def test_add():
assert add(1, 2) == 3
29. pytest parameterize
• Define multiple sets of arguments and fixtures at the test function or class.
• @pytest.mark.parametrize: parametrizing test functions
• The builtin pytest.mark.parametrize decorator
34. • Buildin markers: skip, skipif and fail
• skip: enable you to skip tests you don’t want to run
• @pytest.mark.skip(reason=‘something’)
• @pytest.mark.skipif(condition, reason=‘something’)
• xfail: we are telling pytest to run a test function, but we expect it to fail.
• @pytest.mark.fail
43. • Thirty-party pytest plugin
• pytest-mock
• Swapping out part of the system to isolate bits of code
• Mock objects: test doubles, spies, fakes, or stubs..
• mock.patch
• mock.patch.object
pytest mock