2013-09-01 60 views
2

我想使用快速檢查(首次),以測試驗證TCP端口號功能:使用Haskell的快速​​檢查,以測試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" 

我寫了任意的一個實例是這樣的:

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

但我不知道如何編寫測試屬性。

+0

你應該給一些無效的端口作爲輸入以檢查else分支(簽出:http://book.realworldhaskell.org/read/testing-and-quality-assurance.html) – jev

回答

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. 
+0

@jozefg: thx爲得到清理parens – jev

+0

謝謝。我認爲這有效。至少,我認爲測試正在運行:-)。我正在使用Hspec並沒有收到任何錯誤。順便說一句,我正在和Hspec一起爆發並編寫Haskell測試。 – Ralph

1

,正如附錄jev的答案,您還可以使用定製的Gen s:

享受鬆散耦合的測試框架
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 "...")