Chapter 4
Chapter 4
Alexander Levin
Data Scientist
Recap of OOP
OOP - programming paradigm based on Example of a Python class:
objects and classes.
class Rectangle:
Class - a template of an object that can # Constructor of Rectangle
def __init__(self, a, b):
contain methods and attributes.
self.a = a
Method - a function or procedure that self.b = b
belongs to a class. # Area method
def get_area(self):
Attribute - a variable that belongs to a return self.a * self.b
class. # Usage example
r = Rectangle(4, 5)
Object - an instance of a class. print(r.get_area())
>> 20
Put the parent class in the brackets after the name of the new class.
class RedRectangle(Rectangle):
self.color = 'red'
Based on OOP: each test case is a class, and each test is a method.
Built-in (is installed with the Python Third-party package (has to be installed
distribution) separately from the Python distribution)
import unittest
.assertTrue() , .assertFalse()
.assertIs() , .assertIsNone()
.assertIsInstance() , .assertIn()
.assertRaises()
Many others
To create a test:
1. Declare a class inheriting from unittest.TestCase
Assertion methods
Alexander Levin
Data Scientist
Example: code
Test of the exponentiation operator:
# test_sqneg.py
import unittest
# Declaring the TestCase class
class TestSquared(unittest.TestCase):
# Defining the test
def test_negative(self):
self.assertEqual((-3) ** 2, 9)
CLI command:
Output:
1 https://docs.python.org/3/library/unittest.html
Use case example: when all of tests are crucial, like testing the airplane before a flight.
1 https://docs.python.org/3/library/unittest.html
If "Ctrl - C"
is pushed once, unittest waits for the current test to end and reports all the results so
far.
1 https://docs.python.org/3/library/unittest.html
Output example:
1 https://docs.python.org/3/library/unittest.html
Alexander Levin
Data Scientist
Fixtures recap
Fixture
a prepared environment for a test
Example: preparing the food for a picnic and the cleaning at the end
.tearDown() - a method called after the test method to clean the environment
1 https://docs.python.org/3/library/unittest.html
class TestLi(unittest.TestCase):
# Fixture setup method
def setUp(self):
self.li = [i for i in range(100)]
# Test method
def test_your_list(self):
self.assertIn(99, self.li)
self.assertNotIn(100, self.li)
class TestLi(unittest.TestCase):
# Fixture setup method
def setUp(self):
self.li = [i for i in range(100)]
.setUp() - a method called to prepare the test fixture before the actual test.
.tearDown() - a method called after the test method to clean the environment.
Alexander Levin
Data Scientist
Data and pipeline
Data: salaries in data science. Pipeline: to get the mean salary:
def test_read_df(read_df):
# Check the type of the dataframe
assert isinstance(read_df, pd.DataFrame)
# Check that df contains rows
assert read_df.shape[0] > 0
def test_write():
# Opening a file in writing mode
with open('temp.txt', 'w') as wfile:
# Writing the text to the file
wfile.write('Testing stuff is awesome')
# Checking the file exists
assert os.path.exists('temp.txt')
# Don't forget to clean after yourself
os.remove('temp.txt')
def test_units(read_df):
filtered = filter_df(read_df)
assert filtered['employment_type'].unique() == ['FT']
assert isinstance(get_mean(filtered), float)
The mean is not bigger than the maximum salary in the dataset
Code:
def test_feature(read_df):
# Filtering the data
filtered = filter_df(read_df)
# Test case: mean is greater than zero
assert get_mean(filtered) > 0
# Test case: mean is not bigger than the maximum
assert get_mean(filtered) <= read_df['salary_in_usd'].max()
Code:
Alexander Levin
Data Scientist
Chapter 1 - Creating tests with pytest
Testing and pytest
CLI: pytest test_script.py
Test markers
Fixtures autouse
Fixtures teardown
Integration testing
Performance testing
Unittest CLI
Fixtures in unittest
Practical examples