Unit testing

หลักการวิศวกรรมซอฟต์แวร์ใน Python

Adam Spannbauer

Machine Learning Engineer at Eastman

ทำไมต้องทดสอบ?

  • ยืนยันว่าโค้ดทำงานได้ตามที่ตั้งใจ
  • ป้องกันไม่ให้การเปลี่ยนแปลงในฟังก์ชันหนึ่งทำให้อีกฟังก์ชันพัง
  • ป้องกันผลกระทบจากการเปลี่ยนแปลง dependency
หลักการวิศวกรรมซอฟต์แวร์ใน Python

การทดสอบใน Python

  • doctest
  • pytest

โลโก้ pytest

หลักการวิศวกรรมซอฟต์แวร์ใน Python

การใช้ doctest

def square(x):
    """Square the number x

    :param x: number to square
    :return: x squared

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


import doctest doctest.testmod()
Failed example:
    square(3)
Expected:
    9
Got:
    27
หลักการวิศวกรรมซอฟต์แวร์ใน Python

โครงสร้างของ pytest

โครงสร้างการทดสอบ

หลักการวิศวกรรมซอฟต์แวร์ใน Python

โครงสร้างของ pytest

โครงสร้างการทดสอบ

หลักการวิศวกรรมซอฟต์แวร์ใน Python

การเขียน unit test

ทำงานใน workdir/tests/test_document.py

from text_analyzer import Document


# Test tokens attribute on Document object
def test_document_tokens():
    doc = Document('a e i o u')

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

# Test edge case of blank document def test_document_empty(): doc = Document('') assert doc.tokens == [] assert doc.word_counts == Counter()
หลักการวิศวกรรมซอฟต์แวร์ใน Python

การเขียน unit test

# Create 2 identical Document objects
doc_a = Document('a e i o u')
doc_b = Document('a e i o u')

# Check if objects are ==
print(doc_a == doc_b)

# Check if attributes are == print(doc_a.tokens == doc_b.tokens) print(doc_a.word_counts == doc_b.word_counts)
False

True True
หลักการวิศวกรรมซอฟต์แวร์ใน Python

การรัน pytest

ทำงานกับ terminal

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

tests/test_document.py ..                     [100%]

========== 2 passed in 0.61 seconds ==========
หลักการวิศวกรรมซอฟต์แวร์ใน Python

การรัน pytest

ทำงานกับ terminal

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

tests/test_document.py ..                     [100%]

========== 2 passed in 0.61 seconds ==========
หลักการวิศวกรรมซอฟต์แวร์ใน Python

การทดสอบที่ล้มเหลว

ทำงานกับ 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 ======
หลักการวิศวกรรมซอฟต์แวร์ใน Python

มาฝึกกันเถอะ!

หลักการวิศวกรรมซอฟต์แวร์ใน Python

Preparing Video For Download...