[python] doctest를 사용하여 파일 처리와 관련된 함수를 테스트하는 방법은?

import doctest

def count_lines(file_path): “”” Count the number of lines in a file.

>>> count_lines('test.txt')
5
"""
with open(file_path, 'r') as file:
    lines = file.readlines()
    return len(lines)

def process_file(file_path): “”” Process a file and return the result.

>>> process_file('test.txt')
'This is line 1.\\nThis is line 2.\\nThis is line 3.\\nThis is line 4.\\nThis is line 5.'
"""
with open(file_path, 'r') as file:
    return file.read()

if name == “main”: # Run the doctests doctest.testmod() ```

위의 코드는 doctest 모듈을 사용하여 파일 처리와 관련된 두 개의 함수를 테스트하는 예제입니다. doctest는 소스 코드의 docstring에 포함된 예제를 실행하고 결과를 확인해줍니다.

count_lines 함수는 주어진 파일의 줄 수를 반환하는 함수입니다. 이 함수의 docstring에 >>>로 시작하는 예제를 작성하고 이를 통해 함수의 동작을 검증할 수 있습니다.

process_file 함수는 주어진 파일을 처리하고 결과를 반환하는 함수입니다. 이 함수 역시 docstring에 예제를 작성하여 동작을 검증할 수 있습니다.

doctest.testmod() 함수를 호출하여 모든 docstring에 작성된 예제를 실행하고 검증합니다. 만약 예제의 실행 결과와 예상 결과가 다를 경우 테스트가 실패하며, 일치할 경우 테스트는 통과합니다.

테스트를 실행하려면 위의 코드를 파일에 저장한 후에 해당 파일을 실행하면 됩니다.