觀看https://www.youtube.com/watch?v=zi0rHwfiX1Q后,我嘗試將示例從 C(實作)和 Erlang(測驗)移植到 Python 和假設。鑒于此實作(該rem函式模擬%的 C 行為):
import math
def rem(x, y):
res = x % y
return int(math.copysign(res,x))
class Queue:
def __init__(self, capacity: int):
self.capacity = capacity 1
self.data = [None] * self.capacity
self.inp = 0
self.outp = 0
def put(self, n: int):
self.data[self.inp] = n
self.inp = (self.inp 1) % self.capacity
def get(self):
ans = self.data[self.outp]
self.outp = (self.outp 1) % self.capacity
return ans
def size(self):
return rem((self.inp - self.outp), self.capacity)
和這個測驗代碼
import unittest
from hypothesis.stateful import rule, precondition, RuleBasedStateMachine
from hypothesis.strategies import integers
from myqueue import Queue
class QueueMachine(RuleBasedStateMachine):
cap = 1
def __init__(self):
super().__init__()
self.queue = Queue(self.cap)
self.model = []
@rule(value=integers())
@precondition(lambda self: len(self.model) < self.cap)
def put(self, value):
self.queue.put(value)
self.model.append(value)
@rule()
def size(self):
expected = len(self.model)
actual = self.queue.size()
assert actual == expected
@rule()
@precondition(lambda self: self.model)
def get(self):
actual = self.queue.get()
expected = self.model[0]
self.model = self.model[1:]
assert actual == expected
TestQueue = QueueMachine.TestCase
if __name__ == "__main__":
unittest.main()
實際的問題是如何使用 Hypothesis 進行引數化,QueueMachine.cap而不是在測驗類中手動設定。
uj5u.com熱心網友回復:
您可以self.queue在initialize方法中設定,而不是__init__使用合適的整數策略來設定容量。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/411816.html
標籤:
上一篇:Chai-http請求回傳未定義
