Masih melanjutkan dari modul sebelumnya, kali ini kita akan melakukan testing dengan menggunakan external test file. Jadi fungsi test akan disimpan pada file baru.
Jika Anda mengikuti dari modul awal, disebutkan, aturan penulisan test file adalah:
- diawali dengan test_namafilegoeshere.py
- atau namafilegoeshere_test.py
Kita buat 2 file baru, pada tutorial digunakan nama test_result4.py dan result5_test.py. Berikut isi masing-masing file.
#test_result4.py
from second import my_func
def test_result5():
assert my_func(1, 2, 3) == 5, "from test_result4.py"
#result5_test.py
from second import my_func
def test_result5():
assert my_func(1, 2, 3) == 6
Pada command prompt, jalankan perintah pytest -v, log berikut akan tampil:
PS F:\Project\learnpytest> pytest -v
============================ test session starts ==========================
platform win32 -- Python 3.8.5, pytest-6.2.4, py-1.9.0, pluggy-0.13.1 -- c:\users\rangga\anaconda3\python.exe
cachedir: .pytest_cache
rootdir: F:\Project\learnpytest, configfile: pytest.ini
plugins: dash-1.19.0
collected 2 items
result5_test.py::test_result5 PASSED [ 50%]
test_result4.py::test_result5 FAILED [100%]
=============================== FAILURES =================================
______________________________ test_result5 ______________________________
def test_result5():
> assert my_func(1, 2, 3) == 5, "from test_result4.py"
E AssertionError: from test_result4.py
E assert 6 == 5
E +6
E -5
test_result4.py:4: AssertionError
========================== short test summary info =========================
FAILED test_result4.py::test_result5 - AssertionError: from test_result4.py
======================== 1 failed, 1 passed in 0.66s =======================
Perhatikan, karena perintah pytest tidak disertai nama file, maka pytest akan mengikuti aturan pencarian nama file dengan konvensi test_*.py atau *_test.py.
Sesuai ekspetasi, pytest akan menjalankan fungsi test dari file test_result4.py dan result5_test.py. Fungsi test pada file second.py akan diabaikan.
Sampai modul ini kita sudah mempelajari beberapa cara membuat test, dari test berupa fungsi, test berupa class dan test berupa fungsi pada file terpisah.