본문 바로가기
programing/[ python ] unittest

[ python ] __name__ == "__main__" test 하는 방법(coverage)

by 궈능비 2022. 6. 18.
728x90
반응형

python에서 unittest를 할 경우 만약 코드가 

// main.py

import sys

def test_a():
    return 15

def test_b():
    return 1

if __name__ == "__main__":
    try:
        a = test_a()

        b = test_b()

        c = a+b

        print(c)

        d = 0

    except Exception as e:
        print(e)
        d = 1
    finally:
        sys.exit(d)

이렇게 if __main__ == '__main__'  으로 되어 있을 경우 테스트 파일에서 main.py을 직접 호출해야한다.

 

호출하는 방법은 imp 모듈을 사용하면 된다.

 

코드는 다음과 같다.

# testMain.py

import sys
import os
import imp
import unittest

class testMain(unittest.TestCase):

    # unittest 실행시 기동 함수
    def setup(self):
        pass
    
    # unittest 종료시 기동 함수
    def down(self):
        pass

	# main.py 기동 함수
    def mainCond(self, testObj, srcFilePath, expectedExcType=SystemExit, cliArgsStr=''):
        sys.argv = [os.path.basename(srcFilePath)] + ([] if len(cliArgsStr) == 0 else cliArgsStr.split(' '))
        testObj.assertRaises(expectedExcType, imp.load_source, '__main__', srcFilePath)
	
    # test 함수
    def test_main(self):
        self.mainCond(self, 'main.py')

 

만약 main.py가 아니라 다른 파일을 실행시키고 싶다면 mainCond를 호출할 때 내가 실행하고 싶은 파일 이름을 넣으면 된다.

 

만약 arg가 필요하다면 mainCond를 호출할 때 cliArgsStr에 보내고 싶은 arg를 설정할 수 있다.

 

밑의 코드는 args가 userId, 값이 userId1이라고 가정했을 때의 코드다.

 

#testMain.py

import sys
import os
import imp
import unittest

class testMain(unittest.TestCase):

    # unittest 실행시 기동 함수
    def setup(self):
        pass
    
    # unittest 종료시 기동 함수
    def down(self):
        pass

    def mainCond(self, testObj, srcFilePath, expectedExcType=SystemExit, cliArgsStr=''):
        sys.argv = [os.path.basename(srcFilePath)] + ([] if len(cliArgsStr) == 0 else cliArgsStr.split(' '))
        testObj.assertRaises(expectedExcType, imp.load_source, '__main__', srcFilePath)

    def test_main(self):
        self.mainCond(self, 'main.py', cliArgsStr='--userId=userId1')

 

arg 설정은 여러 개도 가능하다. 형식은 동일하다.

728x90
반응형

댓글