豆子之前初步了解了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里面写一个简单求和功能
1
2
3
4
5
6
7
8
|
function
add {
param
(
[int]
$a
,
[int]
$b
)
$sum
=
$a
+
$b
$sum
}
|
对应的test.tests.ps1 里面这么写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
$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执行,看看结果 成功
本文转自 beanxyz 51CTO博客,原文链接:http://blog.51cto.com/beanxyz/1789850,如需转载请自行联系原作者