Tests/Unit/MSFT_xServiceResource.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")]
param ()

Import-Module "$PSScriptRoot\..\..\DSCResource.Tests\TestHelper.psm1" -Force

$TestEnvironment = Initialize-TestEnvironment `
    -DSCModuleName 'xPSDesiredStateConfiguration' `
    -DSCResourceName 'MSFT_xServiceResource' `
    -TestType Unit

InModuleScope 'MSFT_xServiceResource' {
    Describe 'xService Unit Tests' {
        BeforeAll {
            Import-Module "$PSScriptRoot\..\CommonTestHelper.psm1" -Force
            Import-Module "$PSScriptRoot\..\MSFT_xServiceResource.TestHelper.psm1" -Force

            $script:getTargetResourceResultProperties = @('Name', 'StartupType', 'DisplayName', 'Description', 'State', 'Path', 'Dependencies')

            $script:testServiceName = "DscTestService"
            $script:testServiceCodePath = "$PSScriptRoot\..\DscTestService.cs"
            $script:testServiceDisplayName = "DSC test service display name"
            $script:testServiceDescription = "This is DSC test service used for testing ServiceSet composite resource"
            $script:testServiceDependsOn = "winrm"
            $script:testServiceExecutablePath = Join-Path -Path (Get-Location) -ChildPath "DscTestService.exe"

            Stop-Service $script:testServiceName -ErrorAction SilentlyContinue

            New-TestService `
                -ServiceName $script:testServiceName `
                -ServiceCodePath $script:testServiceCodePath `
                -ServiceDisplayName $script:testServiceDisplayName `
                -ServiceDescription $script:testServiceDescription `
                -ServiceDependsOn $script:testServiceDependsOn `
                -ServiceExecutablePath $script:testServiceExecutablePath
        }

        AfterAll {
            Remove-TestService -ServiceName $script:testServiceName -ServiceExecutablePath $script:testServiceExecutablePath
        }

        BeforeEach {
            Set-TargetResource `
                -Name $script:testServiceName `
                -DisplayName $script:testServiceDisplayName `
                -Description $script:testServiceDescription `
                -Path $script:testServiceExecutablePath `
                -Dependencies $script:testServiceDependsOn `
                -BuiltInAccount 'LocalSystem' `
                -State 'Stopped' `
                -StartupType 'Manual'
        }

        AfterEach {
            Set-TargetResource -Name $script:testServiceName -Ensure 'Absent'
        }

        Context 'Get-TargetResource' {
            It 'Should return the correct hashtable properties' {
                $getTargetResourceResult = Get-TargetResource -Name $script:testServiceName

                Test-GetTargetResourceResult -GetTargetResourceResult $getTargetResourceResult -GetTargetResourceResultProperties $script:getTargetResourceResultProperties

                $getTargetResourceResult.Name | Should Be $script:testServiceName
                $getTargetResourceResult.StartupType | Should Be 'Manual'
                $getTargetResourceResult.DisplayName | Should Be $script:testServiceDisplayName
                $getTargetResourceResult.Description | Should Be $script:testServiceDescription
                $getTargetResourceResult.State | Should Be 'Stopped'
                $getTargetResourceResult.Path.IndexOf($script:testServiceName, [System.StringComparison]::OrdinalIgnoreCase)  | Should Not Be -1
                $getTargetResourceResult.Dependencies | Should Be $script:testServiceDependsOn
            }

            It 'Should throw with an invalid service name'{
                { Get-TargetResource -Name "NotAService" } | Should Throw
            }
        }

        Context 'Set-TargetResource' {

            It 'Should set the correct state' {
                Set-TargetResource -Name $script:testServiceName
                $getTargetResourceResult = Get-TargetResource $script:testServiceName
                $getTargetResourceResult.State | Should Be 'Running'

                Set-TargetResource -Name $script:testServiceName -State 'Stopped'
                $getTargetResourceResult = Get-TargetResource $script:testServiceName
                $getTargetResourceResult.State | Should Be 'Stopped'
            }

            It 'Should provide correct verbose output when setting State to Running with the service already started' {
                Set-TargetResource -Name $script:testServiceName

                $verboseFilePath = Join-Path -Path (Get-Location) -ChildPath 'SetTargetResourceRunningTestVerboseOutput.txt'

                if (Test-Path $verboseFilePath)
                {
                    Remove-Item $verboseFilePath -ErrorAction SilentlyContinue
                }

                try
                {
                    Set-TargetResource -Name $script:testServiceName -Verbose 4> $verboseFilePath

                    $actualVerboseOutput = (Get-Content -Path $verboseFilePath -Raw).Trim().Replace("`r`n", "").Replace("`n", "")
                    $expectedVerboseOutputWritePropertiesIgnored = $serviceLocalizedData.WritePropertiesIgnored -f $script:testServiceName
                    $expectedVerboseOutputServiceAlreadyStarted = $serviceLocalizedData.ServiceAlreadyStarted -f $script:testServiceName

                    $actualVerboseOutput.Contains($expectedVerboseOutputWritePropertiesIgnored) | Should Be $true
                    $actualVerboseOutput.Contains($expectedVerboseOutputServiceAlreadyStarted) | Should Be $true
                }
                finally
                {
                    if (Test-Path $verboseFilePath)
                    {
                        Remove-Item $verboseFilePath -ErrorAction SilentlyContinue
                    }
                }
            }

            It 'Should provide correct verbose output when setting State to Stopped with the service already stopped' {
                Set-TargetResource -Name $script:testServiceName -State 'Stopped'

                $verboseFilePath = Join-Path -Path (Get-Location) -ChildPath 'SetTargetResourceStoppedTestVerboseOutput.txt'

                if (Test-Path $verboseFilePath)
                {
                    Remove-Item $verboseFilePath -ErrorAction SilentlyContinue
                }

                try
                {
                    Set-TargetResource -Name $script:testServiceName -State 'Stopped' -Verbose 4> $verboseFilePath

                    $actualVerboseOutput = (Get-Content -Path $verboseFilePath -Raw).Trim().Replace("`r`n", "").Replace("`n", "")
                    $expectedVerboseOutputWritePropertiesIgnored = $serviceLocalizedData.WritePropertiesIgnored -f $script:testServiceName
                    $expectedVerboseOutputServiceAlreadyStopped = $serviceLocalizedData.ServiceAlreadyStopped -f $script:testServiceName

                    $actualVerboseOutput.Contains($expectedVerboseOutputWritePropertiesIgnored) | Should Be $true
                    $actualVerboseOutput.Contains($expectedVerboseOutputServiceAlreadyStopped) | Should Be $true
                }
                finally
                {
                    if (Test-Path $verboseFilePath)
                    {
                        Remove-Item $verboseFilePath -ErrorAction SilentlyContinue
                    }
                }
            }

            It 'Should throw when setting State to Stopped and StartupType to Automatic' {
                Set-TargetResource -Name $script:testServiceName
                { Set-TargetResource -Name $script:testServiceName -State 'Stopped' -StartupType 'Automatic' } | Should Throw
            }

            It 'Should throw when setting State to Running and StartupType to Disabled' {
                Set-TargetResource -Name $script:testServiceName -State 'Stopped'
                { Set-TargetResource -Name $script:testServiceName -StartupType 'Disabled' } | Should Throw
            }

            It 'Should throw when both BuiltInAccount and Credential specified' {
                $testUsername = 'username'
                $testPassword = 'password'
                $secureTestPassword = ConvertTo-SecureString $testPassword  -AsPlainText -Force

                $testCredential = New-Object System.Management.Automation.PSCredential ($testUsername, $secureTestPassword)
                { Set-TargetResource -Name $script:testServiceName -BuiltInAccount 'LocalService' -Credential $testCredential } | Should Throw
            }

            It 'Should correctly change StartupType' {
                Set-TargetResource -Name $script:testServiceName -State 'Stopped' -StartupType 'Disabled'
                $getTargetResourceResult = Get-TargetResource -Name $script:testServiceName
                $getTargetResourceResult.StartupType | Should Be "Disabled"

                Set-TargetResource -Name $script:testServiceName -State 'Stopped' -StartupType 'Manual'
                $getTargetResourceResult = Get-TargetResource -Name $script:testServiceName
                $getTargetResourceResult.StartupType | Should Be "Manual"
            }

            It 'Should correctly change BuiltInAccount' {
                Set-TargetResource -Name $script:testServiceName -State 'Stopped' -BuiltInAccount 'NetworkService'
                $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName -State 'Stopped' -BuiltInAccount 'NetworkService'
                $testTargetResourceResult | Should Be $true

                Set-TargetResource -Name $script:testServiceName -State 'Stopped' -BuiltInAccount 'LocalService'
                $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName -State 'Stopped' -BuiltInAccount 'LocalService'
                $testTargetResourceResult | Should Be $true

                Set-TargetResource -Name $script:testServiceName -State 'Stopped' -BuiltInAccount 'LocalSystem'
                $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName -State 'Stopped' -BuiltInAccount 'LocalSystem'
                $testTargetResourceResult | Should Be $true
            }

            It 'Should throw when trying to set an invalid credential' {
                $testUsername = 'username'
                $testPassword = 'password'
                $secureTestPassword = ConvertTo-SecureString $testPassword  -AsPlainText -Force

                $testCredential = New-Object System.Management.Automation.PSCredential ($testUsername, $secureTestPassword)

                { Set-TargetResource -Name $script:testServiceName -State 'Stopped' -Credential $testCredential } | Should Throw
            }

            It 'Should output correct description and not start a stopped service when WhatIf is specified' {
                Set-TargetResource -Name $script:testServiceName -State 'Stopped'

                $transcriptPath = Join-Path -Path (Get-Location) -ChildPath 'WhatIfTestTranscript.txt'
                if (Test-Path $transcriptPath)
                {
                    Wait-ScriptBlockReturnTrue -ScriptBlock {-not (Test-IsFileLocked -Path $transcriptPath)}
                    Remove-Item $transcriptPath
                }

                try
                {
                    Wait-ScriptBlockReturnTrue -ScriptBlock {-not (Test-IsFileLocked -Path $transcriptPath)}

                    Start-Transcript -Path $transcriptPath
                    Set-TargetResource -Name $script:testServiceName -WhatIf
                    Stop-Transcript

                    Wait-ScriptBlockReturnTrue -ScriptBlock {-not (Test-IsFileLocked -Path $transcriptPath)}

                    $transcriptContent = Get-Content -Path $transcriptPath -Raw
                    $transcriptContent | Should Not Be $null

                    $expectedTranscriptMessage = $LocalizedData.StartServiceWhatIf -f $script:testServiceName

                    $transcriptContent = $transcriptContent.Replace("`r`n", "").Replace("`n", "")
                    $transcriptContent.Contains($expectedTranscriptMessage) | Should Be $true

                    $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName -State 'Stopped'
                    $testTargetResourceResult | Should Be $true
                }
                finally
                {
                    if (Test-Path $transcriptPath)
                    {
                        Wait-ScriptBlockReturnTrue -ScriptBlock {-not (Test-IsFileLocked -Path $transcriptPath)}
                        Remove-Item $transcriptPath
                    }
                }
            }

            It 'Should output correct description and not stop a started service when WhatIf is specified' {
                Set-TargetResource -Name $script:testServiceName

                $transcriptPath = Join-Path -Path (Get-Location) -ChildPath 'WhatIfTestTranscript.txt'
                if (Test-Path $transcriptPath)
                {
                    Wait-ScriptBlockReturnTrue -ScriptBlock {-not (Test-IsFileLocked -Path $transcriptPath)}
                    Remove-Item $transcriptPath
                }

                try
                {
                    Wait-ScriptBlockReturnTrue -ScriptBlock {-not (Test-IsFileLocked -Path $transcriptPath)}

                    Start-Transcript -Path $transcriptPath
                    Set-TargetResource -Name $script:testServiceName -State 'Stopped' -WhatIf
                    Stop-Transcript

                    Wait-ScriptBlockReturnTrue -ScriptBlock {-not (Test-IsFileLocked -Path $transcriptPath)}

                    $transcriptContent = Get-Content -Path $transcriptPath -Raw
                    $transcriptContent | Should Not Be $null

                    $expectedTranscriptMessage = $LocalizedData.StopServiceWhatIf -f $script:testServiceName

                    $transcriptContent = $transcriptContent.Replace("`r`n", "").Replace("`n", "")
                    $transcriptContent.Contains($expectedTranscriptMessage) | Should Be $true

                    $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName
                    $testTargetResourceResult | Should Be $true
                }
                finally
                {
                    if (Test-Path $transcriptPath)
                    {
                        Wait-ScriptBlockReturnTrue -ScriptBlock {-not (Test-IsFileLocked -Path $transcriptPath)}
                        Remove-Item $transcriptPath
                    }
                }
            }

            It 'Should throw with invalid service name' {
                { Set-TargetResource -Name "NotAService" } | Should Throw
            }

            It 'Should throw when trying to start a disabled service' {
                Set-TargetResource -Name $script:testServiceName -State 'Stopped' -StartupType 'Disabled'
                { Set-TargetResource -Name $script:testServiceName } | Should Throw
            }
        }

        Context 'Test-TargetResource' {
            It 'Should return correct value based on State' {
                Set-TargetResource -Name $script:testServiceName
                $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName
                $testTargetResourceResult | Should Be $true

                $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName -State 'Stopped'
                $testTargetResourceResult | Should Be $false

                Set-TargetResource -Name $script:testServiceName -State 'Stopped'
                $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName
                $testTargetResourceResult | Should Be $false

                $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName -State 'Stopped'
                $testTargetResourceResult | Should Be $true
            }

            It 'Should return true with the Automatic StartupType' {
                Set-TargetResource -Name $script:testServiceName -StartupType 'Automatic'
                $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName -StartupType 'Automatic'
                $testTargetResourceResult | Should Be $true
            }

            It 'Should return true with the Manual StartupType' {
                Set-TargetResource -Name $script:testServiceName -StartupType 'Manual'
                $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName -StartupType 'Manual'
                $testTargetResourceResult | Should Be $true
            }

            It 'Should return true with the Disabled StartupType' {
                Set-TargetResource -Name $script:testServiceName -State 'Stopped' -StartupType 'Disabled'
                $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName -State 'Stopped' -StartupType 'Disabled'
                $testTargetResourceResult | Should Be $true
            }

            It 'Should return false with different StartType' {
                Set-TargetResource -Name $script:testServiceName
                $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName -StartupType 'Automatic'
                $testTargetResourceResult | Should Be $false
            }

            It 'Should return false with different BuiltInAccount' {
                Set-TargetResource -Name $script:testServiceName
                $testTargetResourceResult = Test-TargetResource -Name $script:testServiceName -BuiltInAccount NetworkService
                $testTargetResourceResult | Should Be $false
            }

            It 'Should return false with invalid service name' {
                Test-TargetResource -Name "NotAService" | Should Be $false
            }
        }

        Context 'Set-ServiceStartupType' {
            It 'Should throw with invalid StartupType' {
                $win32ServiceObject = Get-Win32ServiceObject -Name $script:testServiceName
                { Set-ServiceStartupType -Win32ServiceObject $win32ServiceObject -StartupType "NotAStartupValue" } | Should Throw
            }
        }
    }
}