PYTHON · 테스트
프로퍼티 기반 테스트 (hypothesis)
hypothesis 라이브러리로 무작위 입력을 자동 생성하여 속성(property)을 검증합니다.
테스트고급hypothesis프로퍼티테스트무작위
핵심 설명
hypothesis 라이브러리로 무작위 입력을 자동 생성하여 속성(property)을 검증합니다.
Python code
# hypothesis 패턴 시뮬레이션
import random
def property_test(func, generator, num_tests=100):
"""간단한 프로퍼티 기반 테스트 러너"""
for i in range(num_tests):
test_input = generator()
try:
func(test_input)
except AssertionError as e:
print(f" 실패! 입력: {test_input}")
raise
print(f" {num_tests}개 테스트 통과!")
# 테스트할 함수
def my_sort(lst):
return sorted(lst)
# 속성 1: 정렬 결과의 길이는 입력과 같다
def test_sort_preserves_length(data):
result = my_sort(data)
assert len(result) == len(data)
# 속성 2: 결과는 정렬되어 있다
def test_sort_is_ordered(data):
result = my_sort(data)
assert all(result[i] <= result[i+1] for i in range(len(result)-1))
# 속성 3: 모든 원소가 보존된다
def test_sort_preserves_elements(data):
result = my_sort(data)
assert sorted(result) == sorted(data)
# 무작위 입력 생성기
def random_int_list():
return [random.randint(-100, 100)
for _ in range(random.randint(0, 20))]
print("=== 길이 보존 ===")
property_test(test_sort_preserves_length, random_int_list)
print("=== 정렬 순서 ===")
property_test(test_sort_is_ordered, random_int_list)
print("=== 원소 보존 ===")
property_test(test_sort_preserves_elements, random_int_list)
# 실제 hypothesis 사용법:
# from hypothesis import given, strategies as st
# @given(st.lists(st.integers()))
# def test_sort(data):
# assert sorted(data) == sorted(sorted(data))학습 팁
프로퍼티 기반 테스트는 개발자가 생각하지 못한 엣지 케이스를 자동으로 찾아줍니다.
주의할 점
프로퍼티를 정의하기 어려운 경우가 있습니다. 먼저 "불변조건"과 "왕복 변환(roundtrip)" 속성을 시도하세요.
자주 묻는 질문
프로퍼티 기반 테스트 (hypothesis)란 무엇인가요?
hypothesis 라이브러리로 무작위 입력을 자동 생성하여 속성(property)을 검증합니다.
프로퍼티 기반 테스트 (hypothesis) 학습 시 주의할 점은 무엇인가요?
프로퍼티를 정의하기 어려운 경우가 있습니다. 먼저 "불변조건"과 "왕복 변환(roundtrip)" 속성을 시도하세요.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.