Applying test markers

Introduction to Testing in Python

Alexander Levin

Data Scientist

Overview of test markers

  • Use case 1: skip the test if the condition met
  • Use case 2: this test is expected to fail

  • Test marker - a tag (a marker) of a test in the pytest library

  • Allows to specify behavior for particular tests by tagging them (marking them)
Introduction to Testing in Python

Markers syntax

  • Decorator - a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure
  • Test markers syntax are started with @pytest.mark decorator:
import pytest

def get_length(string):
    return len(string)

# The test marker syntax
@pytest.mark.skip
def test_get_len():
    assert get_length('123') == 3
Introduction to Testing in Python

Skip and skipif markers

  • Use @pytest.mark.skip - when you want a test to be skipped in any case
  • Use @pytest.mark.skipif - if you want a test to be skipped if a given condition is True
Introduction to Testing in Python

Skip marker example

  • Use @pytest.mark.skip - when you want a test to be skipped indefinitely.
import pytest
def get_length(string):
    return len(string)

# The skip marker example
@pytest.mark.skip
def test_get_len():
    assert get_length('123') == 3
Introduction to Testing in Python

Skip marker example: output

  • Output with a skipped test:

pytest.mark.skip example

Introduction to Testing in Python

Skipif marker example

  • Use @pytest.mark.skipif - when you want a test to be skipped if the given condition is True.
import pytest
def get_length(string):
    return len(string)

# The skipif marker example
@pytest.mark.skipif('2 * 2 == 5')
def test_get_len():
    assert get_length('abc') == 3
Introduction to Testing in Python

Skipif marker example: output

  • Output of a conditionally skipped test:

pytest.mark.skipif example

Introduction to Testing in Python

Xfail marker

  • Use @pytest.mark.xfail - when you expect a test to be failed
import pytest

def gen_sequence(n):
    return list(range(1, n+1))

# The xfail marker example
@pytest.mark.xfail
def test_gen_seq():
    assert gen_sequence(-1)
Introduction to Testing in Python

Xfail marker: output

  • Output of a test, that is expected to fail:

pytest.mark.xfail example

Introduction to Testing in Python

Summary

Test marker:

  • Is an attribute of a test in the pytest library
  • Is used to specify behavior for particular tests
  • Has syntax started with @pytest.mark.name_of_the_marker
  • Out-of-the-box implementations in pytest:
    • @pytest.mark.xfail
    • @pytest.mark.skip
    • @pytest.mark.skipif
Introduction to Testing in Python

Let's practice!

Introduction to Testing in Python

Preparing Video For Download...