반응형
이 파이썬 코드가 있다고 가정합니다.
def answer():
ans = raw_input('enter yes or no')
if ans == 'yes':
print 'you entered yes'
if ans == 'no':
print 'you entered no'
이것에 대한 단위 테스트를 어떻게 작성합니까? 'Mock'을 사용해야하는 건 알지만 방법을 모르겠습니다. 누구든지 간단한 예를 만들 수 있습니까?
해결 방법
입력을 패치 할 수는 없지만 mock.patch ()를 사용하도록 래핑 할 수 있습니다. 해결책은 다음과 같습니다.
from unittest.mock import patch
from unittest import TestCase
def get_input(text):
return input(text)
def answer():
ans = get_input('enter yes or no')
if ans == 'yes':
return 'you entered yes'
if ans == 'no':
return 'you entered no'
class Test(TestCase):
# get_input will return 'yes' during this test
@patch('yourmodule.get_input', return_value='yes')
def test_answer_yes(self, input):
self.assertEqual(answer(), 'you entered yes')
@patch('yourmodule.get_input', return_value='no')
def test_answer_no(self, input):
self.assertEqual(answer(), 'you entered no')
이 스 니펫은 Python 버전 3.3 이상에서만 작동합니다.
참조 페이지 https://stackoverflow.com/questions/21046717
반응형
'파이썬' 카테고리의 다른 글
파이썬 Python에서 파일 크기를 어떻게 확인할 수 있습니까? (0) | 2020.12.26 |
---|---|
파이썬 목록에없는 요소 찾기 (0) | 2020.12.26 |
파이썬은 int와 long을 어떻게 관리합니까? (0) | 2020.12.26 |
파이썬 -inf를 0 값으로 바꿉니다. (0) | 2020.12.25 |
파이썬 'sudo pip'를 실행하면 어떤 위험이 있습니까? (0) | 2020.12.25 |
댓글