简体   繁体   中英

How to parameterize a non-deterministic function in pytest?

Say I have a function which returns a random item from a list:

def get_item(L):
    if not L: return None
    return random.choice(L)

How can I use parameterization with pytest to test both cases?

You can easily pass in parameters which give a deterministic result:

result = get_item(None)
assert result is None

result = get_item([42])
assert result == 42

random.seed(1)
result = get_item([1,2,3])
assert result == 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM