使用Haskell QuickCheck测试TCP端口验证器

时间:2013-09-01 13:22:36

标签: haskell quickcheck

我正在尝试使用QuickCheck(第一次)来测试验证TCP端口号的函数:

validatePort :: Int -> Either String Int
validatePort port =
  if port > 0 && port <= 65535
    then Right port
    else Left "Port must be between 1 and 65535 inclusive"

我写了一个这样的Arbitrary实例:

instance Arbitrary Int where
  arbitrary = choose (1, 65535)

但我不确定如何编写测试属性。

2 个答案:

答案 0 :(得分:1)

作为起点,首先:import Test.QuickCheck已经为Int

定义了任意实例

然后写一个属性:

prop_validate_port port = 
  if   port > 0 && port <= 65535
  then validatePort port == Right port
  else validatePort port == Left "Port must be between 1 and 65535 inclusive"

运行测试:

>quickCheck prop_validate_port
>+++ OK. passed 100 tests.

答案 1 :(得分:1)

作为对jev答案的补充,您还可以使用自定义Gen来享受松散耦合的测试框架:

validPorts :: Gen Int
validPorts = choose (1, 65535)

invalidPorts :: Gen Int
invalidPorts = oneof [choose (minBound, 0), choose (65536, maxBound)]

prop_validatePortValidatesValidPorts = 
  forAll validPorts (\port -> validatePort port == Right port)

prop_validatePortDoesNotValidateInvalidPorts =
  forAll invalidPorts (\port -> validatePort port == Left "...")