hypothess로 샘플 CSV 데이터 만드는 방법

8178 단어 hypothesisPython
hypothesis는 테스트 용례보다 더 효과적인 단원 테스트 라이브러리 입니다.
테스트에 사용할 값을 광범위하게 테스트할 수 있다.하지만 이번에는hypothesis의 데이터 생성 기능을 사용하여 샘플 데이터를 간단하게 만들 수 있는지 시험해 보고 싶습니다.

과제.


파일 형식(CSV)의 범위 또는 한계를 결정하는 데이터를 생성하고자 합니다.
해봐!
우선, 나는 데이터를 정의하고 싶다.생성hypothesis의 데이터 사용strategy을 정의하고자 합니다.
이번에는python의 표준 라이브러리csv를 사용해야 하기 때문에 DictWriter를 위해 Dict를 만들면 간단하게 쓸 수 있기 때문에 dict를 만들 때fixed_dictionaries라는 strattegy가 있으면 된다.
이 중에서 만들고 싶은 dict 키를 선택한 다음 값을 결정하는strategy로 정의할 수 있습니다!
from hypothesis import strategies as st

DictRowDataModel = st.fixed_dictionaries({
    'k_id': st.none(),
    'w_id': st.none(),
    '項目1': st.integers(min_value=1, max_value=7),
    '項目2': st.integers(min_value=1, max_value=5),
    '項目3': st.integers(min_value=1, max_value=16)
})
다음은 이걸 어떻게 사용해서 데이터를 만드는지 이해하기 어렵다.
일반적인 단원 테스트에서 사용되는 제작이기 때문에 이 사용 예는 없다.
테스트 용례:
from hypothesis import given
import hypothesis.strategies as st

@given(st.integers(), st.integers())
def test_ints_are_commutative(x, y):
    assert x + y == y + x
그런데 찾아보니 strategy에 example() 정보가 준비되어 있어서 사용할 수 있을 것 같아요.

import csv
from hypothesis import strategies as st

d = {
    'k_id': st.none(),
    'w_id': st.none(),
    '項目1': st.integers(min_value=1, max_value=7),
    '項目2': st.integers(min_value=1, max_value=5),
    '項目3': st.integers(min_value=1, max_value=16)
}

DictRowDataModel = st.fixed_dictionaries(d)

samples = 3
with open('sample.csv', 'w', encoding='utf8') as out:
    writer = csv.DictWriter(out, fieldnames=tuple(d.keys()))
    for i in range(samples):
        sample = DictRowDataModel.example()
        writer.writerow(sample)

나는 범위에서 생성된 코드를 쓰지 않고 완성했다.나는 매우 기쁘다.

결론

strategy.example()를 사용하면 CSV 데이터를 쉽게 만들 수 있습니다~
여기 워닝이 나왔는데 속도 측정 등 주의사항으로 쓰이기 때문에 먼저 만들어놨어요.현재 무시:
NonInteractiveExampleWarning: The `.example()` method is good for exploring strategies, but should only be used interactively.  We recommend using `@given` for tests - it performs better, saves and replays failures to avoid flakiness, and reports minimal examples. (strategy: fixed_dictionaries(...),

좋은 웹페이지 즐겨찾기