명령 줄을 통해 unittest.TestCase에서 단일 테스트 실행
우리 팀에서는 다음과 같이 대부분의 테스트 사례를 정의합니다.
하나의 "프레임 워크"클래스 ourtcfw.py :
import unittest
class OurTcFw(unittest.TestCase):
def setUp:
# something
# other stuff that we want to use everywhere
testMyCase.py와 같은 많은 테스트 사례 :
import localweather
class MyCase(OurTcFw):
def testItIsSunny(self):
self.assertTrue(localweather.sunny)
def testItIsHot(self):
self.assertTrue(localweather.temperature > 20)
if __name__ == "__main__":
unittest.main()
새 테스트 코드를 작성하고 자주 실행하고 시간을 절약하고 싶을 때 다른 모든 테스트 앞에 "__"을 두는 것입니다. 그러나 번거롭고 작성중인 코드에서 산만 해집니다.이 커밋 노이즈는 분명 성가신 일입니다.
예를 들어로 변경하면 다음 testItIsHot()
과 같이 할 수 있기를 원합니다.
$ python testMyCase.py testItIsHot
그리고 한 unittest
실행 만 testItIsHot()
어떻게하면 되나요?
나는 if __name__ == "__main__":
부분 을 다시 쓰려고 노력했지만 파이썬을 처음 사용하기 때문에 길을 잃어 버리고 메서드 이외의 모든 것에 부딪 히고 있습니다.
이것은 제안한대로 작동합니다. 클래스 이름도 지정해야합니다.
python testMyCase.py MyCase.testItIsHot
테스트 사례를 구성하는 경우, 즉 실제 코드와 같은 동일한 조직을 따르고 동일한 패키지의 모듈에 대해 상대적 가져 오기를 사용하십시오.
다음 명령 형식을 사용할 수도 있습니다.
python -m unittest mypkg.tests.test_module.TestClass.test_method
# In your case, this would be:
python -m unittest testMyCase.MyCase.testItIsHot
이에 대한 Python3 설명서 : https://docs.python.org/3/library/unittest.html#command-line-interface
추측 한대로 잘 작동 할 수 있습니다
python testMyCase.py MyCase.testItIsHot
그리고 테스트하는 또 다른 방법이 있습니다 testItIsHot
.
suite = unittest.TestSuite()
suite.addTest(MyCase("testItIsHot"))
runner = unittest.TextTestRunner()
runner.run(suite)
unittest 모듈의 도움말을 확인하면 모듈에서 테스트 케이스 클래스를 실행하고 테스트 케이스 클래스에서 테스트 메소드를 실행할 수있는 몇 가지 조합에 대해 알려줍니다.
python3 -m unittest -h
[...]
Examples:
python3 -m unittest test_module - run tests from test_module
python3 -m unittest module.TestClass - run tests from module.TestClass
python3 -m unittest module.Class.test_method - run specified test method
unittest.main()
모듈의 기본 동작으로 a를 정의 할 필요는 없습니다 .
아마 누군가에게 도움이 될 것입니다. 특정 클래스의 테스트 만 실행하려는 경우 :
if __name__ == "__main__":
unittest.main(MyCase())
파이썬 3.6에서 작동합니다.
@yarkee에서 영감을 얻어 이미 얻은 코드 중 일부와 결합했습니다. run_unit_tests()
명령 줄을 사용하지 않고 함수 를 호출하거나 다른 명령을 사용하여 다른 스크립트에서이를 호출 할 수도 있습니다 python3 my_test_file.py
.
import my_test_file
my_test_file.run_unit_tests()
슬프게도 이것은 Python 3.3
우수하거나 우수합니다.
import unittest
class LineBalancingUnitTests(unittest.TestCase):
@classmethod
def setUp(self):
self.maxDiff = None
def test_it_is_sunny(self):
self.assertTrue("a" == "a")
def test_it_is_hot(self):
self.assertTrue("a" != "b")
러너 코드 :
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from .somewhere import LineBalancingUnitTests
def create_suite(classes, unit_tests_to_run):
suite = unittest.TestSuite()
unit_tests_to_run_count = len( unit_tests_to_run )
for _class in classes:
_object = _class()
for function_name in dir( _object ):
if function_name.lower().startswith( "test" ):
if unit_tests_to_run_count > 0 \
and function_name not in unit_tests_to_run:
continue
suite.addTest( _class( function_name ) )
return suite
def run_unit_tests():
runner = unittest.TextTestRunner()
classes = [
LineBalancingUnitTests,
]
# Comment all the tests names on this list, to run all Unit Tests
unit_tests_to_run = [
"test_it_is_sunny",
# "test_it_is_hot",
]
runner.run( create_suite( classes, unit_tests_to_run ) )
if __name__ == "__main__":
print( "\n\n" )
run_unit_tests()
코드를 약간 편집하면 호출하려는 모든 단위 테스트로 배열을 전달할 수 있습니다.
...
def run_unit_tests(unit_tests_to_run):
runner = unittest.TextTestRunner()
classes = \
[
LineBalancingUnitTests,
]
runner.run( suite( classes, unit_tests_to_run ) )
...
그리고 다른 파일 :
import my_test_file
# Comment all the tests names on this list, to run all Unit Tests
unit_tests_to_run = \
[
"test_it_is_sunny",
# "test_it_is_hot",
]
my_test_file.run_unit_tests( unit_tests_to_run )
또는 https://docs.python.org/3/library/unittest.html#load-tests-protocol 을 사용하고 테스트 모듈 / 파일에서 다음 방법을 정의 할 수 있습니다 .
def load_tests(loader, standard_tests, pattern):
suite = unittest.TestSuite()
# To add a single test from this file
suite.addTest( LineBalancingUnitTests( 'test_it_is_sunny' ) )
# To add a single test class from this file
suite.addTests( unittest.TestLoader().loadTestsFromTestCase( LineBalancingUnitTests ) )
return suite
실행을 하나의 단일 테스트 파일로 제한하려면 테스트 검색 패턴을 load_tests()
함수 를 정의한 유일한 파일로 설정하면됩니다 .
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import unittest
test_pattern = 'mytest/module/name.py'
PACKAGE_ROOT_DIRECTORY = os.path.dirname( os.path.realpath( __file__ ) )
loader = unittest.TestLoader()
start_dir = os.path.join( PACKAGE_ROOT_DIRECTORY, 'testing' )
suite = loader.discover( start_dir, test_pattern )
runner = unittest.TextTestRunner( verbosity=2 )
results = runner.run( suite )
print( "results: %s" % results )
print( "results.wasSuccessful: %s" % results.wasSuccessful() )
sys.exit( not results.wasSuccessful() )
참고 문헌 :
- unittest 모듈이 스크립트에있을 때 sys.argv [1] 관련 문제
- 파이썬 클래스에서 모든 함수를 반복하고 실행하는 방법이 있습니까?
- 파이썬에서 클래스의 모든 멤버 변수를 반복
마지막 주 프로그램 예제 대신에 unittest.main()
메소드 구현 을 읽은 후 다음과 같은 변형이 발생했습니다 .
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import unittest
PACKAGE_ROOT_DIRECTORY = os.path.dirname( os.path.realpath( __file__ ) )
start_dir = os.path.join( PACKAGE_ROOT_DIRECTORY, 'testing' )
from testing_package import main_unit_tests_module
testNames = ["TestCaseClassName.test_nameHelloWorld"]
loader = unittest.TestLoader()
suite = loader.loadTestsFromNames( testNames, main_unit_tests_module )
runner = unittest.TextTestRunner(verbosity=2)
results = runner.run( suite )
print( "results: %s" % results )
print( "results.wasSuccessful: %s" % results.wasSuccessful() )
sys.exit( not results.wasSuccessful() )
'Programing' 카테고리의 다른 글
string.Equals ()와 == 연산자가 실제로 동일합니까? (0) | 2020.04.21 |
---|---|
반영-속성의 속성 이름 및 값 가져 오기 (0) | 2020.04.21 |
CSS : before / : after pseudo-elements에서 이미지의 높이를 변경할 수 있습니까? (0) | 2020.04.21 |
배경색을 기준으로 글꼴 색 결정 (0) | 2020.04.21 |
생성자가 Java에서 예외를 발생시킬 수 있습니까? (0) | 2020.04.21 |