温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PowerShell Pester 使用 - Assertion

发布时间:2020-07-10 10:23:11 来源:网络 阅读:1078 作者:beanxyz 栏目:开发技术

豆子之前初步了解了Pester的基本功能,今天继续看看。Pester里面有个很重要的概念叫 assertion (断言),他的作用是通过Should这个关键字 (function)来定义预测应该出现的结果。

这个shoud后面的操作符有以下几种

  • Be                      

  • BeExactly          

  • BeGreaterThan  

  • BeLessThan      

  • BeLike                

  • BeLikeExactly     

  • BeOfType           

  • Exist                    

  • Contain               

  • ContainExactly   

  • Match                  

  • MatchExactly      

  • Throw                  

  • BeNullOrEmpty   


下面这个链接有相关的wiki说明,有兴趣的可以看看

https://github.com/pester/Pester/wiki/Should



这些关键字操作符从名字都能猜的出是干啥的,下面给几个实例看看怎么用。

比如在一个test.ps1里面写一个简单求和功能


function add {
param(
[int]$a,
[int]$b
)
$sum=$a+$b
$sum
}


对应的test.tests.ps1 里面这么写

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"

Describe "Test" {

#Shoud Be 比较结果是否一样,不区分大小写
Context "Should be test"{
    It "Add 1 and 2 is equal to 3" {
        add 1 2 | Should Be 3
    }
      It "Add -1 and 2 is not equal to 0" {
        add -1 2 | Should not Be 0
    }
}

#should be Exactly 比较结果是否一样,区分大小写
Context "Should BeExactly test"{
    It "HostName" {
        hostname | Should beexactly "yli-ise"
    }

}

#Should BeGreaterThan判断得到的结果是否比预定值大
Context "Should BeGreaterThan test"{
    It "PsVersion is above 3" {
        $PSVersionTable.PSVersion.Major | Should beGreaterThan 3
    }

}

#Should beoftype判断结果类型是否为指定类型
Context "Should beOfType test"{
    It "Get-ADUser type"{
        Get-aduser yli | Should beoftype Microsoft.ActiveDirectory.Management.ADUser
    }

}

#Should Exist判断文件是否存在
Context "Should Exist test"{
    It "C:\temp exist"{
        "c:\temp" | should exist
    }
     
}


#Should match 判断结果是否匹配正则表达式, 不区分大小写

Context "Should match test"{
    It "Find Email"{
        "jksjsjsjssdjs abc.xyz@yahoo.com hsosofs" | should match "[a-z0-9!#\$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#\$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
    }
     
}


#Should Throw 判断script block结果是否抛出异常
Context "Should Throw test" {
    It "Get a non-exist Process"{ 
    
        {Get-Process -Name "!@#$%&" -ErrorAction Stop} | Should Throw
    }
}


#Should BeNulorEmpty 判断结果是否为空
Context "Should BeNullorEmpty test"{
    It "Get something from test folder"{
    
        get-childitem C:\temp | should not benullorempty
    }


}


}


直接运行这个测试文件或者通过Invoke-pester执行,看看结果 成功

PowerShell Pester 使用 -  Assertion

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI