Python Zero to Heros

Online Absolute Beginner Python Tutorials 

Every Sunday 2pm (UK time/ BST)

Get this slide deck: https://slides.com/cheukting_ho/python-pytest

Recap

Python objects - int, float, str, list, dict, bool

Control flows - if-else, for loop, while loop

Functions, modeuls and classes

 

Any Questions?

What is Unit test

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

What is Unit test

Input

Test function

Check if matches expected output

✅ or ❌

Function

Libraries for testing

unittest

(and mock)

Pytest

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)

 

https://docs.pytest.org/en/latest/getting-started.html

pip install -U pytest

pytest --version

Test functions

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"

Test functions

To run it, in the ternimal:

pytest <you_test.py>::<test_your_func>

Let's see it in action!!!

Expected Exceptions

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)

Let's write tests for our previous program

 

Simple E-comerce similator ( e-shop.py)

 

https://github.com/Cheukting/python02hero/tree/master/2020-05-17-python-pytest

Homework 📝

 

Can you write test for your code?

 

https://github.com/Cheukting/python02hero/tree/master/2020-05-17-python-pytest

Next week:
Decorator

Sunday 2pm (UK time/ BST)

There are also Mid Meet Py every Wednesday 1pm

Python Unit Testing with Pytest

By Cheuk Ting Ho

Python Unit Testing with Pytest

  • 98
Loading comments...

More from Cheuk Ting Ho