Prinsip Rekayasa Perangkat Lunak di Python
Adam Spannbauer
Machine Learning Engineer at Eastman
doctestpytest
def square(x): """Mengkuadratkan angka x :param x: angka yang akan dikuadratkan :return: x dikuadratkan >>> square(3) 9 """ return x ** 3import doctest doctest.testmod()
Contoh gagal:
square(3)
Diharapkan:
9
Didapat:
27


bekerja di workdir/tests/test_document.py
from text_analyzer import Document # Uji atribut tokens pada objek Document def test_document_tokens(): doc = Document('a e i o u') assert doc.tokens == ['a', 'e', 'i', 'o', 'u']# Uji kasus tepi dokumen kosong def test_document_empty(): doc = Document('') assert doc.tokens == [] assert doc.word_counts == Counter()
# Buat 2 objek Document yang identik doc_a = Document('a e i o u') doc_b = Document('a e i o u') # Periksa apakah objek == print(doc_a == doc_b)# Periksa apakah atribut == print(doc_a.tokens == doc_b.tokens) print(doc_a.word_counts == doc_b.word_counts)
FalseTrue True
bekerja dengan terminal
datacamp@server:~/work_dir $ pytest
collected 2 items
tests/test_document.py .. [100%]
========== 2 passed in 0.61 seconds ==========
bekerja dengan terminal
datacamp@server:~/work_dir $ pytest tests/test_document.py
collected 2 items
tests/test_document.py .. [100%]
========== 2 passed in 0.61 seconds ==========
bekerja dengan 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 ======
Prinsip Rekayasa Perangkat Lunak di Python