使用Python測試框架hypothesis,我想實現一個相當復雜的測試策略組合: 1.我想測試創建s由唯一字符集組成的字符串。2. 每個示例我都想運行一個函數func(s: str, n: int) -> Tuple[str, int],該函數接受一個字符串s和一個整數n作為參數。在這里,我想讓整數也由假設填充,但 的最大值n應該是len(s), 的長度s。我嘗試過使用flatmap,但還沒有充分理解它,無法讓它發揮作用。這是我嘗試過的最小示例:from typing import Tuplefrom hypothesis import givenfrom hypothesis.strategies import text, integersdef func(s: str, n: int) -> Tuple[str, int]: for i in range(n): pass # I do something here on s, which is not relevant to the question return (s, n)# 1. Create the strategy for unique character strings:unique_char_str = text().map(lambda s: "".join(set(s)))#2. Create the complex strategy with flatmap:confined_tuple_str_int = unique_char_str.flatmap( lambda s: func(s, integers(min_value=0, max_value=len(s))))當我嘗試使用這個新策略時,@given(tup=confined_tuple_str_int)def test_foo(tup): pass我的測試失敗了,聲稱test_foo - 類型錯誤:“LazyStrategy”對象無法解釋為整數在行 中,for i in range(n):in不是整數,而是對象。funcnLazyStrategy這告訴我,我對flatmap工作原理有一些誤解,但我自己無法弄清楚。我需要做什么才能正確定義我的測試策略?
1 回答

揚帆大魚
TA貢獻1799條經驗 獲得超9個贊
使用,您不能組合兩個依賴策略 - 這可以使用裝飾器來flatmap完成:composite
@composite
def confined_tuple_str_int(draw, elements=text()):
? ? s = draw(lists(characters(), unique=True).map("".join))
? ? i = draw(integers(min_value=0, max_value=len(s)))
? ? return func(s, i)
@given(confined_tuple_str_int())
def test_foo(tup):
? ? print(tup)
該draw參數允許您獲取策略的繪制值(例如示例) - 在本例中是唯一字符串 - 并使用它來創建依賴于該值的策略 - 在本例中是依賴于字符串長度的整數策略。在從該策略中繪制示例之后,復合裝飾器從這些示例值創建一個新策略并返回它。
免責聲明:我是新手hypothesis,所以我的術語可能有點偏差。
添加回答
舉報
0/150
提交
取消