zoukankan      html  css  js  c++  java
  • Haskell语言学习笔记(96)Hspec

    hspec 模块

    Hspec 是一个测试框架。
    hspec 模块需要安装

    $ cabal install hspec --lib
    Completed    hspec-2.7.1 (lib)
    

    示例 1

    -- file Spec.hs
    import Test.Hspec
    import Test.QuickCheck
    import Control.Exception (evaluate)
    
    main :: IO ()
    main = hspec $ do
      describe "Prelude.head" $ do
        it "returns the first element of a list" $ do
          head [23 ..] `shouldBe` (23 :: Int)
    
        it "returns the first element of an *arbitrary* list" $
          property $ x xs -> head (x:xs) == (x :: Int)
    
        it "throws an exception if used with an empty list" $ do
          evaluate (head []) `shouldThrow` anyException
    
    Prelude> :set -package QuickCheck
    package flags have changed, resetting and loading new packages...
    Prelude> :l Spec.hs
    [1 of 1] Compiling Main             ( Spec.hs, interpreted )
    Ok, one module loaded.
    *Main> main
    
    Prelude.head
      returns the first element of a list
      returns the first element of an *arbitrary* list
        +++ OK, passed 100 tests.
      throws an exception if used with an empty list
    
    Finished in 0.0012 seconds
    3 examples, 0 failures
    

    示例 2

    -- file MathSpec.hs
    module MathSpec where
    
    import Test.Hspec
    import Math
    
    main :: IO ()
    main = hspec $ do
      describe "absolute" $ do
        it "returns the original number when given a positive input" $
          absolute 1 `shouldBe` 1
    
        it "returns a positive number when given a negative input" $
          absolute (-1) `shouldBe` 1
    
        it "returns zero when given zero" $
          absolute 0 `shouldBe` 0
    
    -- file Math.hs
    module Math where
    
    absolute :: Int -> Int
    absolute n = if n < 0 then negate n else n
    
    Prelude> :l MathSpec
    [1 of 2] Compiling Math             ( Math.hs, interpreted )
    [2 of 2] Compiling MathSpec         ( MathSpec.hs, interpreted )
    Ok, two modules loaded.
    *MathSpec> main
    
    absolute
      returns the original number when given a positive input
      returns a positive number when given a negative input
      returns zero when given zero
    
    Finished in 0.0008 seconds
    3 examples, 0 failures
    
  • 相关阅读:
    洛谷P3400 仓鼠窝(单调栈)
    牛客练习赛65
    2015 HIAST Collegiate Programming Contest] 题解(AK)
    “科林明伦杯”哈尔滨理工大学第十届程序设计竞赛(同步赛)
    POJ 2421 Constructing Roads
    逆序数&&线段树
    HDU-1166 敌兵布阵 (线段树&&树状数组入门)
    Codeforces Round #484 (Div. 2)
    HDU
    HDU 5773 The All-purpose Zero (变形LIS)
  • 原文地址:https://www.cnblogs.com/zwvista/p/12817236.html
Copyright © 2011-2022 走看看