ရိုးရိုးလေး ရှင်းပြမယ်
Unit testing ကို ရိုးရိုးလေး ပြောရရင်
Unit test ဆိုတာ သင့် code ရဲ့ အပိုင်းအစ သေးသေးလေး (function တစ်ခု၊ method တစ်ခု) ကို input တစ်ခုပေးပြီး မျှော်လင့်ထားတဲ့ output ထွက်မထွက် စစ်တဲ့ code အတိုလေးပါ။ print() နဲ့ မျက်စိနဲ့ စစ်တာနဲ့ မတူတာက test ကို command တစ်ကြောင်းနဲ့ ထောင်ချီ ပြန် run လို့ ရပြီး မှားရင် ဘယ်နေရာ မှားလဲ ချက်ချင်း ပြောပြတာပါ။
ကားစက်ရုံက quality check လိုပါပဲ။ ဘရိတ်တစ်ခုချင်းကို ကားထဲ မတပ်ခင် စက်တစ်ခုပေါ်မှာ သီးသန့် စမ်းပါတယ်၊ ဒါမှ ကားတစ်စီးလုံး တပ်ပြီးမှ ပြဿနာ ရှာရတာထက် အများကြီး မြန်ပါတယ်။ Code ပြင်တိုင်း test တွေ run လိုက်ရင် အရင် အလုပ်လုပ်ခဲ့တာတွေ မပျက်သေးဘူးဆိုတာ စက္ကန့်ပိုင်းအတွင်း သိရပါတယ်။
Problem → Why → Solution
ပြဿနာ: happy path ကိုပဲ မျက်စိနဲ့ စစ်ခြင်း
divide() function ကို ရေးပြီး print(divide(10, 2)) နဲ့ 5.0 ထွက်လာတာ မြင်လို့ ပြီးပြီလို့ ထင်လိုက်တယ် ဆိုပါစို့။ နှစ်ပတ်ကြာတော့ teammate တစ်ယောက်က zero check ကို 'မလိုဘူး' ထင်ပြီး ဖျက်လိုက်ပါတယ်၊ ဘယ်သူမှ divide(10, 0) ကို ပြန်မစမ်းတဲ့အတွက် production မှာ ZeroDivisionError ပေါက်မှ သိရပါတယ်။ ပြဿနာက code မှာ မဟုတ်ဘဲ စစ်ဆေးမှုက လူ့မှတ်ဉာဏ်ပေါ်မှာ မှီခိုနေတာပါ။
def divide(a, b):
return a / b # someone removed: if b == 0: raise ValueError(...)
print(divide(10, 2)) # 5.0 -- "looks right", so ship it
# divide(10, 0) is never tried again, and nothing fails until productionAutomated test က ဘာကို ပြောင်းလဲပေးလဲ
Test တစ်ခုက 'divide(10, 0) က ValueError ပေါက်ရမယ်' ဆိုတဲ့ စည်းကမ်းကို code အဖြစ် ရေးမှတ်ထားပါတယ်။ အဲဒီ rule ကို ဖျက်လိုက်တဲ့ commit က test ကို ချက်ချင်း fail စေပြီး CI က merge မလုပ်ခင် တားပေးပါတယ်။ Test တွေဟာ အလုပ်လုပ်တဲ့ documentation လည်း ဖြစ်ပါတယ်: function က ဘာလုပ်ရမလဲဆိုတာ ဥပမာနဲ့ ပြထားလို့ပါ။
Core concept: TestCase, assertion နဲ့ test discovery
Standard library ထဲက unittest မှာ test တွေကို unittest.TestCase ကို subclass လုပ်တဲ့ class ထဲမှာ ရေးပါတယ်။ test_ နဲ့ စတဲ့ method တိုင်းက test တစ်ခုပါ၊ တခြားနာမည်တွေကို runner က လျစ်လျူရှုပါတယ်။ Method တစ်ခုစီက class ရဲ့ instance အသစ်ပေါ်မှာ run တဲ့အတွက် test တစ်ခုက ပြောင်းလိုက်တဲ့ self attribute တွေက နောက် test ကို မထိခိုက်ပါဘူး။ setUp() method ရှိရင် test တိုင်း မစခင် run ပြီး တူညီတဲ့ စတင်အခြေအနေကို ပြင်ဆင်ပေးပါတယ်။
Test တစ်ခုကို Arrange-Act-Assert အဆင့်သုံးဆင့်နဲ့ ဖွဲ့ပါ: data နဲ့ object တွေ ပြင်ဆင် (arrange)၊ စစ်ချင်တဲ့ function ကို တစ်ကြိမ် ခေါ် (act)၊ ရလဒ်ကို စစ် (assert)။ Assertion မအောင်ရင် test က FAIL ဖြစ်ပြီး မျှော်လင့်တဲ့ value နဲ့ တကယ်ရတဲ့ value ကို ပြပါတယ်။ Test ထဲမှာ မမျှော်လင့်တဲ့ exception ပေါက်ရင်တော့ ERROR လို့ သီးခြား မှတ်ပါတယ်။
| Assertion | စစ်တာ |
|---|---|
| assertEqual(a, b) | a == b (မတူရင် နှစ်ခုလုံးကို ပြ) |
| assertTrue(x) / assertIn(a, b) | x က truthy / a က b ထဲမှာ ပါ |
| assertAlmostEqual(a, b) | Float နှစ်ခု ဒသမ 7 နေရာအထိ နီးစပ် |
| with assertRaises(Error): | Block ထဲမှာ အဲဒီ exception ပေါက်ရမယ် |
python -m unittest က current folder အောက်က test*.py file တွေကို ရှာပြီး (test discovery) ထဲက TestCase တွေကို run ပါတယ်။ Class တစ်ခုထဲက test တွေကို နာမည်အလိုက် အက္ခရာစဉ်နဲ့ run တဲ့အတွက် test တွေက တစ်ခုနဲ့တစ်ခု အစဉ်ပေါ် မမှီခိုသင့်ပါဘူး။ ပြင်ပ package pytest ကလည်း unittest test တွေကို run နိုင်သလို plain assert နဲ့ ပိုတိုတဲ့ test function တွေကိုလည်း ခွင့်ပြုပါတယ်။
ဘာကို test လုပ်ရမလဲဆိုတာကလည်း ဘယ်လို ရေးမလဲလောက် အရေးကြီးပါတယ်။ Function တစ်ခုစီအတွက် case သုံးမျိုးကို စဉ်းစားပါ: ပုံမှန် input (10, 4)၊ boundary input (0, list အလွတ်, အများဆုံး value) နဲ့ invalid input (zero နဲ့ စား၊ string အမှား)။ Bug အများစုက boundary မှာ ပုန်းနေပါတယ်။ Test နာမည်ကိုလည်း test_divide_by_zero လို အပြုအမူကို ဖော်ပြတဲ့ နာမည်ပေးပါ၊ fail တဲ့အခါ report ထဲမှာ နာမည်ကို ဖတ်ရုံနဲ့ ဘာပျက်လဲ သိရပါတယ်။
- Runner က test_ method ကို ရှာ
- Instance အသစ် + setUp()
- Arrange → Act → Assert
- ok, FAIL ဒါမှမဟုတ် ERROR မှတ်
FAIL က 'code က မှားတယ်' (assertion မအောင်)၊ ERROR က 'test ကိုယ်တိုင် ပျက်သွားတယ်' (မမျှော်လင့်တဲ့ exception) လို့ ခွဲမှတ်ပါ။
အထွေထွေ ပုံစံ
import unittest
class TestThing(unittest.TestCase):
def setUp(self):
self.data = make_fresh_data() # Arrange (runs before each test)
def test_behaviour(self):
result = function_under_test(self.data) # Act
self.assertEqual(result, expected) # Assert
if __name__ == "__main__":
unittest.main()TestCase subclass တစ်ခု၊ test_ method တစ်ခုချင်းစီမှာ act တစ်ခုနဲ့ assert တစ်ခု — ဒါက test အများစုရဲ့ ပုံစံပါ။ unittest.main() က file ကို တိုက်ရိုက် run တဲ့အခါ အထဲက test အားလုံးကို run ပေးပါတယ်။
Worked example: add() နဲ့ divide() အတွက် test လေးခု
'OK' စာကြောင်းတွေကို print() နဲ့ ရိုက်ထုတ်တာက test run သလို ဟန်ဆောင်ရုံပါ၊ ဒီ script ကတော့ test တွေကို တကယ် run ပါတယ်။ unittest ရဲ့ report မှာ 'Ran 4 tests in 0.001s' လို အချိန်ပါလို့ run တိုင်း ပြောင်းပါတယ်၊ ဒါကြောင့် report ကို buffer ထဲ ထည့်ပြီး result object ကနေ ကိန်းဂဏန်းတွေကိုပဲ print ထုတ်ထားပါတယ်။ ကိုယ့်စက်ပေါ်မှာတော့ unittest.main() ဒါမှမဟုတ် python -m unittest နဲ့ run တာ ပုံမှန်ပါ။
import io
import unittest
def add(a, b):
return a + b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
class TestMathFunctions(unittest.TestCase):
def test_add_positive_numbers(self):
self.assertEqual(add(5, 3), 8)
def test_add_negative_numbers(self):
self.assertEqual(add(-5, -3), -8)
def test_divide_normal(self):
self.assertEqual(divide(10, 4), 2.5)
def test_divide_by_zero(self):
with self.assertRaises(ValueError):
divide(10, 0)
if __name__ == "__main__":
# unittest.main() also works; here the report goes to a buffer so the
# timing line ("Ran 4 tests in 0.001s") does not change the output.
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestMathFunctions)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
for name in unittest.defaultTestLoader.getTestCaseNames(TestMathFunctions):
print(name)
print(f"ran {result.testsRun}, failures {len(result.failures)}, "
f"errors {len(result.errors)}")
print("all passed:", result.wasSuccessful())Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- A test class
class TestMathFunctions(unittest.TestCase):TestCase ကို subclass လုပ်လိုက်တာနဲ့ assertEqual လို assertion method တွေ ရပြီး runner က ဒီ class ကို test တွေ စုထားတဲ့နေရာလို့ သိပါတယ်။
- One behaviour per test
self.assertEqual(divide(10, 4), 2.5)10 / 4 ကို ရွေးထားတာက ကိန်းပြည့် မဟုတ်တဲ့ ရလဒ်ကို စစ်ချင်လို့ပါ၊ တစ်ယောက်ယောက်က / ကို // နဲ့ မှားပြောင်းရင် 2 ရပြီး ဒီ test fail ပါမယ်။ 2.5 က float နဲ့ အတိအကျ ဖော်ပြလို့ရလို့ assertEqual နဲ့ စစ်လို့ ရပါတယ်။
- Expecting an exception
with self.assertRaises(ValueError):with block ထဲမှာ ValueError ပေါက်မှ test အောင်ပါတယ်။ Exception မပေါက်ရင် ဒါမှမဟုတ် ZeroDivisionError လို တခြား type ပေါက်ရင် test မအောင်ပါဘူး၊ ဒါကြောင့် zero check ကို ဖျက်လိုက်တဲ့ bug ကို ဖမ်းမိပါတယ်။
- Running without timing noise
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)TextTestRunner က report ကို StringIO buffer ထဲ ရေးပြီး TestResult object ကို ပြန်ပေးပါတယ်။ testsRun, failures, errors နဲ့ wasSuccessful() တို့က run တိုင်း တူတဲ့ value တွေပါ။
- Discovery order
for name in unittest.defaultTestLoader.getTestCaseNames(TestMathFunctions):Loader က test_ နဲ့ စတဲ့ method နာမည်တွေကို အက္ခရာစဉ်နဲ့ ပြန်ပေးပါတယ်။ Output မှာ test_add_negative_numbers က positive ထက် အရင် ပေါ်တာကို ကြည့်ပါ — file ထဲက ရေးထားတဲ့ အစဉ် မဟုတ်ပါဘူး။
test_add_negative_numbers
test_add_positive_numbers
test_divide_by_zero
test_divide_normal
ran 4, failures 0, errors 0
all passed: Truepytest နဲ့ table-driven test
pytest ကို pip install pytest နဲ့ ထည့်ရပါတယ်။ Class မလိုဘဲ test_ နဲ့ စတဲ့ function ရိုးရိုးနဲ့ plain assert ကို သုံးပြီး fail ဖြစ်ရင် expression ထဲက value တွေကို အသေးစိတ် ပြပေးပါတယ်။ @pytest.mark.parametrize က case တစ်ခုချင်းကို သီးခြား test အဖြစ် run တဲ့အတွက် တစ်ခု fail ရင်လည်း ကျန်တာတွေ ဆက် run ပါတယ်။
import pytest
def apply_discount(price, percent):
if not 0 <= percent <= 100:
raise ValueError("percent must be 0-100")
return round(price * (1 - percent / 100), 2)
@pytest.mark.parametrize("price, percent, expected", [
(100, 10, 90.0), # normal
(59.99, 0, 59.99), # boundary: no discount
(20, 100, 0.0), # boundary: free
])
def test_apply_discount(price, percent, expected):
assert apply_discount(price, percent) == expected
def test_rejects_bad_percent():
with pytest.raises(ValueError, match="0-100"):
apply_discount(100, 150)python -m unittest # discover and run test*.py with unittest
python -m unittest -v # one line per test
pytest -q # run with pytest, quiet summary
pytest -k discount # only tests whose name contains "discount"Network, database, အချိန် လို ပြင်ပ အရာတွေကို ခေါ်တဲ့ code ကို unit test လုပ်တဲ့အခါ အဲဒီ dependency ကို fake object နဲ့ အစားထိုးပါ။ အောက်က function က HTTP function ကို parameter အဖြစ် လက်ခံတဲ့အတွက် test က Mock တစ်ခုကို ပေးပြီး ပြန်လာမယ့် data ကို ထိန်းချုပ်နိုင်ကာ ခေါ်ပုံ မှန်မမှန်ကိုလည်း စစ်နိုင်ပါတယ်။
import unittest
from unittest import mock
def fetch_temperature(city, http_get):
data = http_get(f"https://api.example.com/weather?city={city}")
return round(data["temp_c"])
class TestWeather(unittest.TestCase):
def test_rounds_the_temperature(self):
fake_get = mock.Mock(return_value={"temp_c": 31.6})
self.assertEqual(fetch_temperature("Yangon", fake_get), 32)
fake_get.assert_called_once_with("https://api.example.com/weather?city=Yangon")လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ testing
Team တွေက test တွေကို အမျိုးအစား သုံးမျိုး ခွဲပါတယ်။ Unit test တွေက function တစ်ခုချင်းကို millisecond ပိုင်းအတွင်း စစ်ပြီး အများဆုံး ရေးပါတယ်။ Integration test တွေက database, file, ပြင်ပ API နဲ့ ချိတ်ဆက်တဲ့ နေရာကို စစ်ပါတယ်။ End-to-end test တွေကတော့ browser ကို ထိန်းပြီး user flow တစ်ခုလုံးကို စစ်ပါတယ်၊ နှေးလို့ အရေအတွက် နည်းနည်းပဲ ထားပါတယ်။
- CI: GitHub Actions လို CI service က pull request တိုင်းမှာ pytest ကို run ပြီး fail ရင် merge ကို တားပါတယ်။
- Price calculation လို business rule တွေကို parametrize နဲ့ normal, boundary (0, 100%), invalid case တွေ ပါတဲ့ table test နဲ့ ကာကွယ်ပါတယ်။
- File ရေးတဲ့ code ကို tempfile.TemporaryDirectory ဒါမှမဟုတ် pytest ရဲ့ tmp_path fixture နဲ့ စစ်ပြီး test ပြီးရင် ဘာမှ မကျန်ခဲ့အောင် လုပ်ပါတယ်။
- Bug တစ်ခု ပြင်တိုင်း အဲဒီ bug ကို ပြန်ဖြစ်စေမယ့် regression test တစ်ခုကို အရင်ရေးပြီးမှ ပြင်ပါ။
အမှားများ
Testing မှာ ဖြစ်လေ့ရှိတဲ့ အမှားများ
assertRaises ကို function ခေါ်ပြီးသား ရလဒ်နဲ့ သုံးခြင်း
self.assertRaises(ValueError, divide(10, 0)) မှာ divide(10, 0) က assertRaises မခေါ်ခင် run ပြီး exception က test ထဲကနေ တိုက်ရိုက် လွင့်ထွက်သွားလို့ ERROR ဖြစ်ပါတယ်။ with self.assertRaises(ValueError): block ကို သုံးပါ၊ ဒါမှမဟုတ် self.assertRaises(ValueError, divide, 10, 0) လို function နဲ့ argument တွေကို ခွဲပေးပါ။
Test တွေကို အစဉ်နဲ့ shared state ပေါ် မှီခိုခြင်း
test_create က module-level list ထဲကို item ထည့်ပြီး test_count က အဲဒီ item ရှိနေမယ်လို့ ယူဆရင် test_count ကို တစ်ခုတည်း run တဲ့အခါ fail ပါတယ်။ Test တိုင်းက setUp() ဒါမှမဟုတ် fixture နဲ့ ကိုယ်ပိုင် data ကို ဆောက်ရပါမယ်၊ ဒါမှ ဘယ်အစဉ်နဲ့ run run ရလဒ် တူပါမယ်။
Unit test ထဲကနေ live API ကို ခေါ်ခြင်း
အင်တာနက် ပြတ်တဲ့နေ့၊ API rate limit ထိတဲ့နေ့၊ ရာသီဥတု data ပြောင်းတဲ့နေ့တိုင်း test က ကိုယ့် code မမှားဘဲ fail ပါတယ်။ ဒီလို flaky test တွေကြောင့် team က fail တွေကို လျစ်လျူရှုလာပါတယ်။ Unit test မှာ dependency ကို mock နဲ့ အစားထိုးပြီး တကယ့် API ကို integration test အနည်းငယ်မှာပဲ ခေါ်ပါ။
Mini challenge
Mini challenge: parse_price ကို test လုပ်ပါ
'1,250.50 MMK' လို စာသားကို float အဖြစ် ပြောင်းတဲ့ parse_price() function နဲ့ အဲဒါအတွက် unittest test class တစ်ခု ရေးပါ။ Valid case တွေကို subTest နဲ့ table ပုံစံ စစ်ပြီး မှားတဲ့ input တွေက ValueError ပေါက်မပေါက် စစ်ပါ။ နောက်ဆုံးမှာ test ဘယ်နှခု run ပြီး အောင်မအောင် print ထုတ်ပါ။
- parse_price က comma တွေ၊ နောက်ဆုံးက 'MMK' နဲ့ space တွေကို ဖယ်ပြီး float ပြန်ပေးပါ
- စာသားအလွတ်နဲ့ အနုတ်ကိန်းအတွက် ValueError raise လုပ်ပါ
- Valid case အနည်းဆုံး သုံးခုကို subTest နဲ့ စစ်ပါ (boundary 0 ပါရမယ်)
- Invalid case လေးခု ('', 'MMK', '-5', 'abc') ကို assertRaises နဲ့ စစ်ပါ
import io
import unittest
def parse_price(text):
"""Turn '1,250.50 MMK' style text into a float; reject bad input."""
# TODO: clean the text, convert to float, reject empty and negative values
...
class TestParsePrice(unittest.TestCase):
def test_valid_prices(self):
cases = [] # TODO: (text, expected) pairs, including a zero price
for text, expected in cases:
with self.subTest(text=text):
... # TODO: assert
def test_rejects_bad_input(self):
# TODO: each bad input must raise ValueError
...
if __name__ == "__main__":
# TODO: run the suite with a buffered runner and print the results
...ရလဒ်: 'tests run: 2'၊ 'failures: 0, errors: 0' နဲ့ 'OK' ကို print ထုတ်ပါတယ်။ subTest case တွေက test method နှစ်ခုထဲမှာ ရှိလို့ testsRun က 2 ပါ။
အရိပ်အမြွက် ကြည့်ရန်
str.removesuffix("MMK") (Python 3.9+) က နောက်ဆုံးမှာ ရှိမှပဲ ဖယ်ပါတယ်။ float("abc") က ValueError ကို ကိုယ်တိုင် ပေါက်ပြီးသားပါ။ subTest က case တစ်ခု fail ရင်လည်း ကျန် case တွေကို ဆက်စစ်ပြီး ဘယ် text fail လဲ report မှာ ပြပါတယ်။
အဖြေ ကြည့်ရန်
import io
import unittest
def parse_price(text):
"""Turn '1,250.50 MMK' style text into a float; reject bad input."""
cleaned = text.replace(",", "").strip().removesuffix("MMK").strip()
if not cleaned:
raise ValueError("empty price")
value = float(cleaned)
if value < 0:
raise ValueError("negative price")
return value
class TestParsePrice(unittest.TestCase):
def test_valid_prices(self):
cases = [("1,250.50 MMK", 1250.5), ("99", 99.0), (" 0 MMK", 0.0)]
for text, expected in cases:
with self.subTest(text=text):
self.assertEqual(parse_price(text), expected)
def test_rejects_bad_input(self):
for text in ["", "MMK", "-5", "abc"]:
with self.subTest(text=text):
with self.assertRaises(ValueError):
parse_price(text)
if __name__ == "__main__":
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestParsePrice)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print(f"tests run: {result.testsRun}")
print(f"failures: {len(result.failures)}, errors: {len(result.errors)}")
print("OK" if result.wasSuccessful() else "FAILED")Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Unit test တစ်ခုက code အပိုင်းသေးတစ်ခုကို Arrange-Act-Assert ပုံစံနဲ့ အလိုအလျောက် စစ်ပါတယ်။
- unittest မှာ TestCase subclass ထဲက test prefix ပါတဲ့ method တွေကို instance အသစ်ပေါ်မှာ အက္ခရာစဉ်နဲ့ run ပါတယ်။
- with self.assertRaises(...) နဲ့ exception ကို စစ်ပြီး subTest ဒါမှမဟုတ် parametrize နဲ့ normal, boundary, invalid case တွေကို table ပုံစံ စစ်ပါ။
- Network လို ပြင်ပ dependency တွေကို unit test မှာ mock လုပ်ပါ၊ test တွေက အစဉ်နဲ့ shared state ပေါ် မမှီခိုရပါဘူး။
Python Standard Library — unittest — Python Software Foundation