python unit test template

background

python includes unittest in the standard module, but I didn't know how to use it right away, so I'll keep the template as a memo so that I can copy and paste it in other projects.

*Notes

From python2.7 and above, unittest can use setUpClass and tearDownClass, which are executed when the test class is initialized. For python2.6 and below, you can use these methods by importing a module called unittest2.

Code template

point

# -*- coding: utf-8 -*-
import os, sys, unittest

class Sample():
	"""Class to be tested"""
	#Method to be tested
	def return_hoge(self):
		return 'hoge'

	#Method to be tested
	def return_poyo(self):
		return 'poyo'

class SampleTest(unittest.TestCase):
	"""A test class that tests a class"""
	CLS_VAL = 'none'

	#Called only once when the test class is initialized(python2.7 or more)
	@classmethod
	def setUpClass(cls):
		if sys.flags.debug: print('> setUpClass method is called.')
		#Execute heavy processing methods to prepare for testing
		cls.CLS_VAL = '> setUpClass : initialized!'
		if sys.flags.debug: print(cls.CLS_VAL)

	#Called only once when the test class is released(python2.7 or more)
	@classmethod
	def tearDownClass(cls):
		if sys.flags.debug: print('> tearDownClass method is called.')
		#Release the object prepared by setUpClass
		cls.CLS_VAL = '> tearDownClass : released!'
		if sys.flags.debug: print(cls.CLS_VAL)

	#Called every time the test method is executed
	def setUp(self):
		if sys.flags.debug: print(os.linesep + '> setUp method is called.')
		#Perform a light process to prepare for the test
		self.smpl = Sample()

	#Called after each test method execution
	def tearDown(self):
		if sys.flags.debug: print(os.linesep + '> tearDown method is called.')
		#Release the object prepared by setUp

	def test_hoge(self):
		expected = 'hoge'
		actual = self.smpl.return_hoge()
		self.assertEqual(expected, actual)

	def test_poyo(self):
		expected = 'poyo'
		actual = self.smpl.return_hoge() #Common mistake
		self.assertEqual(expected, actual)

if __name__ == '__main__':
	#Run unittest
	unittest.main()

From gitHub

Execution result

Put the -d flag on when running a python script to enter debug mode. (sys.flags.debug will be True.)

python -d /Users/you/Desktop/sample.py

> setUpClass method is called.
> setUpClass : heavy method

> setUp method is called.

> tearDown method is called.
.
> setUp method is called.
F
> tearDown method is called.
> tearDownClass method is called.
> tearDownClass : released

======================================================================
FAIL: test_poyo (__main__.SampleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/you/Desktop/sample.py", line 54, in test_poyo
    self.assertEqual(expected, actual)
AssertionError: 'poyo' != 'hoge'

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1)

Output when not in debug mode

 python /Users/you/Desktop/sample.py
.F
======================================================================
FAIL: test_poyo (__main__.SampleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/you/Desktop/sample.py", line 54, in test_poyo
    self.assertEqual(expected, actual)
AssertionError: 'poyo' != 'hoge'

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=1)

Appendix

I don't think it's used much in small scripts, but if you need it, there is also an initialization method for each Module such as setUpModule.

Recommended Posts

python unit test template
Python template for Codeforces-manual test-
Competitive programming, coding test template: Python3
Unit test log output with python
Python Integrity Test
python argparse template
Python unit tests
[Python] Tkinter template
Primality test by Python
Primality test with Python
[Python] What I did to do Unit Test
Python basics 8 numpy test
Competitive Pro Template (Python)
Python test package memo
Primality test with python
Python unit test library Nose option introduction-19 types-
Python data analysis template
Jinja2 | Python template engine
python tag integration test
Unit test Databricks Notebook
Python template engine empy
Write code to Unit Test a Python web app
Algorithm in Python (primality test)
Unit test flask with pytest
Python debug and test module
[Python] Competitive template [At Coder]
Set python test in jenkins
Python Design Pattern --Template method
Python
AtCoder: Python: Daddy the sample test.
test
[Python] Test sample using unittest2, mock
Write selenium test code in python
Preprocessing template for data analysis (Python)
Created AtCoder test tool for Python
Statistical test (multiple test) in Python: scikit_posthocs
Template AtCoder ABC 179 Python (A ~ E)
[Pytest] [mock] Web development beginners summarized unit test and mock in python.
Write C unit tests in Python
Blender 2.9, Python background light color test
template
Test Python non-functional programs with GitLab CI
Pharmaceutical company researchers summarized Python unit tests
WebUI test with Python2.6 + Selenium 2.44.0 --profile setting
Write the test in a python docstring
Generate Japanese test data with Python faker
Post Test 3 (Working with PosgreSQL in Python)
Template for writing batch scripts in python
How to do portmanteau test with python
Integrating with setuptools / python setup.py test / pytest-runner
The Python project template I think of.
Django Tutorial (Blog App Creation) ④ --Unit Test
python setup.py test the code using multiprocess
Run python wsgi server on NGINX Unit