Online Absolute Beginner Python Tutorials
Every Sunday 2pm (UK time/ BST)
by Cheuk Ting Ho
Get this slide deck: https://slides.com/cheukting_ho/python-pytest
Python objects - int, float, str, list, dict, bool
Control flows - if-else, for loop, while loop
Functions, modeuls and classes
unit testing is a software testing method by which individual units of source code... are tested to determine whether they are fit for use. - en.wikipedia.org/wiki/Unit_testing
First your program are structured in units: e.g. functions, classes, modules
Making sure a functions works as it is supposed to locks that pieces of code in place
Most basic piece of testing, to test everything we need other tests. e.g. integration testing, end-to-end testing etc
Input
Test function
Check if matches expected output
Function
(and mock)
pytest is a framework that makes building simple and scalable tests easy.
Perfect for unit test, also have other features via fixtures: patching, mocking, parameterize... (which we will not cover today)
pip install -U pytest
pytest --version
import pytest
def serve_beer(age):
if (age is None) or (age<18):
return "No beer"
else:
return "Have beer"
def test_serve_beer_legal():
adult = 25
assert serve_beer(adult) == "Have beer"
def test_serve_beer_illegal():
child = 10
assert serve_beer(child) == "No beer"
To run it, in the ternimal:
pytest <you_test.py>::<test_your_func>
Let's see it in action!!!
import pytest
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
import pytest
def myfunc():
raise ValueError("Exception 123 raised")
def test_match():
with pytest.raises(ValueError, match=r".* 123 .*"):
myfunc()
there is also another Way (xfail)
Simple E-comerce similator ( e-shop.py)
https://github.com/Cheukting/python02hero/tree/master/2020-05-17-python-pytest
Can you write test for your code?
https://github.com/Cheukting/python02hero/tree/master/2020-05-17-python-pytest
Sunday 2pm (UK time/ BST)
There are also Mid Meet Py every Wednesday 1pm