Test unitari

Principi di Ingegneria del Software in Python

Adam Spannbauer

Machine Learning Engineer at Eastman

Perché testare?

  • Conferma che il codice funzioni come previsto
  • Assicurati che le modifiche in una funzione non rompano un'altra
  • Proteggi contro le modifiche in una dipendenza
Principi di Ingegneria del Software in Python

Testare in Python

  • doctest
  • pytest

logo pytest

Principi di Ingegneria del Software in Python

Usare doctest

def square(x):
    """Calcola il quadrato del numero x

    :param x: numero da elevare al quadrato
    :return: x al quadrato

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


import doctest doctest.testmod()
Esempio fallito:
    square(3)
Risultato atteso:
    9
Risultato ottenuto:
    27
Principi di Ingegneria del Software in Python

Struttura di pytest

Struttura del test

Principi di Ingegneria del Software in Python

Struttura di pytest

Struttura del test

Principi di Ingegneria del Software in Python

Scrivere test unitari

lavorando in workdir/tests/test_document.py

from text_analyzer import Document


# Test dell'attributo tokens su oggetto Document
def test_document_tokens():
    doc = Document('a e i o u')

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

# Test caso limite di documento vuoto def test_document_empty(): doc = Document('') assert doc.tokens == [] assert doc.word_counts == Counter()
Principi di Ingegneria del Software in Python

Scrivere test unitari

# Crea 2 oggetti Document identici
doc_a = Document('a e i o u')
doc_b = Document('a e i o u')

# Controlla se gli oggetti sono ==
print(doc_a == doc_b)

# Controlla se gli attributi sono == print(doc_a.tokens == doc_b.tokens) print(doc_a.word_counts == doc_b.word_counts)
False

True True
Principi di Ingegneria del Software in Python

Eseguire pytest

lavorando con terminal

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

tests/test_document.py ..                     [100%]

========== 2 passed in 0.61 seconds ==========
Principi di Ingegneria del Software in Python

Eseguire pytest

lavorando con terminal

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

tests/test_document.py ..                     [100%]

========== 2 passed in 0.61 seconds ==========
Principi di Ingegneria del Software in Python

Test falliti

lavorando con terminal

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

tests/test_document.py F.

============== FAILURES ==============
________ 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 Left contains more items, first extra item: 'u'
E Use -v to get the full diff

tests/test_document.py:7: AssertionError
====== 1 failed in 0.57 seconds ======
Principi di Ingegneria del Software in Python

Facciamo pratica

Principi di Ingegneria del Software in Python

Preparing Video For Download...