Unittesten

Software-engineeringprincipes in Python

Adam Spannbauer

Machine Learning Engineer at Eastman

Waarom testen?

  • Bevestig dat de code werkt zoals bedoeld
  • Zorg dat wijzigingen in één functie een andere niet breken
  • Bescherm tegen wijzigingen in een afhankelijkheid
Software-engineeringprincipes in Python

Testen in Python

  • doctest
  • pytest

pytest logo

Software-engineeringprincipes in Python

Gebruik van doctest

def square(x):
    """Kwadrateer het getal x

    :param x: getal om te kwadrateren
    :return: x in het kwadraat

    >>> square(3)
    9
    """
    return x ** 3


import doctest doctest.testmod()
Mislukt voorbeeld:
    square(3)
Verwacht:
    9
Gekregen:
    27
Software-engineeringprincipes in Python

pytest-structuur

Teststructuur

Software-engineeringprincipes in Python

pytest-structuur

Teststructuur

Software-engineeringprincipes in Python

Unittests schrijven

werken in workdir/tests/test_document.py

from text_analyzer import Document


# Test tokens-attribuut op Document-object
def test_document_tokens():
    doc = Document('a e i o u')

    assert doc.tokens == ['a', 'e', 'i', 'o', 'u']

# Test randgeval van leeg document def test_document_empty(): doc = Document('') assert doc.tokens == [] assert doc.word_counts == Counter()
Software-engineeringprincipes in Python

Unittests schrijven

# Maak 2 identieke Document-objecten
doc_a = Document('a e i o u')
doc_b = Document('a e i o u')

# Controleer of objecten gelijk zijn
print(doc_a == doc_b)

# Controleer of attributen gelijk zijn print(doc_a.tokens == doc_b.tokens) print(doc_a.word_counts == doc_b.word_counts)
False

True True
Software-engineeringprincipes in Python

pytest uitvoeren

werken met terminal

datacamp@server:~/work_dir $ pytest
2 items verzameld

tests/test_document.py ..                     [100%]

========== 2 geslaagd in 0.61 seconden ==========
Software-engineeringprincipes in Python

pytest uitvoeren

werken met terminal

datacamp@server:~/work_dir $ pytest tests/test_document.py
2 items verzameld

tests/test_document.py ..                     [100%]

========== 2 geslaagd in 0.61 seconden ==========
Software-engineeringprincipes in Python

Falen van tests

werken met terminal

datacamp@server:~/work_dir $ pytest
2 items verzameld

tests/test_document.py F.

============== FALEN ==============
________ test_document_tokens ________

def test_document_tokens(): doc = Document('a e i o u')

assert doc.tokens == ['a', 'e', 'i', 'o']
E AssertionError: assert ['a', 'e', 'i', 'o', 'u'] == ['a', 'e', 'i', 'o']
E Linkerzijde bevat meer items, eerste extra item: 'u'
E Gebruik -v voor het volledige verschil

tests/test_document.py:7: AssertionError
====== 1 gefaald in 0.57 seconden ======
Software-engineeringprincipes in Python

Laten we oefenen

Software-engineeringprincipes in Python

Preparing Video For Download...