[python] doctest를 사용하여 파일 시스템에 접근하는 코드를 테스트하는 방법은?
import os

def create_directory(path):
    """
    Create a directory at the given path.

    >>> create_directory('test_directory')
    True
    """
    try:
        os.mkdir(path)
        return True
    except FileExistsError:
        return False

def delete_directory(path):
    """
    Delete a directory at the given path.

    >>> delete_directory('test_directory')
    True
    """
    try:
        os.rmdir(path)
        return True
    except FileNotFoundError:
        return False

if __name__ == '__main__':
    import doctest
    doctest.testmod()

위의 예제에서는 create_directory 함수와 delete_directory 함수를 테스트합니다. 각 함수는 파일 시스템에 디렉토리를 생성하거나 삭제하는 작업을 수행합니다. doctest를 사용하여 함수의 동작을 검증하기 위해 각 함수의 예상된 결과를 문서화될 코드 블록으로 작성하였습니다.

if __name__ == '__main__' 블록은 모듈이 직접 실행될 때만 doctest를 실행하도록 합니다. 이렇게 하면 모듈이 다른 파일에서 임포트될 때는 테스트가 수행되지 않습니다.

이제 터미널에서 스크립트를 실행하면 doctest가 코드 블록과 함수의 동작을 자동으로 확인합니다. 잘못된 결과가 나올 경우 오류가 발생하고, 예상된 결과와 일치하는 경우에는 아무런 출력이 없습니다.

파일 시스템에 접근하는 코드를 개발하고 테스트하는 경우에는 doctest를 사용하여 간단하게 검증할 수 있습니다. 이 모듈을 활용하면 코드의 문서화와 테스트를 한 번에 처리할 수 있으므로 개발 생산성을 높이는 데 도움이 됩니다.

참고 자료: