资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

PowerShellPester使用-Assertion-创新互联

豆子之前初步了解了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

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


文章标题:PowerShellPester使用-Assertion-创新互联
新闻来源:http://cdkjz.cn/article/ddcghi.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220