Introduction to Testing in Python
Alexander Levin
Data Scientist
Common problems:
All of the problems might lead to significant expenses increase for the fixing purposes.
Testing helps to:
We need testing to ensure it meets specified requirements
Test - a procedure to verify the correctness of a software application or system
assert
statementsThink of airplanes:
All of the above - are tests! And we need them for safety.
assert condition
- lets to test if condition
is True
.condition
is False
, Python will raise an AssertionError
.pytest
- a popular testing framework in Python, which provides a simple way to write tests.
Example of an "assert" test written with pytest
in Python:
import pytest
# A function to test
def squared(number):
return number * number
# A test function always starts with "test"
def test_squared():
assert squared(-2) == squared(2)
with
statement# Writing to file example
with open("hello_world.txt", 'w') as hello_file:
hello_file.write("Hello world \n")
pytest.raises
- when you expect the test to raise an Exception
import pytest
# A function to test
def division(a, b):
return a / b
# A test function
def test_raises():
with pytest.raises(ZeroDivisionError):
division(a=25, b=0)
Testing is:
Tests implementation:
pytest
- a powerful Python framework, that simplifies the testing processassert
- a Python keyword, used in pytest
for creating basic tests by validating a conditionpytest.raises
- a context manager, used to create a test that is expected to result in Exception
Introduction to Testing in Python