Unit Testing in Python
Pytest์ Unittest์ ๋ํด ์์๋ณด์์
Before getting started
Unit testing์ด๋?
: Module์ด๋ application ์์ ์๋ ๊ฐ๋ณ์ ์ธ code ๋จ์๊ฐ ์์๋๋ก ์๋ํ๋์ง ํ์ธํ๋ ๋ฐ๋ณต์ ์ธ ํ์
Unit testing์ด ํ์ํ ์ด์
Code๋ฅผ ์ด๋ป๊ฒ ์์ฑํ๋์ง ์๊ฐํ๋๋ฐ ๋์์ ์ค๋ค
๋ฌด์์ ํด์ผํ๋์ง์ ์์ด์ ๊ตฌํ ์ ํ์ ํ ๋, ๊ทธ ์ ํ๋ค์ด ์ ์ ํ์ง ์์๋ด๋๋ฐ ๋์์ ์ค๋ค
Bug๋ฅผ ๋นจ๋ฆฌ ๋ฐ๊ฒฌํ๊ณ , ์ฝ๊ฒ ๊ณ ์น ์ ์๊ฒ ํด์ค๋ค
Code ์ quality๋ฅผ ํฅ์ ์ํฌ ์ ์๋ค
ํตํฉ์ ๊ฐ๋จํ๊ฒ ํ๊ณ , ์ค๊ณ๋ฅผ ๊ฐ์ ํ ์ ์๋ค
Debugging process๋ฅผ ๊ฐ๊ฒฐํ๊ฒ ํด์ค๋ค
Python test frameworks
Unittest
Doctest
Pytest
Unittest ๋?
Python ํ์ค library์ ํจ๊ป ์ ๊ณต๋๋ ๊ธฐ๋ณธ test framework
๋ค๋ฅธ third-party test framework๋งํผ ๋ฒ์๊ฐ ๋์ง ์๋ค
๋๋ถ๋ถ์ project์ ๋ง๋ ๋จ์ ํ ์คํธ๋ฅผ ์์ฑํ๊ธฐ ์ํด ํ์ํ ๊ธฐ๋ฅ๋ง์ ์ ๊ณตํ๋ค
Java์ JUnit testing famework๋ก ๋ถํฐ ์ํฅ์ ๋ฐ์๋ค
๊ทธ๋์ test๋ฅผ ์ํด class๋ฅผ ๋ง๋ค์ง ์์ผ๋ฉด test function์ ์์ฑํ ์ ์๋ค
Unittest example
Unittest Fixtures
: Test๊ฐ ์ํ๋๊ธฐ ์ setup ํน์ ์ข ๋ฃ ํ์ clean-up ํ๋ ๊ณผ์ ์ ์๋ฏธํ๋ค
setUp()
๊ฐ method๋ฅผ ํธ์ถํ๊ธฐ ์ ์ ํธ์ถ๋๋ method
setUpClass()
ํด๋น class๊ฐ ์์๋๋ฉด ๋จ ํ ๋ฒ ํธ์ถ๋๋ method
method์
@classmethod
decorator๋ฅผ ๋ฌ์์ค์ผ ํ๊ณ , argument๋กcls
๋ฅผ ๋๊ฒจ์ค์ผ ํ๋คex)
tearDown()
๊ฐ test๊ฐ ๋๋ ์ดํ์ ํธ์ถ๋๋ method
Test ๋์ค exception ์ด ๋ฐ์ํด๋ ์คํ๋๋ค
๋จ, setUp() method๊ฐ ์ฑ๊ณตํ์ ๊ฒฝ์ฐ์๋ง ํธ์ถ๋๋ค
tearDownClass()
ํด๋น class๊ฐ ์ข ๋ฃ๋ ์ดํ ๋จ ํ ๋ฒ ํธ์ถ๋๋ method
์ญ์ method์
@classmethod
decorator๋ฅผ ๋ฌ์์ค์ผ ํ๊ณ , argument๋กcls
๋ฅผ ๋๊ฒจ์ค์ผ ํ๋คex)
Pytest ๋?
Unittest์ ๋ฌ๋ฆฌ Class๊ฐ ์๋ module์ ํน์ ๋ช ๋ช ๊ท์น์ ๋ฐ๋ฅด๋ ํจ์๋ก test method ๋ฅผ ์์ฑํ ์ ์๋ค
Pytest Fixtures
๋ค๋ฅธ testing framework ์๋ ๋ฌ๋ฆฌ ๋ ํนํ ๋ฐฉ์์ผ๋ก fixture๋ฅผ ์ ๊ณตํ๋ค
์ด๋ค test๊ฐ ์ด๋ค fixture๋ฅผ ์ฌ์ฉํ๋์ง ์ฝ๊ฒ ํ์ ํ ์ ์๋ค
ex)
XFail
ํด๋น test function์ด fail ํ ๊ฒ์์ ๋ช ์ํ ์ ์๋ค
์คํจํด์ผ๋ง ํ๋ test๋ฅผ ์์ฑํ ๋ ํ์ฉํ ์ ์๋ค
ex) ์๋ชป๋ ๋ฐ์ดํฐ ํ์ ์ ๋ง๊ธฐ์ํ test code
ex)
Last updated
Was this helpful?