From df01e774ac4ba413e7c62d19f11745d72232f249 Mon Sep 17 00:00:00 2001 From: Karol Kaczmarek Date: Mon, 7 Dec 2015 16:50:51 -0800 Subject: [PATCH 01/23] Replacing before_deploy with deploy_script --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 8eca354..e40a719 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -34,7 +34,7 @@ test_script: #---------------------------------# # scripts to run before deployment -before_deploy: +deploy_script: - ps: | # Creating project artifact $stagingDirectory = (Resolve-Path ..).Path From aeca62db2d23bd8874457f6ea05b9ca97c7c9ede Mon Sep 17 00:00:00 2001 From: Karol Kaczmarek Date: Wed, 16 Dec 2015 15:23:56 -0800 Subject: [PATCH 02/23] Temporary workaround for pester issue causing build to get stuck --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index e40a719..163adf2 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -3,7 +3,7 @@ #---------------------------------# version: 1.1.{build}.0 install: - - cinst -y pester + - cinst -y pester --version 3.3.13 - git clone https://github.com/PowerShell/DscResource.Tests - ps: Push-Location - cd DscResource.Tests From 5ac95857c6e7e7a9023ebd897afcf389846b5b8e Mon Sep 17 00:00:00 2001 From: Karol Kaczmarek Date: Thu, 7 Jan 2016 10:18:59 -0800 Subject: [PATCH 03/23] Reverting temporary workaround for pester issue causing build to get stuck --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 163adf2..e40a719 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -3,7 +3,7 @@ #---------------------------------# version: 1.1.{build}.0 install: - - cinst -y pester --version 3.3.13 + - cinst -y pester - git clone https://github.com/PowerShell/DscResource.Tests - ps: Push-Location - cd DscResource.Tests From d99493c8e52eb5f100c5f4b93dd53190361229ea Mon Sep 17 00:00:00 2001 From: KarolKaczmarek Date: Tue, 2 Feb 2016 12:36:02 -0800 Subject: [PATCH 04/23] Update xSystemSecurity.psd1 --- xSystemSecurity.psd1 | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/xSystemSecurity.psd1 b/xSystemSecurity.psd1 index 9d33fea..0236578 100644 --- a/xSystemSecurity.psd1 +++ b/xSystemSecurity.psd1 @@ -35,5 +35,29 @@ VariablesToExport = '*' # Aliases to export from this module AliasesToExport = '*' + +# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. +PrivateData = @{ + + PSData = @{ + + # Tags applied to this module. These help with module discovery in online galleries. + Tags = @('DesiredStateConfiguration', 'DSC', 'DSCResourceKit', 'DSCResource') + + # A URL to the license for this module. + LicenseUri = 'https://github.com/PowerShell/xSystemSecurity/blob/master/LICENSE' + + # A URL to the main website for this project. + ProjectUri = 'https://github.com/PowerShell/xSystemSecurity' + + # A URL to an icon representing this module. + # IconUri = '' + + # ReleaseNotes of this module + # ReleaseNotes = '' + + } # End of PSData hashtable + +} # End of PrivateData hashtable } From cca2ed490bc766cec3b53514c35bf56c49210681 Mon Sep 17 00:00:00 2001 From: KarolKaczmarek Date: Tue, 2 Feb 2016 12:36:36 -0800 Subject: [PATCH 05/23] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 86c8f41..50947c1 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,8 @@ Please refer to [this article](http://technet.microsoft.com/en-us/library/dd8832 ## Versions +### Versions + ### 1.1.0.0 * Fixed encoding From d5b2581e726bb20abadbf18b216ebd38ef33a17f Mon Sep 17 00:00:00 2001 From: Katie Keim Date: Wed, 22 Jun 2016 17:41:40 -0700 Subject: [PATCH 06/23] Added new MS code of conduct --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 50947c1..7a1bfd8 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,12 @@ -[![Build status](https://ci.appveyor.com/api/projects/status/u3h1665qqneo98bh/branch/master?svg=true)](https://ci.appveyor.com/project/PowerShell/xsystemsecurity/branch/master) +[![Build status](https://ci.appveyor.com/api/projects/status/u3h1665qqneo98bh/branch/master?svg=true)](https://ci.appveyor.com/project/PowerShell/xsystemsecurity/branch/master) # xSystemSecurity The **xSystemSecurity** module contains the **xUAC** and **xIEEsc** DSC resources for configuring and managing UAC and IE Enhanced Security Configuration. +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + ## Contributing Please check out common DSC Resources [contributing guidelines](https://github.com/PowerShell/DscResource.Kit/blob/master/CONTRIBUTING.md). @@ -47,10 +50,10 @@ Please check out common DSC Resources [contributing guidelines](https://github.c If you are logged on as a standard user, any changes that require the permissions of an administrator will automatically be denied. If you select this setting, you will need to restart the computer to complete the process of turning off UAC. Once UAC is off, people that log on as administrator will always have the permissions of an administrator. - This is the least secure setting same as “NeverNotify”, but in addition EnableLUA registry key is disabled. + This is the least secure setting same as NeverNotify, but in addition EnableLUA registry key is disabled. EnableLUA controls the behavior of all UAC policy settings for the computer. If you change this policy setting, you must restart your computer - We do not recommend using this setting, but it can be selected for systems that use programs that are not certified for Windows® 8, Windows Server® 2012, Windows® 7 or Windows Server® 2008 R2 because they do not support UAC. + We do not recommend using this setting, but it can be selected for systems that use programs that are not certified for Windows 8, Windows Server 2012, Windows 7 or Windows Server 2008 R2 because they do not support UAC. ### xIEEsc From 134e1aa0500994b42c9f5b199220b7c8f22bf2cd Mon Sep 17 00:00:00 2001 From: Katie Keim Date: Tue, 5 Jul 2016 18:59:25 -0700 Subject: [PATCH 07/23] Converting Pester install to PSGallery in appveyor.yml. --- appveyor.yml | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index e40a719..49daf5e 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -3,12 +3,11 @@ #---------------------------------# version: 1.1.{build}.0 install: - - cinst -y pester - - git clone https://github.com/PowerShell/DscResource.Tests - - ps: Push-Location - - cd DscResource.Tests - - ps: Import-Module .\TestHelper.psm1 -force - - ps: Pop-Location + - git clone https://github.com/PowerShell/DscResource.Tests + - ps: | + Import-Module -Name .\DscResource.Tests\TestHelper.psm1 -Force + Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force + Install-Module -Name Pester -Repository PSGallery -Force #---------------------------------# # build configuration # From b88c246bf92b6eb15bb066f7ed8bff9d05094e43 Mon Sep 17 00:00:00 2001 From: Katie Keim Date: Tue, 5 Jul 2016 19:00:01 -0700 Subject: [PATCH 08/23] Updating README. --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7a1bfd8..e64e6dc 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,8 @@ Please refer to [this article](http://technet.microsoft.com/en-us/library/dd8832 ## Versions -### Versions +### Unreleased +* Converted appveyor.yml to install Pester from PSGallery instead of from Chocolatey. ### 1.1.0.0 From 38cb555ecbe6d1ab2cfbd6ffcc4afa9261d8be54 Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Thu, 28 Jul 2016 14:38:12 +1000 Subject: [PATCH 09/23] New xFileSystemAccessRule resource --- .vscode/launch.json | 13 + DSCResource.Tests/LICENSE | 21 + DSCResource.Tests/Meta.Tests.ps1 | 274 +++++++++++ DSCResource.Tests/MetaFixers.psm1 | 115 +++++ DSCResource.Tests/README.md | 115 +++++ DSCResource.Tests/TestHelper.psm1 | 456 ++++++++++++++++++ DSCResource.Tests/TestRunner.psm1 | 25 + .../MSFT_xFileSystemAccessRule.psm1 | 229 +++++++++ .../MSFT_xFileSystemAccessRule.schema.mof | 8 + README.md | 56 ++- .../MSFT_xFileSystemAccessRule.config.ps1 | 33 ++ ...FileSystemAccessRule.integration.tests.ps1 | 100 ++++ .../Unit/MSFT_xFileSystemAccessRule.tests.ps1 | 195 ++++++++ 13 files changed, 1638 insertions(+), 2 deletions(-) create mode 100644 .vscode/launch.json create mode 100644 DSCResource.Tests/LICENSE create mode 100644 DSCResource.Tests/Meta.Tests.ps1 create mode 100644 DSCResource.Tests/MetaFixers.psm1 create mode 100644 DSCResource.Tests/README.md create mode 100644 DSCResource.Tests/TestHelper.psm1 create mode 100644 DSCResource.Tests/TestRunner.psm1 create mode 100644 DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 create mode 100644 DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.schema.mof create mode 100644 Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1 create mode 100644 Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 create mode 100644 Tests/Unit/MSFT_xFileSystemAccessRule.tests.ps1 diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..6152b72 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,13 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "PowerShell", + "type": "PowerShell", + "request": "launch", + "program": "${file}", + "args": [], + "cwd": "${file}" + } + ] +} \ No newline at end of file diff --git a/DSCResource.Tests/LICENSE b/DSCResource.Tests/LICENSE new file mode 100644 index 0000000..cec380d --- /dev/null +++ b/DSCResource.Tests/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/DSCResource.Tests/Meta.Tests.ps1 b/DSCResource.Tests/Meta.Tests.ps1 new file mode 100644 index 0000000..3e7040c --- /dev/null +++ b/DSCResource.Tests/Meta.Tests.ps1 @@ -0,0 +1,274 @@ +<# + .summary + Test that describes code. + + .PARAMETER Force + Used to force any installations to occur without confirming with + the user. +#> +[CmdletBinding()] +Param ( + [Boolean]$Force = $false +) + +if (!$PSScriptRoot) # $PSScriptRoot is not defined in 2.0 +{ + $PSScriptRoot = [System.IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Path) +} +# Make sure MetaFixers.psm1 is loaded - it contains Get-TextFilesList +Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath 'MetaFixers.psm1') -Force + +# Load the TestHelper module which contains the *-ResourceDesigner functions +Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath 'TestHelper.psm1') -Force + +$ErrorActionPreference = 'stop' +Set-StrictMode -Version latest + +$RepoRoot = (Resolve-Path $PSScriptRoot\..).Path +$PSVersion = $PSVersionTable.PSVersion + +# Install and/or Import xDSCResourceDesigner Module +if ($env:APPVEYOR) { + # Running in AppVeyor so force silent install of xDSCResourceDesigner + $PSBoundParameters.Force = $true +} + +$xDSCResourceDesignerModuleName = "xDscResourceDesigner" +$xDSCResourceDesignerModulePath = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\$xDSCResourceDesignerModuleName" +$xDSCResourceDesignerModule = Install-ModuleFromPowerShellGallery -ModuleName $xDSCResourceDesignerModuleName -ModulePath $xDSCResourceDesignerModulePath @PSBoundParameters + +if ($xDSCResourceDesignerModule) { + # Import the module if it is available + $xDSCResourceDesignerModule | Import-Module -Force +} +else +{ + # Module could not/would not be installed - so warn user that tests will fail. + Write-Warning -Message ( @( + "The 'xDSCResourceDesigner' module is not installed. " + "The 'PowerShell DSC resource modules' Pester Tests in Meta.Tests.ps1 " + 'will fail until this module is installed.' + ) -Join '' ) +} + +# PSScriptAnalyzer requires PowerShell 5.0 or higher +if ($PSVersion.Major -ge 5) +{ + Write-Verbose -Verbose "Installing PSScriptAnalyzer" + $PSScriptAnalyzerModuleName = "PSScriptAnalyzer" + $PSScriptAnalyzerModulePath = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\$PSScriptAnalyzerModuleName" + $PSScriptAnalyzerModule = Install-ModuleFromPowerShellGallery -ModuleName $PSScriptAnalyzerModuleName -ModulePath $PSScriptAnalyzerModulePath @PSBoundParameters + + if ($PSScriptAnalyzerModule) { + # Import the module if it is available + $PSScriptAnalyzerModule | Import-Module -Force + } + else + { + # Module could not/would not be installed - so warn user that tests will fail. + Write-Warning -Message ( @( + "The 'PSScriptAnalyzer' module is not installed. " + "The 'PowerShell DSC resource modules' Pester Tests in Meta.Tests.ps1 " + 'will fail until this module is installed.' + ) -Join '' ) + } +} +else +{ + Write-Verbose -Verbose "Skipping installation of PSScriptAnalyzer since it requires PSVersion 5.0 or greater. Used PSVersion: $($PSVersion)" +} + +# The folder where this module is found +[String] $moduleRoot = Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path) + +# Modify PSModulePath of the current PowerShell session. +# We want to make sure we always test the development version of the resource +# in the current build directory. +[String] $script:OldModulePath = $env:PSModulePath +[String] $NewModulePath = $script:OldModulePath +if (($NewModulePath.Split(';') | Select-Object -First 1) -ne $moduleRoot) +{ + # Add the ModuleRoot to the beginning if it is not already at the front. + $env:PSModulePath = "$moduleRoot;$env:PSModulePath" +} + +# Wrap tests in a try so that if anything goes wrong or user terminates we roll back +# any enviroment changes (e.g. $ENV:PSModulePath) +try +{ + Describe 'Text files formatting' { + + $allTextFiles = Get-TextFilesList $RepoRoot + + Context 'Files encoding' { + + It "Doesn't use Unicode encoding" { + $unicodeFilesCount = 0 + $allTextFiles | %{ + if (Test-FileUnicode $_) { + $unicodeFilesCount += 1 + if($_.Extension -ieq '.mof') + { + Write-Warning "File $($_.FullName) contains 0x00 bytes. It's probably uses Unicode and need to be converted to ASCII. Use Fixer 'Get-UnicodeFilesList `$pwd | ConvertTo-ASCII'." + } + else + { + Write-Warning "File $($_.FullName) contains 0x00 bytes. It's probably uses Unicode and need to be converted to UTF-8. Use Fixer 'Get-UnicodeFilesList `$pwd | ConvertTo-UTF8'." + } + } + } + $unicodeFilesCount | Should Be 0 + } + } + + Context 'Indentations' { + + It 'Uses spaces for indentation, not tabs' { + $totalTabsCount = 0 + $allTextFiles | %{ + $fileName = $_.FullName + $tabStrings = (Get-Content $_.FullName -Raw) | Select-String "`t" | % { + Write-Warning "There are tab in $fileName. Use Fixer 'Get-TextFilesList `$pwd | ConvertTo-SpaceIndentation'." + $totalTabsCount++ + } + } + $totalTabsCount | Should Be 0 + } + } + + Context 'New Lines' { + + It 'Should end with a new line' { + $noNewLineCount = 0 + + foreach($file in $allTextFiles) + { + $content = Get-Content $file.FullName -Raw + + if($content[-1] -ne "`n") + { + if($noNewLineCount -eq 0) + { + Write-Warning "To improve consistency across multiple environments and editors each text file is required to end with a new line." + } + + Write-Warning "$($file.FullName) does not end with a new line. Use Fixer 'Add-NewLine'" + $noNewLineCount++ + } + } + + if(!$env:AppVeyor) + { + $noNewLineCount | should be 0 + } + } + } + } + + Describe 'PowerShell DSC resource modules' { + + # PSScriptAnalyzer requires PowerShell 5.0 or higher + if ($PSVersion.Major -ge 5) + { + Context 'PSScriptAnalyzer' { + It 'passes Invoke-ScriptAnalyzer' { + + # Perform PSScriptAnalyzer scan. + # Using ErrorAction SilentlyContinue not to cause it to fail due to parse errors caused by unresolved resources. + # Many of our examples try to import different modules which may not be present on the machine and PSScriptAnalyzer throws parse exceptions even though examples are valid. + # Errors will still be returned as expected. + $PSScriptAnalyzerErrors = Invoke-ScriptAnalyzer -path $RepoRoot -Severity Error -Recurse -ErrorAction SilentlyContinue + if ($PSScriptAnalyzerErrors -ne $null) { + Write-Warning -Message 'There are PSScriptAnalyzer errors that need to be fixed:' + @($PSScriptAnalyzerErrors).Foreach( { Write-Warning -Message "$($_.Scriptname) (Line $($_.Line)): $($_.Message)" } ) + Write-Warning -Message 'For instructions on how to run PSScriptAnalyzer on your own machine, please go to https://github.com/powershell/psscriptAnalyzer/' + @($PSScriptAnalyzerErrors).Count | Should Be 0 + } + } + } + } + + # Force convert to array + $psm1Files = @( + Get-ChildItem -Path $RepoRoot\DscResources -Recurse -Filter '*.psm1' -File | + Foreach-Object { + # Ignore Composite configurations + # They requires additional resources to be installed on the box + if (-not ($_.Name -like '*.schema.psm1')) + { + $MofFileName = "$($_.BaseName).schema.mof" + $MofFilePath = Join-Path -Path $_.DirectoryName -ChildPath $MofFileName + if (Test-Path -Path $MofFilePath -ErrorAction SilentlyContinue) + { + Write-Output -InputObject $_ + } + } + } + ) + + if (-not $psm1Files) { + Write-Verbose -Verbose 'There are no resource files to analyze' + } else { + + Write-Verbose -Verbose "Analyzing $($psm1Files.Count) resources" + + Context 'Correctness' { + + function Get-ParseErrors + { + param( + [Parameter(ValueFromPipeline=$True,Mandatory=$True)] + [string]$fileName + ) + + $tokens = $null + $errors = $null + $ast = [System.Management.Automation.Language.Parser]::ParseFile($fileName, [ref] $tokens, [ref] $errors) + return $errors + } + + + It 'all .psm1 files don''t have parse errors' { + $errors = @() + $psm1Files | ForEach-Object { + $localErrors = Get-ParseErrors $_.FullName + if ($localErrors) { + Write-Warning "There are parsing errors in $($_.FullName)" + Write-Warning ($localErrors | Format-List | Out-String) + } + $errors += $localErrors + } + $errors.Count | Should Be 0 + } + } + + foreach ($psm1file in $psm1Files) + { + Context "Schema Validation of $($psm1file.BaseName)" { + + It 'should pass Test-xDscResource' { + $result = Test-xDscResource -Name $psm1file.DirectoryName + $result | Should Be $true + } + + It 'should pass Test-xDscSchema' { + $Splat = @{ + Path = $psm1file.DirectoryName + ChildPath = "$($psm1file.BaseName).schema.mof" + } + $result = Test-xDscSchema -Path (Join-Path @Splat -Resolve -ErrorAction Stop) + $result | Should Be $true + } + } + } + } + } +} +finally +{ + # Restore PSModulePath + if ($script:OldModulePath -ne $env:PSModulePath) + { + $env:PSModulePath = $OldModulePath + } +} diff --git a/DSCResource.Tests/MetaFixers.psm1 b/DSCResource.Tests/MetaFixers.psm1 new file mode 100644 index 0000000..780cdb4 --- /dev/null +++ b/DSCResource.Tests/MetaFixers.psm1 @@ -0,0 +1,115 @@ +<# + This module helps fix problems, found by Meta.Tests.ps1 +#> + +$ErrorActionPreference = 'stop' +Set-StrictMode -Version latest + +function ConvertTo-UTF8() +{ + [CmdletBinding()] + [OutputType([void])] + param( + [Parameter(ValueFromPipeline=$true, Mandatory=$true)] + [System.IO.FileInfo]$fileInfo + ) + + process + { + $content = Get-Content -Raw -Encoding Unicode -Path $fileInfo.FullName + [System.IO.File]::WriteAllText($fileInfo.FullName, $content, [System.Text.Encoding]::UTF8) + } +} + +function ConvertTo-ASCII() +{ + [CmdletBinding()] + [OutputType([void])] + param( + [Parameter(ValueFromPipeline=$true, Mandatory=$true)] + [System.IO.FileInfo]$fileInfo + ) + + process + { + $content = Get-Content -Raw -Encoding Unicode -Path $fileInfo.FullName + [System.IO.File]::WriteAllText($fileInfo.FullName, $content, [System.Text.Encoding]::ASCII) + } +} + +function ConvertTo-SpaceIndentation() +{ + [CmdletBinding()] + [OutputType([void])] + param( + [Parameter(ValueFromPipeline=$true, Mandatory=$true)] + [System.IO.FileInfo]$fileInfo + ) + + process + { + $content = (Get-Content -Raw -Path $fileInfo.FullName) -replace "`t",' ' + [System.IO.File]::WriteAllText($fileInfo.FullName, $content) + } +} + +function Get-TextFilesList +{ + [CmdletBinding()] + [OutputType([System.IO.FileInfo])] + param( + [Parameter(Mandatory=$true)] + [string]$root + ) + ls -File -Recurse $root | ? { @('.gitignore', '.gitattributes', '.ps1', '.psm1', '.psd1', '.json', '.xml', '.cmd', '.mof') -contains $_.Extension } +} + +function Test-FileUnicode +{ + + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(ValueFromPipeline=$true, Mandatory=$true)] + [System.IO.FileInfo]$fileInfo + ) + + process + { + + $path = $fileInfo.FullName + $bytes = [System.IO.File]::ReadAllBytes($path) + $zeroBytes = @($bytes -eq 0) + return [bool]$zeroBytes.Length + + } +} + +function Get-UnicodeFilesList() +{ + [CmdletBinding()] + [OutputType([System.IO.FileInfo])] + param( + [Parameter(Mandatory=$true)] + [string]$root + ) + + Get-TextFilesList $root | ? { Test-FileUnicode $_ } +} + +function Add-NewLine() +{ + [CmdletBinding()] + [OutputType([void])] + param( + [Parameter(ValueFromPipeline=$true, Mandatory=$true)] + [System.IO.FileInfo]$fileInfo + ) + + process + { + $content = Get-Content -Raw -Path $fileInfo.FullName + $content += "`r`n" + [System.IO.File]::WriteAllText($fileInfo.FullName, $content) + } +} diff --git a/DSCResource.Tests/README.md b/DSCResource.Tests/README.md new file mode 100644 index 0000000..0d0fe7f --- /dev/null +++ b/DSCResource.Tests/README.md @@ -0,0 +1,115 @@ +# DscResource.Tests +Common meta tests for PowerShell DSC resources repositories. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +## DscResourceCommonTests +### Unreleased +* Extra whitespace trimmed from TestHelper.psm1 (feature of VS Code). +* Removed code to Remove-Module from Initialize-TestEnvironment because not required: Import-Module -force should do the same thing. +* Initialize-TestEnvironment changed to import module being tested into Global scope so that InModuleScope not required in tests. + +### 0.2.0.0 +* Fixed unicode and path bugs in tests + +### 0.1.0.0 +* Initial release + +## DscResourceTestHelper +### Unreleased + +### 0.2.0.0 +* Fixed unicode and path bugs in tests + +### 0.1.0.0 +* Initial release + +## Goals + +1. Consistency in encoding and indentations. +Consistency is good by itself. But more important it allows us to: +2. Avoid big diffs with cosmetic changes in Pull Requests. +Cosmetic changes (like formatting) make reviews harder. +If you want to include formatting changes (like replacing `"` by `'`), +please make it a **separate commit**. +This will give reviewers an option to review meaningful changes separately from formatting changes. + + +## Git and Unicode + +By default git treats [unicode files as binary files](http://stackoverflow.com/questions/6855712/why-does-git-treat-this-text-file-as-a-binary-file). +You may not notice it if your client (like VS or GitHub for Windows) takes care of such conversion. +History with Unicode files is hardly usable from command line `git`. + +``` +> git diff + diff --git a/xActiveDirectory.psd1 b/xActiveDirectory.psd1 + index 0fc1914..55fdb85 100644 +Binary files a/xActiveDirectory.psd1 and b/xActiveDirectory.psd1 differ +``` + +With forced `--text` option it would look like this: + +``` +> git diff --text + diff --git a/xActiveDirectory.psd1 b/xActiveDirectory.psd1 + index 0fc1914..55fdb85 100644 + --- a/xActiveDirectory.psd1 + +++ b/xActiveDirectory.psd1 +@@ -30,4 +30,4 @@ + C m d l e t s T o E x p o r t = ' * ' + + } + + + + - + \ No newline at end of file + + # h e l l o + \ No newline at end of file +``` + +Command line `git` version is a core component and should be used as a common denominator. + + +## MetaFixers Module + +We are trying to provide automatic fixers where it's appropriate. A fixer corresponds to a particular test. + +For example, if `Files encoding` test from [Meta.Tests.ps1](Meta.Tests.ps1) test fails, you should be able to run `ConvertTo-UTF8` fixer from [MetaFixers.psm1](MetaFixers.psm1). + + +## TestHelper Module + +The test helper module (TestHelper.psm1) contains the following functions: +**New-Nuspec**: Creates a new nuspec file for nuget package. +**Install-ResourceDesigner**: Will attempt to download the xDSCResourceDesignerModule using Nuget package and return the module. +**Initialize-TestEnvironment**: Initializes an environment for running unit or integration tests on a DSC resource. +**Restore-TestEnvironment**: Restores the environment after running unit or integration tests on a DSC resource. + + +## Templates for Creating Tests + +The Template files that are used for creating Unit and Integration tests for a DSC resource are available in the [DSCResources GitHub Repository](https://github.com/PowerShell/DscResources) in the [Tests.Template folder](https://github.com/PowerShell/DscResources/tree/master/Tests.Template) + +To use these files, see the [test guidelines](https://github.com/PowerShell/DscResources/blob/master/TestsGuidelines.md) document and the instructions at the top of each template file. + +The resource files are: +*[Unit_Template.ps1](https://github.com/PowerShell/DscResources/blob/master/Tests.Template/unit_template.ps1)**: Use to create a set of Unit Pester tests for a single DSC Resource. +**[Integration_Template.ps1](https://github.com/PowerShell/DscResources/blob/master/Tests.Template/integration_template.ps1)**: Use to create a set of Integration Pester tests for a single DSC Resource. +**[Integration_Config_Template.ps1](https://github.com/PowerShell/DscResources/blob/master/Tests.Template/unit_template.ps1)**: Use to create a DSC Configuration file for a single DSC Resource. Used in conjunction with Integration_Template.ps1. + + +## Example Test Usage + +To see examples of the Unit/Integration tests in practice, see the xNetworking MSFT_xFirewall resource: +[Unit Tests](https://github.com/PowerShell/xNetworking/blob/dev/Tests/Unit/MSFT_xFirewall.Tests.ps1) +[Integration Tests](https://github.com/PowerShell/xNetworking/blob/dev/Tests/Integration/MSFT_xFirewall.Integration.Tests.ps1) +[Resource DSC Configuration](https://github.com/PowerShell/xNetworking/blob/dev/Tests/Integration/MSFT_xFirewall.config.ps1) + + +## Example Usage of DSCResource.Tests in AppVeyor.yml + +To automatically download and install the DscResource.Tests in an AppVeyor.yml file, please see the following sample AppVeyor.yml. +[https://github.com/PowerShell/DscResources/blob/master/DscResource.Template/appveyor.yml](https://github.com/PowerShell/DscResources/blob/master/DscResource.Template/appveyor.yml) diff --git a/DSCResource.Tests/TestHelper.psm1 b/DSCResource.Tests/TestHelper.psm1 new file mode 100644 index 0000000..1a58858 --- /dev/null +++ b/DSCResource.Tests/TestHelper.psm1 @@ -0,0 +1,456 @@ +<# + Script Constants used by *-ResourceDesigner Functions +#> +<# + .SYNOPSIS Creates a new nuspec file for nuget package. + Will create $packageName.nuspec in $destinationPath + + .EXAMPLE + New-Nuspec -packageName "TestPackage" -version 1.0.1 -licenseUrl "http://license" -packageDescription "description of the package" -tags "tag1 tag2" -destinationPath C:\temp +#> +function New-Nuspec +{ + param + ( + [Parameter(Mandatory=$true)] + [string] $packageName, + [Parameter(Mandatory=$true)] + [string] $version, + [Parameter(Mandatory=$true)] + [string] $author, + [Parameter(Mandatory=$true)] + [string] $owners, + [string] $licenseUrl, + [string] $projectUrl, + [string] $iconUrl, + [string] $packageDescription, + [string] $releaseNotes, + [string] $tags, + [Parameter(Mandatory=$true)] + [string] $destinationPath + ) + + $year = (Get-Date).Year + + $content += +" + + + $packageName + $version + $author + $owners" + + if (-not [string]::IsNullOrEmpty($licenseUrl)) + { + $content += " + $licenseUrl" + } + + if (-not [string]::IsNullOrEmpty($projectUrl)) + { + $content += " + $projectUrl" + } + + if (-not [string]::IsNullOrEmpty($iconUrl)) + { + $content += " + $iconUrl" + } + + $content +=" + true + $packageDescription + $releaseNotes + Copyright $year + $tags + +" + + if (-not (Test-Path -Path $destinationPath)) + { + New-Item -Path $destinationPath -ItemType Directory > $null + } + + $nuspecPath = Join-Path $destinationPath "$packageName.nuspec" + New-Item -Path $nuspecPath -ItemType File -Force > $null + Set-Content -Path $nuspecPath -Value $content +} + +<# + .SYNOPSIS + Will attempt to download the module from PowerShellGallery using + Nuget package and return the module. + + If already installed will return the module without making changes. + + If module could not be downloaded it will return null. + + .PARAMETER Force + Used to force any installations to occur without confirming with + the user. + + .PARAMETER moduleName + Name of the module to install + + .PARAMETER modulePath + Path where module should be installed + + .EXAMPLE + Install-ModuleFromPowerShellGallery + + .EXAMPLE + if ($env:APPVEYOR) { + # Running in AppVeyor so force silent install of xDSCResourceDesigner + $PSBoundParameters.Force = $true + } + + $xDSCResourceDesignerModuleName = "xDscResourceDesigner" + $xDSCResourceDesignerModulePath = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\$xDSCResourceDesignerModuleName" + $xDSCResourceDesignerModule = Install-ModuleFromPowerShellGallery -ModuleName $xDSCResourceDesignerModuleName -ModulePath $xDSCResourceDesignerModulePath @PSBoundParameters +#> +function Install-ModuleFromPowerShellGallery { + [OutputType([System.Management.Automation.PSModuleInfo])] + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High')] + Param + ( + [Parameter(Mandatory=$true)] + [String] $moduleName, + + [Parameter(Mandatory=$true)] + [String] $modulePath, + + [Boolean]$Force = $false + ) + + $module = Get-Module -Name $moduleName -ListAvailable + if (@($module).Count -ne 0) + { + # Module is already installed - report it. + Write-Host -Object (` + 'Version {0} of the {1} module is already installed.' ` + -f $($module.Version -join ', '),$moduleName + ) -ForegroundColor:Yellow + # Could check for a newer version available here in future and perform an update. + # Return only the latest version of the module + return $module ` + | Sort-Object -Property Version -Descending ` + | Select-Object -First 1 + } + + Write-Verbose -Message (` + 'The {0} module is not installed.' ` + -f $moduleName + ) + + $OutputDirectory = "$(Split-Path -Path $modulePath -Parent)\" + + # Use Nuget directly to download the module + $nugetPath = 'nuget.exe' + + # Can't assume nuget.exe is available - look for it in Path + if ((Get-Command $nugetPath -ErrorAction SilentlyContinue) -eq $null) + { + # Is it in temp folder? + $nugetPath = Join-Path -Path $ENV:Temp -ChildPath $nugetPath + if (-not (Test-Path -Path $nugetPath)) + { + # Nuget.exe can't be found - download it to temp folder + $NugetDownloadURL = 'http://nuget.org/nuget.exe' + If ($Force -or $PSCmdlet.ShouldProcess( ` + "Download Nuget.exe from '{0}' to Temp folder" ` + -f $NugetDownloadURL)) + { + Invoke-WebRequest $NugetDownloadURL -OutFile $nugetPath + + Write-Verbose -Message (` + "Nuget.exe was installed from '{0}' to Temp folder." ` + -f $NugetDownloadURL + ) + } + else + { + # Without Nuget.exe we can't continue + Write-Warning -Message (` + 'Nuget.exe was not installed. {0} module can not be installed automatically.' ` + -f $moduleName + ) + return $null + } + } + else + { + Write-Verbose -Message 'Using Nuget.exe found in Temp folder.' + } + } + + $nugetSource = 'https://www.powershellgallery.com/api/v2' + If ($Force -or $PSCmdlet.ShouldProcess(( ` + "Download and install the {0} module from '{1}' using Nuget" ` + -f $moduleName,$nugetSource))) + { + # Use Nuget.exe to install the module + $null = & "$nugetPath" @( ` + 'install', $moduleName, ` + '-source', $nugetSource, ` + '-outputDirectory', $OutputDirectory, ` + '-ExcludeVersion' ` + ) + $ExitCode = $LASTEXITCODE + + if ($ExitCode -ne 0) + { + throw ( + 'Installation of {0} module using Nuget failed with exit code {1}.' ` + -f $moduleName,$ExitCode + ) + } + Write-Host -Object (` + 'The {0} module was installed using Nuget.' ` + -f $moduleName + ) -ForegroundColor:Yellow + } + else + { + Write-Warning -Message (` + '{0} module was not installed automatically.' ` + -f $moduleName + ) + return $null + } + + return (Get-Module -Name $moduleName -ListAvailable) +} + +<# + .SYNOPSIS + Initializes an enviroment for running unit or integration tests + on a DSC resource. + + This includes the following things: + 1. Creates a temporary working folder. + 2. Updates the $env:PSModulePath to ensure the correct module is tested. + 3. Backs up any settings that need to be changed to accurately test + the resource. + 4. Produces a test object containing any parameters that may be used + for testing as well as storing the backed up settings. + + The above changes are reverted by calling the Restore-TestEnvironment + function. This includes deleteing the temporary working folder. + + .PARAMETER DSCModuleName + The name of the DSC Module containing the resource that the tests will be + run on. + + .PARAMETER DSCResourceName + The full name of the DSC resource that the tests will be run on. This is + usually the name of the folder containing the actual resource MOF file. + + .PARAMETER TestType + Specifies the type of tests that are being intialized. It can be: + Unit: Initialize for running Unit tests on a DSC resource. Default. + Integration: Initialize for running Integration tests on a DSC resource. + + .OUTPUT + Returns a test environment object which must be passed to the + Restore-TestEnvironment function to allow it to restore the system + back to the original state as well as clean up and working/temp files. + + .EXAMPLE + $TestEnvironment = Inialize-TestEnvironment ` + -DSCModuleName 'xNetworking' ` + -DSCResourceName 'MSFT_xFirewall' ` + -TestType Unit + + This command will initialize the test enviroment for Unit testing + the MSFT_xFirewall DSC resource in the xNetworking DSC module. + + .EXAMPLE + $TestEnvironment = Inialize-TestEnvironment ` + -DSCModuleName 'xNetworking' ` + -DSCResourceName 'MSFT_xFirewall' ` + -TestType Integration + + This command will initialize the test enviroment for Integration testing + the MSFT_xFirewall DSC resource in the xNetworking DSC module. +#> +function Initialize-TestEnvironment +{ + [OutputType([PSObject])] + [CmdletBinding()] + Param + ( + [Parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [String] $DSCModuleName, + + [Parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [String] $DSCResourceName, + + [Parameter(Mandatory=$true)] + [ValidateSet('Unit','Integration')] + [String] $TestType + ) + + Write-Host -Object (` + 'Initializing Test Environment for {0} testing of {1} in module {2}.' ` + -f $TestType,$DSCResourceName,$DSCModuleName) -ForegroundColor:Yellow + if ($TestType -eq 'Unit') + { + [String] $RelativeModulePath = "DSCResources\$DSCResourceName\$DSCResourceName.psm1" + } + else + { + [String] $RelativeModulePath = "$DSCModuleName.psd1" + } + + # Unique Temp Working Folder - always gets removed on completion + # The tests can put anything in here and it will get cleaned up. + [String] $RandomFileName = [System.IO.Path]::GetRandomFileName() + [String] $WorkingFolder = Join-Path -Path $env:Temp -ChildPath "$DSCResourceName_$RandomFileName" + # Create the working folder if it doesn't exist (it really shouldn't anyway) + if (-not (Test-Path -Path $WorkingFolder)) + { + New-Item -Path $WorkingFolder -ItemType Directory + } + + # Determine the root folder of this module by stepping up the path until the disk root is found + # or the DSC Module Manifest is found. + [String] $Path = $Script:MyInvocation.MyCommand.Path + [String] $DiskRoot = [System.IO.Path]::GetPathRoot($Path) + while (($Path -ne $DiskRoot) -and (-not [String]::IsNullOrEmpty($Path))) + { + # Does the Path contain the Resource Module? + if (Test-Path -Path (Join-Path -Path $Path -ChildPath "$DSCModuleName.psd1")) + { + # The Module Root folder has been found + [String] $moduleRoot = $Path + break + } + $Path = Split-Path -Path $Path -Parent + } # while + + # Check that the Module Root was found + if (-not $ModuleRoot) + { + Throw "The DSC Module Manifest '$DSCModuleName.psd1' could not be found or it was found in the root folder on the disk." + } # if + Write-Host -Object (` + "DSC Module Manifest '{0}.psd1' detected in folder '{1}'." ` + -f $DSCModuleName,$ModuleRoot) -ForegroundColor:Yellow + + # The folder that all tests will find this module in + [string] $modulesFolder = Split-Path -Parent $moduleRoot + + # Import the Module + $Splat = @{ + Path = $moduleRoot + ChildPath = $RelativeModulePath + Resolve = $true + ErrorAction = 'Stop' + } + $DSCModuleFile = Get-Item -Path (Join-Path @Splat) + + # Import the Module to test. + Import-Module -Name $DSCModuleFile.FullName -Force -Scope Global + + # Set the PSModulePath environment variable so that the module path this module is in + # appears first because the LCM will use this path to try and locate modules when integration + # tests are called. This is to ensure the correct module is tested. + [String] $OldModulePath = $env:PSModulePath + [String] $NewModulePath = $OldModulePath + if (($NewModulePath).Split(';') -ccontains $modulesFolder) + { + # Remove the existing module from the module path if it exists + $NewModulePath = ($NewModulePath -split ';' | Where-Object {$_ -ne $modulesFolder}) -join ';' + } + $NewModulePath = "$modulesFolder;$NewModulePath" + $env:PSModulePath = $NewModulePath + if ($TestType -eq 'integration') { + # For integration tests we have to set the Machine PSModulePath because otherwise the DSC + # LCM won't be able to find the Resource module being tested and may use the wrong one. + [System.Environment]::SetEnvironmentVariable('PSModulePath',$NewModulePath,[System.EnvironmentVariableTarget]::Machine) + } + + # Preserve and set the execution policy so that the DSC MOF can be created + $OldExecutionPolicy = Get-ExecutionPolicy + if ($OldExecutionPolicy -ne 'Unrestricted') + { + Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force + } + + # Generate the test environment object that will be returned + $TestEnvironment = @{ + DSCModuleName = $DSCModuleName + DSCResourceName = $DSCResourceName + TestType = $TestType + RelativeModulePath = $RelativeModulePath + WorkingFolder = $WorkingFolder + OldModulePath = $OldModulePath + OldExecutionPolicy = $OldExecutionPolicy + } + + return $TestEnvironment +} + +<# + .SYNOPSIS + Restores the enviroment after running unit or integration tests + on a DSC resource. + + This restores the following changes made by calling + Initialize-TestEnvironemt: + 1. Deletes the Working folder. + 2. Restores the $env:PSModulePath if it was changed. + 3. Restores any settings that were changed to test the resource. + + .PARAMETER TestEnvironment + This is the object created by the Initialize-TestEnvironment + cmdlet. + + .EXAMPLE + Restore-TestEnvironment -TestEnvironment $TestEnvironment + + This command will initialize the test enviroment for Unit testing + the MSFT_xFirewall DSC resource in the xNetworking DSC module. +#> +function Restore-TestEnvironment +{ + [CmdletBinding()] + Param + ( + [Parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [PSObject] $TestEnvironment + ) + + Write-Verbose -Message (` + 'Cleaning up Test Environment after {0} testing of {1} in module {2}.' ` + -f $TestEnvironment.TestType,$TestEnvironment.DSCResourceName,$TestEnvironment.DSCModuleName) + + # Restore PSModulePath + if ($TestEnvironment.OldModulePath -ne $env:PSModulePath) + { + $env:PSModulePath = $TestEnvironment.OldModulePath + if ($TestType -eq 'integration') { + # Restore the machine PSModulePath for integration tests. + [System.Environment]::SetEnvironmentVariable('PSModulePath',$env:PSModulePath,[System.EnvironmentVariableTarget]::Machine) + } + } + + # Restore the Execution Policy + if ($TestEnvironment.OldExecutionPolicy -ne (Get-ExecutionPolicy)) + { + Set-ExecutionPolicy -ExecutionPolicy $TestEnvironment.OldExecutionPolicy -Force + } + + # Cleanup Working Folder + if (Test-Path -Path $TestEnvironment.WorkingFolder) + { + Remove-Item -Path $TestEnvironment.WorkingFolder -Recurse -Force + } +} diff --git a/DSCResource.Tests/TestRunner.psm1 b/DSCResource.Tests/TestRunner.psm1 new file mode 100644 index 0000000..94b7a14 --- /dev/null +++ b/DSCResource.Tests/TestRunner.psm1 @@ -0,0 +1,25 @@ +<# + .SYNOPSIS Runs tests on all DSC resources in given folder (including common tests) + .PARAM + resourcesPath Path where DSC resource modules have been cloned (tests will run for all modules in that path) + .EXAMPLE + Start-DscResourceTests -resourcesPath C:\DscResources\xDscResources +#> +function Start-DscResourceTests +{ + param( + [String] $resourcesPath + ) + + $testsPath = $pwd + cd $resourcesPath + ls | % { + $module = $_.Name + Write-Host "Copying common tests from $testsPath to $resourcesPath\$module" -ForegroundColor Yellow + Copy-Item $testsPath "$resourcesPath\$module" -recurse -force + cd $module + Write-Host "Running tests for $module" -ForegroundColor Yellow + Invoke-Pester + cd .. + } +} diff --git a/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 b/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 new file mode 100644 index 0000000..83bda61 --- /dev/null +++ b/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 @@ -0,0 +1,229 @@ +function Get-TargetResource +{ + param( + [Parameter(Mandatory = $true)] + [String] + $Path, + + [Parameter(Mandatory = $true)] + [String] + $Identity, + + [Parameter(Mandatory = $false)] + [String[]] + [ValidateSet("ListDirectory", + "ReadData", + "WriteData", + "CreateFiles", + "CreateDirectories", + "AppendData", + "ReadExtendedAttributes", + "WriteExtendedAttributes", + "Traverse", + "ExecuteFile", + "DeleteSubdirectoriesAndFiles", + "ReadAttributes", + "WriteAttributes", + "Write", + "Delete", + "ReadPermissions", + "Read", + "ReadAndExecute", + "Modify", + "ChangePermissions", + "TakeOwnership", + "Synchronize", + "FullControl")] + $Rights, + + [Parameter(Mandatory = $false)] + [String] + [ValidateSet("Present","Absent")] + $Ensure = "Present" + ) + + if ((Test-Path -Path $Path) -eq $false) + { + throw "Unable to get ACL for '$Path' as it does not exist" + } + + $acl = Get-Acl -Path $Path + $accessRules = $acl.Access + + $identityRule = $accessRules | Where-Object -FilterScript { + $_.IdentityReference -eq $Identity + } | Select-Object -First 1 + + if ($null -eq $identityRule) + { + return @{ + Path = $Path + Identity = $Identity + Rights = @() + Ensure = "Absent" + } + } + return @{ + Path = $Path + Identity = $Identity + Rights = $identityRule.FileSystemRights.ToString() -split ", " + Ensure = "Present" + } +} + +function Set-TargetResource +{ + param( + [Parameter(Mandatory = $true)] + [String] + $Path, + + [Parameter(Mandatory = $true)] + [String] + $Identity, + + [Parameter(Mandatory = $false)] + [String[]] + [ValidateSet("ListDirectory", + "ReadData", + "WriteData", + "CreateFiles", + "CreateDirectories", + "AppendData", + "ReadExtendedAttributes", + "WriteExtendedAttributes", + "Traverse", + "ExecuteFile", + "DeleteSubdirectoriesAndFiles", + "ReadAttributes", + "WriteAttributes", + "Write", + "Delete", + "ReadPermissions", + "Read", + "ReadAndExecute", + "Modify", + "ChangePermissions", + "TakeOwnership", + "Synchronize", + "FullControl")] + $Rights, + + [Parameter(Mandatory = $false)] + [String] + [ValidateSet("Present","Absent")] + $Ensure = "Present" + ) + + if ((Test-Path -Path $Path) -eq $false) + { + throw "Unable to get ACL for '$Path' as it does not exist" + } + + $acl = Get-Acl -Path $Path + $accessRules = $acl.Access + + if ($Ensure -eq "Present") + { + Write-Verbose -Message "Setting access rules for $Identity on $Path" + $newRights = [System.Security.AccessControl.FileSystemRights]$Rights + $ar = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule ` + -ArgumentList @( + $Identity, + $newRights, + "ContainerInherit,ObjectInherit", + "None", + "Allow") + $acl.SetAccessRule($ar) + + Set-Acl -Path $Path -AclObject $acl + + } + + if ($Ensure -eq "Absent") + { + $identityRule = $accessRules | Where-Object -FilterScript { + $_.IdentityReference -eq $Identity + } | Select-Object -First 1 + + if ($null -ne $identityRule) + { + Write-Verbose -Message "Removing access rules for $Identity on $Path" + $acl.RemoveAccessRule($identityRule) | Out-Null + Set-Acl -Path $Path -AclObject $acl + } + } +} + +function Test-TargetResource +{ + param( + [Parameter(Mandatory = $true)] + [String] + $Path, + + [Parameter(Mandatory = $true)] + [String] + $Identity, + + [Parameter(Mandatory = $false)] + [String[]] + [ValidateSet("ListDirectory", + "ReadData", + "WriteData", + "CreateFiles", + "CreateDirectories", + "AppendData", + "ReadExtendedAttributes", + "WriteExtendedAttributes", + "Traverse", + "ExecuteFile", + "DeleteSubdirectoriesAndFiles", + "ReadAttributes", + "WriteAttributes", + "Write", + "Delete", + "ReadPermissions", + "Read", + "ReadAndExecute", + "Modify", + "ChangePermissions", + "TakeOwnership", + "Synchronize", + "FullControl")] + $Rights, + + [Parameter(Mandatory = $false)] + [String] + [ValidateSet("Present","Absent")] + $Ensure = "Present" + ) + + $CurrentValues = Get-TargetResource @PSBoundParameters + + if ($null -eq $CurrentValues) + { + throw "Unable to determine current ACL values for '$Path'" + } + + if ($CurrentValues.Ensure -ne $Ensure) + { + Write-Verbose -Message "Ensure property does not match" + return $false + } + + if ($Ensure -eq "Present") + { + $rightsCompare = Compare-Object -ReferenceObject $CurrentValues.Rights ` + -DifferenceObject $Rights + if ($null -ne $rightsCompare) + { + Write-Verbose -Message "Rights property does not match" + return $false + } + } + + return $true +} + +Export-ModuleMember -Function *-TargetResoruce diff --git a/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.schema.mof b/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.schema.mof new file mode 100644 index 0000000..daf6d8d --- /dev/null +++ b/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.schema.mof @@ -0,0 +1,8 @@ +[ClassVersion("1.0.0.0"), FriendlyName("xFileSystemAccessRule")] +class MSFT_xFileSystemAccessRule : OMI_BaseResource +{ + [Key, Description("The path to the item that should have permissions set")] string Path; + [Key, Description("The identity to set permissions for")] string Identity; + [Write, Description("The permissions to include in this rule, can be empty if ensure = absent"), ValueMap{"ListDirectory","ReadData","WriteData","CreateFiles","CreateDirectories","AppendData","ReadExtendedAttributes","WriteExtendedAttributes","Traverse","ExecuteFile","DeleteSubdirectoriesAndFiles","ReadAttributes","WriteAttributes","Write","Delete","ReadPermissions","Read","ReadAndExecute","Modify","ChangePermissions","TakeOwnership","Synchronize","FullControl"}, Values{"ListDirectory","ReadData","WriteData","CreateFiles","CreateDirectories","AppendData","ReadExtendedAttributes","WriteExtendedAttributes","Traverse","ExecuteFile","DeleteSubdirectoriesAndFiles","ReadAttributes","WriteAttributes","Write","Delete","ReadPermissions","Read","ReadAndExecute","Modify","ChangePermissions","TakeOwnership","Synchronize","FullControl"}] string Rights[]; + [Write, Description("Present to create the rule, Absent to remove an existing rule"), ValueMap{"Present","Absent"}, Values{"Present","Absent"}] string Ensure; +}; diff --git a/README.md b/README.md index e64e6dc..55b10e0 100644 --- a/README.md +++ b/README.md @@ -50,16 +50,46 @@ Please check out common DSC Resources [contributing guidelines](https://github.c If you are logged on as a standard user, any changes that require the permissions of an administrator will automatically be denied. If you select this setting, you will need to restart the computer to complete the process of turning off UAC. Once UAC is off, people that log on as administrator will always have the permissions of an administrator. - This is the least secure setting same as NeverNotify, but in addition EnableLUA registry key is disabled. + This is the least secure setting same as �NeverNotify�, but in addition EnableLUA registry key is disabled. EnableLUA controls the behavior of all UAC policy settings for the computer. If you change this policy setting, you must restart your computer - We do not recommend using this setting, but it can be selected for systems that use programs that are not certified for Windows 8, Windows Server 2012, Windows 7 or Windows Server 2008 R2 because they do not support UAC. + We do not recommend using this setting, but it can be selected for systems that use programs that are not certified for Windows� 8, Windows Server� 2012, Windows� 7 or Windows Server� 2008 R2 because they do not support UAC. ### xIEEsc * **UserRole**: Enable or Disable ESC for **Administrators** or **Users**. * **IsEnabled**: Determines if ESC is **Enabled** or **Disabled**. +### xFileSystemAccessRule + +* **Path**: The path to the item that should have permissions set +* **Identity**: The identity to set permissions for +* **Rights**: The permissions to include in this rule, can be empty if ensure = absent. Should be a combination of the following: + * "ListDirectory" + * "ReadData" + * "WriteData" + * "CreateFiles" + * "CreateDirectories" + * "AppendData" + * "ReadExtendedAttributes" + * "WriteExtendedAttributes" + * "Traverse" + * "ExecuteFile" + * "DeleteSubdirectoriesAndFiles" + * "ReadAttributes" + * "WriteAttributes" + * "Write" + * "Delete" + * "ReadPermissions" + * "Read" + * "ReadAndExecute" + * "Modify" + * "ChangePermissions" + * "TakeOwnership" + * "Synchronize" + * "FullControl" +* **Ensure**: Present to create the rule, Absent to remove an existing rule + Please refer to [this article](http://technet.microsoft.com/en-us/library/dd883248(v=ws.10).aspx) for the effects and security impact of Enhanced Security Configuration. @@ -67,6 +97,7 @@ Please refer to [this article](http://technet.microsoft.com/en-us/library/dd8832 ### Unreleased * Converted appveyor.yml to install Pester from PSGallery instead of from Chocolatey. +* Added xFileSystemAccessRule resource ### 1.1.0.0 @@ -118,3 +149,24 @@ Configuration DisableLocalIEEsc } } ``` + +### Sets a permission on a specific folder + +This configuration will grant the network service account full control over the directory. + +```powershell +Configuration DisableLocalIEEsc +{ + Import-DSCResource -Module MSFT_xSystemSecurity + + Node localhost + { + xFileSystemAccessRule FullControlExample + { + Path = "C:\some\path" + Identity = "NT AUTHORITY\NETWORK SERVICE" + Rights = @("FullControl") + } + } +} +``` \ No newline at end of file diff --git a/Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1 b/Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1 new file mode 100644 index 0000000..43a55de --- /dev/null +++ b/Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1 @@ -0,0 +1,33 @@ +configuration MSFT_xFileSystemAccessRule_NewRule { + Import-DscResource -ModuleName 'xSystemSecurity' + node localhost { + xFileSystemAccessRule Integration_Test { + Path = "TestDrive:\SampleFolder" + Identity = "NT AUTHORITY\NETWORK SERVICE" + Rights = @("Read","Synchronize") + } + } +} + +configuration MSFT_xFileSystemAccessRule_UpdateRule { + Import-DscResource -ModuleName 'xSystemSecurity' + node localhost { + xFileSystemAccessRule Integration_Test { + Path = "TestDrive:\SampleFolder" + Identity = "NT AUTHORITY\NETWORK SERVICE" + Rights = @("FullControl") + } + } +} + +configuration MSFT_xFileSystemAccessRule_RemoveRule { + Import-DscResource -ModuleName 'xSystemSecurity' + node localhost { + xFileSystemAccessRule Integration_Test { + Path = "TestDrive:\SampleFolder" + Identity = "NT AUTHORITY\NETWORK SERVICE" + Ensure = "Absent" + } + } +} + diff --git a/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 b/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 new file mode 100644 index 0000000..c80e096 --- /dev/null +++ b/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 @@ -0,0 +1,100 @@ +$script:DSCModuleName = 'xSystemSecurity' +$script:DSCResourceName = 'MSFT_xFileSystemAccessRule' + +[String] $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) +if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) +{ + & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) +} + +Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force +$TestEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:DSCModuleName ` + -DSCResourceName $script:DSCResourceName ` + -TestType Integration + +try +{ + $ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1" + . $ConfigFile + + Describe "$($script:DSCResourceName)_Integration" { + + BeforeAll { + New-Item -Path "TestDrive:\SampleFolder" + } + AfterAll { + Remove-Item "TestDrive:\SampleFolder" + } + + It 'New rule - Should compile without throwing' { + { + Invoke-Expression -Command "$($script:DSCResourceName)_NewRule -OutputPath `$TestEnvironment.WorkingFolder" + } | Should not throw + } + + It "New rule - Should apply without throwing" { + { + Start-DscConfiguration -Path $TestEnvironment.WorkingFolder ` + -ComputerName localhost -Wait -Verbose -Force + } | Should not throw + } + + It 'New rule - Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw + } + + It 'New rule - Should have set the resource and all the parameters should match' { + Test-DscConfiguration -Path $TestEnvironment.WorkingFolder | Should Be $true + } + + + It 'Update rule - Should compile without throwing' { + { + Invoke-Expression -Command "$($script:DSCResourceName)_UpdateRule -OutputPath `$TestEnvironment.WorkingFolder" + } | Should not throw + } + + It "Update rule - Should apply without throwing" { + { + Start-DscConfiguration -Path $TestEnvironment.WorkingFolder ` + -ComputerName localhost -Wait -Verbose -Force + } | Should not throw + } + + + It 'Update rule - Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw + } + + It 'Remove rule - Should have set the resource and all the parameters should match' { + Test-DscConfiguration -Path $TestEnvironment.WorkingFolder | Should Be $true + } + + It 'Remove rule - Should compile without throwing' { + { + Invoke-Expression -Command "$($script:DSCResourceName)_RemoveRule -OutputPath `$TestEnvironment.WorkingFolder" + } | Should not throw + } + + It "Remove rule - Should apply without throwing" { + { + Start-DscConfiguration -Path $TestEnvironment.WorkingFolder ` + -ComputerName localhost -Wait -Verbose -Force + } | Should not throw + } + + It 'Remove rule - Should be able to call Get-DscConfiguration without throwing' { + { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw + } + + It 'New rule - Should have set the resource and all the parameters should match' { + Test-DscConfiguration -Path $TestEnvironment.WorkingFolder | Should Be $true + } + } +} +finally +{ + Restore-TestEnvironment -TestEnvironment $TestEnvironment +} \ No newline at end of file diff --git a/Tests/Unit/MSFT_xFileSystemAccessRule.tests.ps1 b/Tests/Unit/MSFT_xFileSystemAccessRule.tests.ps1 new file mode 100644 index 0000000..ba05360 --- /dev/null +++ b/Tests/Unit/MSFT_xFileSystemAccessRule.tests.ps1 @@ -0,0 +1,195 @@ +$script:DSCModuleName = 'xSystemSecurity' +$script:DSCResourceName = 'MSFT_xFileSystemAccessRule' + +[String] $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) +if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) +{ + & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) +} + +Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force +$TestEnvironment = Initialize-TestEnvironment ` + -DSCModuleName $script:DSCModuleName ` + -DSCResourceName $script:DSCResourceName ` + -TestType Unit + +Import-Module (Join-Path $script:moduleRoot "\DSCResources\$script:DSCResourceName\$script:DSCResourceName.psm1") -Force + + +try +{ + Describe "xFileSystemAccessRule" { + InModuleScope -ModuleName $script:DSCResourceName { + + Mock Set-Acl {} + Mock Test-Path { return $true } + + Context "No permissions exist for a user, but should" { + $testParams = @{ + Path = "C:\TestFolder" + Identity = "NT AUTHORITY\NETWORK SERVICE" + Rights = @("Read","Synchronize") + } + Mock Get-Acl { + return @{ + Access = @() + } | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru ` + | Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru + } + + It "should return absent from the get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Absent" + } + + It "should return false from the test method" { + Test-TargetResource @testParams | Should Be $false + } + + It "should add the permission in the set method" { + Set-TargetResource @testParams + Assert-MockCalled -CommandName Set-Acl + } + } + + Context "A permission exists and should, but the rights are incorrect" { + $testParams = @{ + Path = "C:\TestFolder" + Identity = "NT AUTHORITY\NETWORK SERVICE" + Rights = @("Read","Synchronize") + } + Mock Get-Acl { + return @{ + Access = @( + @{ + IdentityReference = $testParams.Identity + FileSystemRights = [System.Security.AccessControl.FileSystemRights]::FullControl + } + ) + } | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru ` + | Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru + } + + It "should return present from the get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Present" + } + + It "should return false from the test method" { + Test-TargetResource @testParams | Should Be $false + } + + It "should add the permission in the set method" { + Set-TargetResource @testParams + Assert-MockCalled -CommandName Set-Acl + } + } + + Context "A permission exists and should, including correct rights" { + $testParams = @{ + Path = "C:\TestFolder" + Identity = "NT AUTHORITY\NETWORK SERVICE" + Rights = @("Read","Synchronize") + } + Mock Get-Acl { + return @{ + Access = @( + @{ + IdentityReference = $testParams.Identity + FileSystemRights = [System.Security.AccessControl.FileSystemRights]$testParams.Rights + } + ) + } | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru ` + | Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru + } + + It "should return present from the get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Present" + } + + It "should return true from the test method" { + Test-TargetResource @testParams | Should Be $true + } + } + + Context "A permission exists that shouldn't" { + $testParams = @{ + Path = "C:\TestFolder" + Identity = "NT AUTHORITY\NETWORK SERVICE" + Ensure = "Absent" + } + Mock Get-Acl { + return @{ + Access = @( + @{ + IdentityReference = $testParams.Identity + FileSystemRights = [System.Security.AccessControl.FileSystemRights]::FullControl + } + ) + } | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru ` + | Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru + } + + It "should return present from the get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Present" + } + + It "should return false from the test method" { + Test-TargetResource @testParams | Should Be $false + } + + It "should add the permission in the set method" { + Set-TargetResource @testParams + Assert-MockCalled -CommandName Set-Acl + } + } + + Context "A permission doesn't exist and shouldn't" { + $testParams = @{ + Path = "C:\TestFolder" + Identity = "NT AUTHORITY\NETWORK SERVICE" + Ensure = "Absent" + } + Mock Get-Acl { + return @{ + Access = @() + } | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru ` + | Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru + } + + It "should return absent from the get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Absent" + } + + It "should return true from the test method" { + Test-TargetResource @testParams | Should Be $true + } + } + + Mock Test-Path { return $false } + + Context "A path doesn't exist" { + $testParams = @{ + Path = "C:\TestFolder" + Identity = "NT AUTHORITY\NETWORK SERVICE" + Rights = @("Read","Synchronize") + } + + It "should throw from the get method" { + { Get-TargetResource @testParams } | Should Throw + } + + It "should throw from the test method" { + { Test-TargetResource @testParams } | Should Throw + } + + It "should throw from the set method" { + { Set-TargetResource @testParams } | Should Throw + } + } + } + } +} +finally +{ + Restore-TestEnvironment -TestEnvironment $TestEnvironment +} From 5bad5ec5cc0ada71ca6a5b4e002e06805c46afb0 Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Thu, 28 Jul 2016 14:40:00 +1000 Subject: [PATCH 10/23] Removed tests folder that should have been exluded --- DSCResource.Tests/LICENSE | 21 -- DSCResource.Tests/Meta.Tests.ps1 | 274 ------------------ DSCResource.Tests/MetaFixers.psm1 | 115 -------- DSCResource.Tests/README.md | 115 -------- DSCResource.Tests/TestHelper.psm1 | 456 ------------------------------ DSCResource.Tests/TestRunner.psm1 | 25 -- 6 files changed, 1006 deletions(-) delete mode 100644 DSCResource.Tests/LICENSE delete mode 100644 DSCResource.Tests/Meta.Tests.ps1 delete mode 100644 DSCResource.Tests/MetaFixers.psm1 delete mode 100644 DSCResource.Tests/README.md delete mode 100644 DSCResource.Tests/TestHelper.psm1 delete mode 100644 DSCResource.Tests/TestRunner.psm1 diff --git a/DSCResource.Tests/LICENSE b/DSCResource.Tests/LICENSE deleted file mode 100644 index cec380d..0000000 --- a/DSCResource.Tests/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Microsoft Corporation. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/DSCResource.Tests/Meta.Tests.ps1 b/DSCResource.Tests/Meta.Tests.ps1 deleted file mode 100644 index 3e7040c..0000000 --- a/DSCResource.Tests/Meta.Tests.ps1 +++ /dev/null @@ -1,274 +0,0 @@ -<# - .summary - Test that describes code. - - .PARAMETER Force - Used to force any installations to occur without confirming with - the user. -#> -[CmdletBinding()] -Param ( - [Boolean]$Force = $false -) - -if (!$PSScriptRoot) # $PSScriptRoot is not defined in 2.0 -{ - $PSScriptRoot = [System.IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Path) -} -# Make sure MetaFixers.psm1 is loaded - it contains Get-TextFilesList -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath 'MetaFixers.psm1') -Force - -# Load the TestHelper module which contains the *-ResourceDesigner functions -Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath 'TestHelper.psm1') -Force - -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..).Path -$PSVersion = $PSVersionTable.PSVersion - -# Install and/or Import xDSCResourceDesigner Module -if ($env:APPVEYOR) { - # Running in AppVeyor so force silent install of xDSCResourceDesigner - $PSBoundParameters.Force = $true -} - -$xDSCResourceDesignerModuleName = "xDscResourceDesigner" -$xDSCResourceDesignerModulePath = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\$xDSCResourceDesignerModuleName" -$xDSCResourceDesignerModule = Install-ModuleFromPowerShellGallery -ModuleName $xDSCResourceDesignerModuleName -ModulePath $xDSCResourceDesignerModulePath @PSBoundParameters - -if ($xDSCResourceDesignerModule) { - # Import the module if it is available - $xDSCResourceDesignerModule | Import-Module -Force -} -else -{ - # Module could not/would not be installed - so warn user that tests will fail. - Write-Warning -Message ( @( - "The 'xDSCResourceDesigner' module is not installed. " - "The 'PowerShell DSC resource modules' Pester Tests in Meta.Tests.ps1 " - 'will fail until this module is installed.' - ) -Join '' ) -} - -# PSScriptAnalyzer requires PowerShell 5.0 or higher -if ($PSVersion.Major -ge 5) -{ - Write-Verbose -Verbose "Installing PSScriptAnalyzer" - $PSScriptAnalyzerModuleName = "PSScriptAnalyzer" - $PSScriptAnalyzerModulePath = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\$PSScriptAnalyzerModuleName" - $PSScriptAnalyzerModule = Install-ModuleFromPowerShellGallery -ModuleName $PSScriptAnalyzerModuleName -ModulePath $PSScriptAnalyzerModulePath @PSBoundParameters - - if ($PSScriptAnalyzerModule) { - # Import the module if it is available - $PSScriptAnalyzerModule | Import-Module -Force - } - else - { - # Module could not/would not be installed - so warn user that tests will fail. - Write-Warning -Message ( @( - "The 'PSScriptAnalyzer' module is not installed. " - "The 'PowerShell DSC resource modules' Pester Tests in Meta.Tests.ps1 " - 'will fail until this module is installed.' - ) -Join '' ) - } -} -else -{ - Write-Verbose -Verbose "Skipping installation of PSScriptAnalyzer since it requires PSVersion 5.0 or greater. Used PSVersion: $($PSVersion)" -} - -# The folder where this module is found -[String] $moduleRoot = Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path) - -# Modify PSModulePath of the current PowerShell session. -# We want to make sure we always test the development version of the resource -# in the current build directory. -[String] $script:OldModulePath = $env:PSModulePath -[String] $NewModulePath = $script:OldModulePath -if (($NewModulePath.Split(';') | Select-Object -First 1) -ne $moduleRoot) -{ - # Add the ModuleRoot to the beginning if it is not already at the front. - $env:PSModulePath = "$moduleRoot;$env:PSModulePath" -} - -# Wrap tests in a try so that if anything goes wrong or user terminates we roll back -# any enviroment changes (e.g. $ENV:PSModulePath) -try -{ - Describe 'Text files formatting' { - - $allTextFiles = Get-TextFilesList $RepoRoot - - Context 'Files encoding' { - - It "Doesn't use Unicode encoding" { - $unicodeFilesCount = 0 - $allTextFiles | %{ - if (Test-FileUnicode $_) { - $unicodeFilesCount += 1 - if($_.Extension -ieq '.mof') - { - Write-Warning "File $($_.FullName) contains 0x00 bytes. It's probably uses Unicode and need to be converted to ASCII. Use Fixer 'Get-UnicodeFilesList `$pwd | ConvertTo-ASCII'." - } - else - { - Write-Warning "File $($_.FullName) contains 0x00 bytes. It's probably uses Unicode and need to be converted to UTF-8. Use Fixer 'Get-UnicodeFilesList `$pwd | ConvertTo-UTF8'." - } - } - } - $unicodeFilesCount | Should Be 0 - } - } - - Context 'Indentations' { - - It 'Uses spaces for indentation, not tabs' { - $totalTabsCount = 0 - $allTextFiles | %{ - $fileName = $_.FullName - $tabStrings = (Get-Content $_.FullName -Raw) | Select-String "`t" | % { - Write-Warning "There are tab in $fileName. Use Fixer 'Get-TextFilesList `$pwd | ConvertTo-SpaceIndentation'." - $totalTabsCount++ - } - } - $totalTabsCount | Should Be 0 - } - } - - Context 'New Lines' { - - It 'Should end with a new line' { - $noNewLineCount = 0 - - foreach($file in $allTextFiles) - { - $content = Get-Content $file.FullName -Raw - - if($content[-1] -ne "`n") - { - if($noNewLineCount -eq 0) - { - Write-Warning "To improve consistency across multiple environments and editors each text file is required to end with a new line." - } - - Write-Warning "$($file.FullName) does not end with a new line. Use Fixer 'Add-NewLine'" - $noNewLineCount++ - } - } - - if(!$env:AppVeyor) - { - $noNewLineCount | should be 0 - } - } - } - } - - Describe 'PowerShell DSC resource modules' { - - # PSScriptAnalyzer requires PowerShell 5.0 or higher - if ($PSVersion.Major -ge 5) - { - Context 'PSScriptAnalyzer' { - It 'passes Invoke-ScriptAnalyzer' { - - # Perform PSScriptAnalyzer scan. - # Using ErrorAction SilentlyContinue not to cause it to fail due to parse errors caused by unresolved resources. - # Many of our examples try to import different modules which may not be present on the machine and PSScriptAnalyzer throws parse exceptions even though examples are valid. - # Errors will still be returned as expected. - $PSScriptAnalyzerErrors = Invoke-ScriptAnalyzer -path $RepoRoot -Severity Error -Recurse -ErrorAction SilentlyContinue - if ($PSScriptAnalyzerErrors -ne $null) { - Write-Warning -Message 'There are PSScriptAnalyzer errors that need to be fixed:' - @($PSScriptAnalyzerErrors).Foreach( { Write-Warning -Message "$($_.Scriptname) (Line $($_.Line)): $($_.Message)" } ) - Write-Warning -Message 'For instructions on how to run PSScriptAnalyzer on your own machine, please go to https://github.com/powershell/psscriptAnalyzer/' - @($PSScriptAnalyzerErrors).Count | Should Be 0 - } - } - } - } - - # Force convert to array - $psm1Files = @( - Get-ChildItem -Path $RepoRoot\DscResources -Recurse -Filter '*.psm1' -File | - Foreach-Object { - # Ignore Composite configurations - # They requires additional resources to be installed on the box - if (-not ($_.Name -like '*.schema.psm1')) - { - $MofFileName = "$($_.BaseName).schema.mof" - $MofFilePath = Join-Path -Path $_.DirectoryName -ChildPath $MofFileName - if (Test-Path -Path $MofFilePath -ErrorAction SilentlyContinue) - { - Write-Output -InputObject $_ - } - } - } - ) - - if (-not $psm1Files) { - Write-Verbose -Verbose 'There are no resource files to analyze' - } else { - - Write-Verbose -Verbose "Analyzing $($psm1Files.Count) resources" - - Context 'Correctness' { - - function Get-ParseErrors - { - param( - [Parameter(ValueFromPipeline=$True,Mandatory=$True)] - [string]$fileName - ) - - $tokens = $null - $errors = $null - $ast = [System.Management.Automation.Language.Parser]::ParseFile($fileName, [ref] $tokens, [ref] $errors) - return $errors - } - - - It 'all .psm1 files don''t have parse errors' { - $errors = @() - $psm1Files | ForEach-Object { - $localErrors = Get-ParseErrors $_.FullName - if ($localErrors) { - Write-Warning "There are parsing errors in $($_.FullName)" - Write-Warning ($localErrors | Format-List | Out-String) - } - $errors += $localErrors - } - $errors.Count | Should Be 0 - } - } - - foreach ($psm1file in $psm1Files) - { - Context "Schema Validation of $($psm1file.BaseName)" { - - It 'should pass Test-xDscResource' { - $result = Test-xDscResource -Name $psm1file.DirectoryName - $result | Should Be $true - } - - It 'should pass Test-xDscSchema' { - $Splat = @{ - Path = $psm1file.DirectoryName - ChildPath = "$($psm1file.BaseName).schema.mof" - } - $result = Test-xDscSchema -Path (Join-Path @Splat -Resolve -ErrorAction Stop) - $result | Should Be $true - } - } - } - } - } -} -finally -{ - # Restore PSModulePath - if ($script:OldModulePath -ne $env:PSModulePath) - { - $env:PSModulePath = $OldModulePath - } -} diff --git a/DSCResource.Tests/MetaFixers.psm1 b/DSCResource.Tests/MetaFixers.psm1 deleted file mode 100644 index 780cdb4..0000000 --- a/DSCResource.Tests/MetaFixers.psm1 +++ /dev/null @@ -1,115 +0,0 @@ -<# - This module helps fix problems, found by Meta.Tests.ps1 -#> - -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -function ConvertTo-UTF8() -{ - [CmdletBinding()] - [OutputType([void])] - param( - [Parameter(ValueFromPipeline=$true, Mandatory=$true)] - [System.IO.FileInfo]$fileInfo - ) - - process - { - $content = Get-Content -Raw -Encoding Unicode -Path $fileInfo.FullName - [System.IO.File]::WriteAllText($fileInfo.FullName, $content, [System.Text.Encoding]::UTF8) - } -} - -function ConvertTo-ASCII() -{ - [CmdletBinding()] - [OutputType([void])] - param( - [Parameter(ValueFromPipeline=$true, Mandatory=$true)] - [System.IO.FileInfo]$fileInfo - ) - - process - { - $content = Get-Content -Raw -Encoding Unicode -Path $fileInfo.FullName - [System.IO.File]::WriteAllText($fileInfo.FullName, $content, [System.Text.Encoding]::ASCII) - } -} - -function ConvertTo-SpaceIndentation() -{ - [CmdletBinding()] - [OutputType([void])] - param( - [Parameter(ValueFromPipeline=$true, Mandatory=$true)] - [System.IO.FileInfo]$fileInfo - ) - - process - { - $content = (Get-Content -Raw -Path $fileInfo.FullName) -replace "`t",' ' - [System.IO.File]::WriteAllText($fileInfo.FullName, $content) - } -} - -function Get-TextFilesList -{ - [CmdletBinding()] - [OutputType([System.IO.FileInfo])] - param( - [Parameter(Mandatory=$true)] - [string]$root - ) - ls -File -Recurse $root | ? { @('.gitignore', '.gitattributes', '.ps1', '.psm1', '.psd1', '.json', '.xml', '.cmd', '.mof') -contains $_.Extension } -} - -function Test-FileUnicode -{ - - [CmdletBinding()] - [OutputType([bool])] - param( - [Parameter(ValueFromPipeline=$true, Mandatory=$true)] - [System.IO.FileInfo]$fileInfo - ) - - process - { - - $path = $fileInfo.FullName - $bytes = [System.IO.File]::ReadAllBytes($path) - $zeroBytes = @($bytes -eq 0) - return [bool]$zeroBytes.Length - - } -} - -function Get-UnicodeFilesList() -{ - [CmdletBinding()] - [OutputType([System.IO.FileInfo])] - param( - [Parameter(Mandatory=$true)] - [string]$root - ) - - Get-TextFilesList $root | ? { Test-FileUnicode $_ } -} - -function Add-NewLine() -{ - [CmdletBinding()] - [OutputType([void])] - param( - [Parameter(ValueFromPipeline=$true, Mandatory=$true)] - [System.IO.FileInfo]$fileInfo - ) - - process - { - $content = Get-Content -Raw -Path $fileInfo.FullName - $content += "`r`n" - [System.IO.File]::WriteAllText($fileInfo.FullName, $content) - } -} diff --git a/DSCResource.Tests/README.md b/DSCResource.Tests/README.md deleted file mode 100644 index 0d0fe7f..0000000 --- a/DSCResource.Tests/README.md +++ /dev/null @@ -1,115 +0,0 @@ -# DscResource.Tests -Common meta tests for PowerShell DSC resources repositories. - -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). -For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. - -## DscResourceCommonTests -### Unreleased -* Extra whitespace trimmed from TestHelper.psm1 (feature of VS Code). -* Removed code to Remove-Module from Initialize-TestEnvironment because not required: Import-Module -force should do the same thing. -* Initialize-TestEnvironment changed to import module being tested into Global scope so that InModuleScope not required in tests. - -### 0.2.0.0 -* Fixed unicode and path bugs in tests - -### 0.1.0.0 -* Initial release - -## DscResourceTestHelper -### Unreleased - -### 0.2.0.0 -* Fixed unicode and path bugs in tests - -### 0.1.0.0 -* Initial release - -## Goals - -1. Consistency in encoding and indentations. -Consistency is good by itself. But more important it allows us to: -2. Avoid big diffs with cosmetic changes in Pull Requests. -Cosmetic changes (like formatting) make reviews harder. -If you want to include formatting changes (like replacing `"` by `'`), -please make it a **separate commit**. -This will give reviewers an option to review meaningful changes separately from formatting changes. - - -## Git and Unicode - -By default git treats [unicode files as binary files](http://stackoverflow.com/questions/6855712/why-does-git-treat-this-text-file-as-a-binary-file). -You may not notice it if your client (like VS or GitHub for Windows) takes care of such conversion. -History with Unicode files is hardly usable from command line `git`. - -``` -> git diff - diff --git a/xActiveDirectory.psd1 b/xActiveDirectory.psd1 - index 0fc1914..55fdb85 100644 -Binary files a/xActiveDirectory.psd1 and b/xActiveDirectory.psd1 differ -``` - -With forced `--text` option it would look like this: - -``` -> git diff --text - diff --git a/xActiveDirectory.psd1 b/xActiveDirectory.psd1 - index 0fc1914..55fdb85 100644 - --- a/xActiveDirectory.psd1 - +++ b/xActiveDirectory.psd1 -@@ -30,4 +30,4 @@ - C m d l e t s T o E x p o r t = ' * ' - - } - - - - - - \ No newline at end of file - + # h e l l o - \ No newline at end of file -``` - -Command line `git` version is a core component and should be used as a common denominator. - - -## MetaFixers Module - -We are trying to provide automatic fixers where it's appropriate. A fixer corresponds to a particular test. - -For example, if `Files encoding` test from [Meta.Tests.ps1](Meta.Tests.ps1) test fails, you should be able to run `ConvertTo-UTF8` fixer from [MetaFixers.psm1](MetaFixers.psm1). - - -## TestHelper Module - -The test helper module (TestHelper.psm1) contains the following functions: -**New-Nuspec**: Creates a new nuspec file for nuget package. -**Install-ResourceDesigner**: Will attempt to download the xDSCResourceDesignerModule using Nuget package and return the module. -**Initialize-TestEnvironment**: Initializes an environment for running unit or integration tests on a DSC resource. -**Restore-TestEnvironment**: Restores the environment after running unit or integration tests on a DSC resource. - - -## Templates for Creating Tests - -The Template files that are used for creating Unit and Integration tests for a DSC resource are available in the [DSCResources GitHub Repository](https://github.com/PowerShell/DscResources) in the [Tests.Template folder](https://github.com/PowerShell/DscResources/tree/master/Tests.Template) - -To use these files, see the [test guidelines](https://github.com/PowerShell/DscResources/blob/master/TestsGuidelines.md) document and the instructions at the top of each template file. - -The resource files are: -*[Unit_Template.ps1](https://github.com/PowerShell/DscResources/blob/master/Tests.Template/unit_template.ps1)**: Use to create a set of Unit Pester tests for a single DSC Resource. -**[Integration_Template.ps1](https://github.com/PowerShell/DscResources/blob/master/Tests.Template/integration_template.ps1)**: Use to create a set of Integration Pester tests for a single DSC Resource. -**[Integration_Config_Template.ps1](https://github.com/PowerShell/DscResources/blob/master/Tests.Template/unit_template.ps1)**: Use to create a DSC Configuration file for a single DSC Resource. Used in conjunction with Integration_Template.ps1. - - -## Example Test Usage - -To see examples of the Unit/Integration tests in practice, see the xNetworking MSFT_xFirewall resource: -[Unit Tests](https://github.com/PowerShell/xNetworking/blob/dev/Tests/Unit/MSFT_xFirewall.Tests.ps1) -[Integration Tests](https://github.com/PowerShell/xNetworking/blob/dev/Tests/Integration/MSFT_xFirewall.Integration.Tests.ps1) -[Resource DSC Configuration](https://github.com/PowerShell/xNetworking/blob/dev/Tests/Integration/MSFT_xFirewall.config.ps1) - - -## Example Usage of DSCResource.Tests in AppVeyor.yml - -To automatically download and install the DscResource.Tests in an AppVeyor.yml file, please see the following sample AppVeyor.yml. -[https://github.com/PowerShell/DscResources/blob/master/DscResource.Template/appveyor.yml](https://github.com/PowerShell/DscResources/blob/master/DscResource.Template/appveyor.yml) diff --git a/DSCResource.Tests/TestHelper.psm1 b/DSCResource.Tests/TestHelper.psm1 deleted file mode 100644 index 1a58858..0000000 --- a/DSCResource.Tests/TestHelper.psm1 +++ /dev/null @@ -1,456 +0,0 @@ -<# - Script Constants used by *-ResourceDesigner Functions -#> -<# - .SYNOPSIS Creates a new nuspec file for nuget package. - Will create $packageName.nuspec in $destinationPath - - .EXAMPLE - New-Nuspec -packageName "TestPackage" -version 1.0.1 -licenseUrl "http://license" -packageDescription "description of the package" -tags "tag1 tag2" -destinationPath C:\temp -#> -function New-Nuspec -{ - param - ( - [Parameter(Mandatory=$true)] - [string] $packageName, - [Parameter(Mandatory=$true)] - [string] $version, - [Parameter(Mandatory=$true)] - [string] $author, - [Parameter(Mandatory=$true)] - [string] $owners, - [string] $licenseUrl, - [string] $projectUrl, - [string] $iconUrl, - [string] $packageDescription, - [string] $releaseNotes, - [string] $tags, - [Parameter(Mandatory=$true)] - [string] $destinationPath - ) - - $year = (Get-Date).Year - - $content += -" - - - $packageName - $version - $author - $owners" - - if (-not [string]::IsNullOrEmpty($licenseUrl)) - { - $content += " - $licenseUrl" - } - - if (-not [string]::IsNullOrEmpty($projectUrl)) - { - $content += " - $projectUrl" - } - - if (-not [string]::IsNullOrEmpty($iconUrl)) - { - $content += " - $iconUrl" - } - - $content +=" - true - $packageDescription - $releaseNotes - Copyright $year - $tags - -" - - if (-not (Test-Path -Path $destinationPath)) - { - New-Item -Path $destinationPath -ItemType Directory > $null - } - - $nuspecPath = Join-Path $destinationPath "$packageName.nuspec" - New-Item -Path $nuspecPath -ItemType File -Force > $null - Set-Content -Path $nuspecPath -Value $content -} - -<# - .SYNOPSIS - Will attempt to download the module from PowerShellGallery using - Nuget package and return the module. - - If already installed will return the module without making changes. - - If module could not be downloaded it will return null. - - .PARAMETER Force - Used to force any installations to occur without confirming with - the user. - - .PARAMETER moduleName - Name of the module to install - - .PARAMETER modulePath - Path where module should be installed - - .EXAMPLE - Install-ModuleFromPowerShellGallery - - .EXAMPLE - if ($env:APPVEYOR) { - # Running in AppVeyor so force silent install of xDSCResourceDesigner - $PSBoundParameters.Force = $true - } - - $xDSCResourceDesignerModuleName = "xDscResourceDesigner" - $xDSCResourceDesignerModulePath = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\$xDSCResourceDesignerModuleName" - $xDSCResourceDesignerModule = Install-ModuleFromPowerShellGallery -ModuleName $xDSCResourceDesignerModuleName -ModulePath $xDSCResourceDesignerModulePath @PSBoundParameters -#> -function Install-ModuleFromPowerShellGallery { - [OutputType([System.Management.Automation.PSModuleInfo])] - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High')] - Param - ( - [Parameter(Mandatory=$true)] - [String] $moduleName, - - [Parameter(Mandatory=$true)] - [String] $modulePath, - - [Boolean]$Force = $false - ) - - $module = Get-Module -Name $moduleName -ListAvailable - if (@($module).Count -ne 0) - { - # Module is already installed - report it. - Write-Host -Object (` - 'Version {0} of the {1} module is already installed.' ` - -f $($module.Version -join ', '),$moduleName - ) -ForegroundColor:Yellow - # Could check for a newer version available here in future and perform an update. - # Return only the latest version of the module - return $module ` - | Sort-Object -Property Version -Descending ` - | Select-Object -First 1 - } - - Write-Verbose -Message (` - 'The {0} module is not installed.' ` - -f $moduleName - ) - - $OutputDirectory = "$(Split-Path -Path $modulePath -Parent)\" - - # Use Nuget directly to download the module - $nugetPath = 'nuget.exe' - - # Can't assume nuget.exe is available - look for it in Path - if ((Get-Command $nugetPath -ErrorAction SilentlyContinue) -eq $null) - { - # Is it in temp folder? - $nugetPath = Join-Path -Path $ENV:Temp -ChildPath $nugetPath - if (-not (Test-Path -Path $nugetPath)) - { - # Nuget.exe can't be found - download it to temp folder - $NugetDownloadURL = 'http://nuget.org/nuget.exe' - If ($Force -or $PSCmdlet.ShouldProcess( ` - "Download Nuget.exe from '{0}' to Temp folder" ` - -f $NugetDownloadURL)) - { - Invoke-WebRequest $NugetDownloadURL -OutFile $nugetPath - - Write-Verbose -Message (` - "Nuget.exe was installed from '{0}' to Temp folder." ` - -f $NugetDownloadURL - ) - } - else - { - # Without Nuget.exe we can't continue - Write-Warning -Message (` - 'Nuget.exe was not installed. {0} module can not be installed automatically.' ` - -f $moduleName - ) - return $null - } - } - else - { - Write-Verbose -Message 'Using Nuget.exe found in Temp folder.' - } - } - - $nugetSource = 'https://www.powershellgallery.com/api/v2' - If ($Force -or $PSCmdlet.ShouldProcess(( ` - "Download and install the {0} module from '{1}' using Nuget" ` - -f $moduleName,$nugetSource))) - { - # Use Nuget.exe to install the module - $null = & "$nugetPath" @( ` - 'install', $moduleName, ` - '-source', $nugetSource, ` - '-outputDirectory', $OutputDirectory, ` - '-ExcludeVersion' ` - ) - $ExitCode = $LASTEXITCODE - - if ($ExitCode -ne 0) - { - throw ( - 'Installation of {0} module using Nuget failed with exit code {1}.' ` - -f $moduleName,$ExitCode - ) - } - Write-Host -Object (` - 'The {0} module was installed using Nuget.' ` - -f $moduleName - ) -ForegroundColor:Yellow - } - else - { - Write-Warning -Message (` - '{0} module was not installed automatically.' ` - -f $moduleName - ) - return $null - } - - return (Get-Module -Name $moduleName -ListAvailable) -} - -<# - .SYNOPSIS - Initializes an enviroment for running unit or integration tests - on a DSC resource. - - This includes the following things: - 1. Creates a temporary working folder. - 2. Updates the $env:PSModulePath to ensure the correct module is tested. - 3. Backs up any settings that need to be changed to accurately test - the resource. - 4. Produces a test object containing any parameters that may be used - for testing as well as storing the backed up settings. - - The above changes are reverted by calling the Restore-TestEnvironment - function. This includes deleteing the temporary working folder. - - .PARAMETER DSCModuleName - The name of the DSC Module containing the resource that the tests will be - run on. - - .PARAMETER DSCResourceName - The full name of the DSC resource that the tests will be run on. This is - usually the name of the folder containing the actual resource MOF file. - - .PARAMETER TestType - Specifies the type of tests that are being intialized. It can be: - Unit: Initialize for running Unit tests on a DSC resource. Default. - Integration: Initialize for running Integration tests on a DSC resource. - - .OUTPUT - Returns a test environment object which must be passed to the - Restore-TestEnvironment function to allow it to restore the system - back to the original state as well as clean up and working/temp files. - - .EXAMPLE - $TestEnvironment = Inialize-TestEnvironment ` - -DSCModuleName 'xNetworking' ` - -DSCResourceName 'MSFT_xFirewall' ` - -TestType Unit - - This command will initialize the test enviroment for Unit testing - the MSFT_xFirewall DSC resource in the xNetworking DSC module. - - .EXAMPLE - $TestEnvironment = Inialize-TestEnvironment ` - -DSCModuleName 'xNetworking' ` - -DSCResourceName 'MSFT_xFirewall' ` - -TestType Integration - - This command will initialize the test enviroment for Integration testing - the MSFT_xFirewall DSC resource in the xNetworking DSC module. -#> -function Initialize-TestEnvironment -{ - [OutputType([PSObject])] - [CmdletBinding()] - Param - ( - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String] $DSCModuleName, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String] $DSCResourceName, - - [Parameter(Mandatory=$true)] - [ValidateSet('Unit','Integration')] - [String] $TestType - ) - - Write-Host -Object (` - 'Initializing Test Environment for {0} testing of {1} in module {2}.' ` - -f $TestType,$DSCResourceName,$DSCModuleName) -ForegroundColor:Yellow - if ($TestType -eq 'Unit') - { - [String] $RelativeModulePath = "DSCResources\$DSCResourceName\$DSCResourceName.psm1" - } - else - { - [String] $RelativeModulePath = "$DSCModuleName.psd1" - } - - # Unique Temp Working Folder - always gets removed on completion - # The tests can put anything in here and it will get cleaned up. - [String] $RandomFileName = [System.IO.Path]::GetRandomFileName() - [String] $WorkingFolder = Join-Path -Path $env:Temp -ChildPath "$DSCResourceName_$RandomFileName" - # Create the working folder if it doesn't exist (it really shouldn't anyway) - if (-not (Test-Path -Path $WorkingFolder)) - { - New-Item -Path $WorkingFolder -ItemType Directory - } - - # Determine the root folder of this module by stepping up the path until the disk root is found - # or the DSC Module Manifest is found. - [String] $Path = $Script:MyInvocation.MyCommand.Path - [String] $DiskRoot = [System.IO.Path]::GetPathRoot($Path) - while (($Path -ne $DiskRoot) -and (-not [String]::IsNullOrEmpty($Path))) - { - # Does the Path contain the Resource Module? - if (Test-Path -Path (Join-Path -Path $Path -ChildPath "$DSCModuleName.psd1")) - { - # The Module Root folder has been found - [String] $moduleRoot = $Path - break - } - $Path = Split-Path -Path $Path -Parent - } # while - - # Check that the Module Root was found - if (-not $ModuleRoot) - { - Throw "The DSC Module Manifest '$DSCModuleName.psd1' could not be found or it was found in the root folder on the disk." - } # if - Write-Host -Object (` - "DSC Module Manifest '{0}.psd1' detected in folder '{1}'." ` - -f $DSCModuleName,$ModuleRoot) -ForegroundColor:Yellow - - # The folder that all tests will find this module in - [string] $modulesFolder = Split-Path -Parent $moduleRoot - - # Import the Module - $Splat = @{ - Path = $moduleRoot - ChildPath = $RelativeModulePath - Resolve = $true - ErrorAction = 'Stop' - } - $DSCModuleFile = Get-Item -Path (Join-Path @Splat) - - # Import the Module to test. - Import-Module -Name $DSCModuleFile.FullName -Force -Scope Global - - # Set the PSModulePath environment variable so that the module path this module is in - # appears first because the LCM will use this path to try and locate modules when integration - # tests are called. This is to ensure the correct module is tested. - [String] $OldModulePath = $env:PSModulePath - [String] $NewModulePath = $OldModulePath - if (($NewModulePath).Split(';') -ccontains $modulesFolder) - { - # Remove the existing module from the module path if it exists - $NewModulePath = ($NewModulePath -split ';' | Where-Object {$_ -ne $modulesFolder}) -join ';' - } - $NewModulePath = "$modulesFolder;$NewModulePath" - $env:PSModulePath = $NewModulePath - if ($TestType -eq 'integration') { - # For integration tests we have to set the Machine PSModulePath because otherwise the DSC - # LCM won't be able to find the Resource module being tested and may use the wrong one. - [System.Environment]::SetEnvironmentVariable('PSModulePath',$NewModulePath,[System.EnvironmentVariableTarget]::Machine) - } - - # Preserve and set the execution policy so that the DSC MOF can be created - $OldExecutionPolicy = Get-ExecutionPolicy - if ($OldExecutionPolicy -ne 'Unrestricted') - { - Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force - } - - # Generate the test environment object that will be returned - $TestEnvironment = @{ - DSCModuleName = $DSCModuleName - DSCResourceName = $DSCResourceName - TestType = $TestType - RelativeModulePath = $RelativeModulePath - WorkingFolder = $WorkingFolder - OldModulePath = $OldModulePath - OldExecutionPolicy = $OldExecutionPolicy - } - - return $TestEnvironment -} - -<# - .SYNOPSIS - Restores the enviroment after running unit or integration tests - on a DSC resource. - - This restores the following changes made by calling - Initialize-TestEnvironemt: - 1. Deletes the Working folder. - 2. Restores the $env:PSModulePath if it was changed. - 3. Restores any settings that were changed to test the resource. - - .PARAMETER TestEnvironment - This is the object created by the Initialize-TestEnvironment - cmdlet. - - .EXAMPLE - Restore-TestEnvironment -TestEnvironment $TestEnvironment - - This command will initialize the test enviroment for Unit testing - the MSFT_xFirewall DSC resource in the xNetworking DSC module. -#> -function Restore-TestEnvironment -{ - [CmdletBinding()] - Param - ( - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [PSObject] $TestEnvironment - ) - - Write-Verbose -Message (` - 'Cleaning up Test Environment after {0} testing of {1} in module {2}.' ` - -f $TestEnvironment.TestType,$TestEnvironment.DSCResourceName,$TestEnvironment.DSCModuleName) - - # Restore PSModulePath - if ($TestEnvironment.OldModulePath -ne $env:PSModulePath) - { - $env:PSModulePath = $TestEnvironment.OldModulePath - if ($TestType -eq 'integration') { - # Restore the machine PSModulePath for integration tests. - [System.Environment]::SetEnvironmentVariable('PSModulePath',$env:PSModulePath,[System.EnvironmentVariableTarget]::Machine) - } - } - - # Restore the Execution Policy - if ($TestEnvironment.OldExecutionPolicy -ne (Get-ExecutionPolicy)) - { - Set-ExecutionPolicy -ExecutionPolicy $TestEnvironment.OldExecutionPolicy -Force - } - - # Cleanup Working Folder - if (Test-Path -Path $TestEnvironment.WorkingFolder) - { - Remove-Item -Path $TestEnvironment.WorkingFolder -Recurse -Force - } -} diff --git a/DSCResource.Tests/TestRunner.psm1 b/DSCResource.Tests/TestRunner.psm1 deleted file mode 100644 index 94b7a14..0000000 --- a/DSCResource.Tests/TestRunner.psm1 +++ /dev/null @@ -1,25 +0,0 @@ -<# - .SYNOPSIS Runs tests on all DSC resources in given folder (including common tests) - .PARAM - resourcesPath Path where DSC resource modules have been cloned (tests will run for all modules in that path) - .EXAMPLE - Start-DscResourceTests -resourcesPath C:\DscResources\xDscResources -#> -function Start-DscResourceTests -{ - param( - [String] $resourcesPath - ) - - $testsPath = $pwd - cd $resourcesPath - ls | % { - $module = $_.Name - Write-Host "Copying common tests from $testsPath to $resourcesPath\$module" -ForegroundColor Yellow - Copy-Item $testsPath "$resourcesPath\$module" -recurse -force - cd $module - Write-Host "Running tests for $module" -ForegroundColor Yellow - Invoke-Pester - cd .. - } -} From dea26b6b21c89082229abe7c873d20f97e2adb7f Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Thu, 28 Jul 2016 14:40:49 +1000 Subject: [PATCH 11/23] Added ignore file --- .gitignore | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..69c4f81 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +*.suo +*.user +*.coverage +.vs +.psproj +.sln +DscResource.Tests +DscResource.Tests/* From aa619bade8cdbdf74a0640acb066124017bdd13b Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Thu, 28 Jul 2016 14:42:33 +1000 Subject: [PATCH 12/23] Added new line --- .../MSFT_xFileSystemAccessRule.integration.tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 b/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 index c80e096..7cf0504 100644 --- a/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 +++ b/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 @@ -97,4 +97,4 @@ try finally { Restore-TestEnvironment -TestEnvironment $TestEnvironment -} \ No newline at end of file +} From ebfa96a107cc8de719dd0d1643e22635b5df8ab2 Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Thu, 28 Jul 2016 14:43:57 +1000 Subject: [PATCH 13/23] Added cmdlet attributes --- .../MSFT_xFileSystemAccessRule.psm1 | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 b/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 index 83bda61..dfbe83f 100644 --- a/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 +++ b/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 @@ -1,5 +1,7 @@ function Get-TargetResource { + [CmdletBinding()] + [OutputType([System.Collections.Hashtable])] param( [Parameter(Mandatory = $true)] [String] @@ -73,6 +75,7 @@ function Get-TargetResource function Set-TargetResource { + [CmdletBinding()] param( [Parameter(Mandatory = $true)] [String] @@ -157,6 +160,8 @@ function Set-TargetResource function Test-TargetResource { + [CmdletBinding()] + [OutputType([System.Boolean])] param( [Parameter(Mandatory = $true)] [String] From 6505235fe37180a043a120d06bc923013eed7b36 Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Thu, 28 Jul 2016 14:45:57 +1000 Subject: [PATCH 14/23] Added new line --- .vscode/launch.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 6152b72..3684ffa 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -10,4 +10,4 @@ "cwd": "${file}" } ] -} \ No newline at end of file +} From 31d6fb261c4679d1c95312607a2813cbb3ced00f Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Thu, 28 Jul 2016 14:46:54 +1000 Subject: [PATCH 15/23] Fixed export module member --- .../MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 b/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 index dfbe83f..95c07bc 100644 --- a/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 +++ b/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 @@ -231,4 +231,4 @@ function Test-TargetResource return $true } -Export-ModuleMember -Function *-TargetResoruce +Export-ModuleMember -Function *-TargetResource \ No newline at end of file From 0ac809bea97bc07a88020b2943afd6aa627fed2b Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Thu, 28 Jul 2016 14:48:40 +1000 Subject: [PATCH 16/23] Added another new line --- .../MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 b/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 index 95c07bc..5987b11 100644 --- a/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 +++ b/DSCResources/MSFT_xFileSystemAccessRule/MSFT_xFileSystemAccessRule.psm1 @@ -231,4 +231,4 @@ function Test-TargetResource return $true } -Export-ModuleMember -Function *-TargetResource \ No newline at end of file +Export-ModuleMember -Function *-TargetResource From b9f018dfd21d579df33c847515b8e3e373df38b9 Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Thu, 28 Jul 2016 14:49:25 +1000 Subject: [PATCH 17/23] Fixed location of test folder creation --- .../MSFT_xFileSystemAccessRule.integration.tests.ps1 | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 b/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 index 7cf0504..08d26e1 100644 --- a/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 +++ b/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 @@ -19,14 +19,9 @@ try $ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1" . $ConfigFile - Describe "$($script:DSCResourceName)_Integration" { + New-Item -Path "TestDrive:\SampleFolder" - BeforeAll { - New-Item -Path "TestDrive:\SampleFolder" - } - AfterAll { - Remove-Item "TestDrive:\SampleFolder" - } + Describe "$($script:DSCResourceName)_Integration" { It 'New rule - Should compile without throwing' { { From 750cfb2210b893b788d3120c097dc9f1bca34dfa Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Thu, 28 Jul 2016 14:55:30 +1000 Subject: [PATCH 18/23] Trying to fix testdrive load --- .../MSFT_xFileSystemAccessRule.integration.tests.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 b/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 index 08d26e1..0a3b7a6 100644 --- a/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 +++ b/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 @@ -19,7 +19,8 @@ try $ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1" . $ConfigFile - New-Item -Path "TestDrive:\SampleFolder" + Import-Module Pester + New-Item -Path "TestDrive:\SampleFolder" -ItemType Directory Describe "$($script:DSCResourceName)_Integration" { From 8c4c0fc2b28a848d05873d0f5fff4181c6d3df95 Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Thu, 28 Jul 2016 14:59:14 +1000 Subject: [PATCH 19/23] Just changed to a C path --- Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1 | 6 +++--- .../MSFT_xFileSystemAccessRule.integration.tests.ps1 | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1 b/Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1 index 43a55de..dc99de7 100644 --- a/Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1 +++ b/Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1 @@ -2,7 +2,7 @@ configuration MSFT_xFileSystemAccessRule_NewRule { Import-DscResource -ModuleName 'xSystemSecurity' node localhost { xFileSystemAccessRule Integration_Test { - Path = "TestDrive:\SampleFolder" + Path = "C:\SampleFolder" Identity = "NT AUTHORITY\NETWORK SERVICE" Rights = @("Read","Synchronize") } @@ -13,7 +13,7 @@ configuration MSFT_xFileSystemAccessRule_UpdateRule { Import-DscResource -ModuleName 'xSystemSecurity' node localhost { xFileSystemAccessRule Integration_Test { - Path = "TestDrive:\SampleFolder" + Path = "C:\SampleFolder" Identity = "NT AUTHORITY\NETWORK SERVICE" Rights = @("FullControl") } @@ -24,7 +24,7 @@ configuration MSFT_xFileSystemAccessRule_RemoveRule { Import-DscResource -ModuleName 'xSystemSecurity' node localhost { xFileSystemAccessRule Integration_Test { - Path = "TestDrive:\SampleFolder" + Path = "C:\SampleFolder" Identity = "NT AUTHORITY\NETWORK SERVICE" Ensure = "Absent" } diff --git a/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 b/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 index 0a3b7a6..e3adb6c 100644 --- a/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 +++ b/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 @@ -19,8 +19,7 @@ try $ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1" . $ConfigFile - Import-Module Pester - New-Item -Path "TestDrive:\SampleFolder" -ItemType Directory + New-Item -Path "C:\SampleFolder" -ItemType Directory Describe "$($script:DSCResourceName)_Integration" { @@ -88,6 +87,9 @@ try It 'New rule - Should have set the resource and all the parameters should match' { Test-DscConfiguration -Path $TestEnvironment.WorkingFolder | Should Be $true } + + + Remove-Item -Path "C:\SampleFolder" -Recurse -Force -Confirm:$false } } finally From f048a5a183ee16cb6415b8de2c8af0769c0912a5 Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Thu, 28 Jul 2016 15:02:25 +1000 Subject: [PATCH 20/23] Fixed invalid characters in readme --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 55b10e0..4c091f6 100644 --- a/README.md +++ b/README.md @@ -50,10 +50,10 @@ Please check out common DSC Resources [contributing guidelines](https://github.c If you are logged on as a standard user, any changes that require the permissions of an administrator will automatically be denied. If you select this setting, you will need to restart the computer to complete the process of turning off UAC. Once UAC is off, people that log on as administrator will always have the permissions of an administrator. - This is the least secure setting same as �NeverNotify�, but in addition EnableLUA registry key is disabled. + This is the least secure setting same as "NeverNotify", but in addition EnableLUA registry key is disabled. EnableLUA controls the behavior of all UAC policy settings for the computer. If you change this policy setting, you must restart your computer - We do not recommend using this setting, but it can be selected for systems that use programs that are not certified for Windows� 8, Windows Server� 2012, Windows� 7 or Windows Server� 2008 R2 because they do not support UAC. + We do not recommend using this setting, but it can be selected for systems that use programs that are not certified for Windows 8, Windows Server 2012, Windows 7 or Windows Server 2008 R2 because they do not support UAC. ### xIEEsc From a3577944c1ea7a4cd7f8a951f5bdc895951cf82b Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Mon, 15 Aug 2016 08:45:12 +1000 Subject: [PATCH 21/23] Fixed drive letters in tests --- .../MSFT_xFileSystemAccessRule.config.ps1 | 6 +++--- Tests/Unit/MSFT_xFileSystemAccessRule.tests.ps1 | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1 b/Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1 index dc99de7..36dbea2 100644 --- a/Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1 +++ b/Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1 @@ -2,7 +2,7 @@ configuration MSFT_xFileSystemAccessRule_NewRule { Import-DscResource -ModuleName 'xSystemSecurity' node localhost { xFileSystemAccessRule Integration_Test { - Path = "C:\SampleFolder" + Path = "$($env:SystemDrive)\SampleFolder" Identity = "NT AUTHORITY\NETWORK SERVICE" Rights = @("Read","Synchronize") } @@ -13,7 +13,7 @@ configuration MSFT_xFileSystemAccessRule_UpdateRule { Import-DscResource -ModuleName 'xSystemSecurity' node localhost { xFileSystemAccessRule Integration_Test { - Path = "C:\SampleFolder" + Path = "$($env:SystemDrive)\SampleFolder" Identity = "NT AUTHORITY\NETWORK SERVICE" Rights = @("FullControl") } @@ -24,7 +24,7 @@ configuration MSFT_xFileSystemAccessRule_RemoveRule { Import-DscResource -ModuleName 'xSystemSecurity' node localhost { xFileSystemAccessRule Integration_Test { - Path = "C:\SampleFolder" + Path = "$($env:SystemDrive)\SampleFolder" Identity = "NT AUTHORITY\NETWORK SERVICE" Ensure = "Absent" } diff --git a/Tests/Unit/MSFT_xFileSystemAccessRule.tests.ps1 b/Tests/Unit/MSFT_xFileSystemAccessRule.tests.ps1 index ba05360..f006a6d 100644 --- a/Tests/Unit/MSFT_xFileSystemAccessRule.tests.ps1 +++ b/Tests/Unit/MSFT_xFileSystemAccessRule.tests.ps1 @@ -27,7 +27,7 @@ try Context "No permissions exist for a user, but should" { $testParams = @{ - Path = "C:\TestFolder" + Path = "$($env:SystemDrive)\TestFolder" Identity = "NT AUTHORITY\NETWORK SERVICE" Rights = @("Read","Synchronize") } @@ -54,7 +54,7 @@ try Context "A permission exists and should, but the rights are incorrect" { $testParams = @{ - Path = "C:\TestFolder" + Path = "$($env:SystemDrive)\TestFolder" Identity = "NT AUTHORITY\NETWORK SERVICE" Rights = @("Read","Synchronize") } @@ -86,7 +86,7 @@ try Context "A permission exists and should, including correct rights" { $testParams = @{ - Path = "C:\TestFolder" + Path = "$($env:SystemDrive)\TestFolder" Identity = "NT AUTHORITY\NETWORK SERVICE" Rights = @("Read","Synchronize") } @@ -113,7 +113,7 @@ try Context "A permission exists that shouldn't" { $testParams = @{ - Path = "C:\TestFolder" + Path = "$($env:SystemDrive)\TestFolder" Identity = "NT AUTHORITY\NETWORK SERVICE" Ensure = "Absent" } @@ -145,7 +145,7 @@ try Context "A permission doesn't exist and shouldn't" { $testParams = @{ - Path = "C:\TestFolder" + Path = "$($env:SystemDrive)\TestFolder" Identity = "NT AUTHORITY\NETWORK SERVICE" Ensure = "Absent" } @@ -169,7 +169,7 @@ try Context "A path doesn't exist" { $testParams = @{ - Path = "C:\TestFolder" + Path = "$($env:SystemDrive)\TestFolder" Identity = "NT AUTHORITY\NETWORK SERVICE" Rights = @("Read","Synchronize") } From 9b30cd4fa3a58c0499ab6cfab08dbbef38dc88a4 Mon Sep 17 00:00:00 2001 From: Brian Farnhill Date: Tue, 16 Aug 2016 09:01:43 +1000 Subject: [PATCH 22/23] Code review feedback --- README.md | 4 ++-- .../MSFT_xFileSystemAccessRule.integration.tests.ps1 | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 4c091f6..ebfa0d7 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Configuration DisableLocalIEEsc This configuration will grant the network service account full control over the directory. ```powershell -Configuration DisableLocalIEEsc +Configuration FullControlExample { Import-DSCResource -Module MSFT_xSystemSecurity @@ -163,7 +163,7 @@ Configuration DisableLocalIEEsc { xFileSystemAccessRule FullControlExample { - Path = "C:\some\path" + Path = "$env:SystemDrive\some\path" Identity = "NT AUTHORITY\NETWORK SERVICE" Rights = @("FullControl") } diff --git a/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 b/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 index e3adb6c..57d0798 100644 --- a/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 +++ b/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1 @@ -19,7 +19,7 @@ try $ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1" . $ConfigFile - New-Item -Path "C:\SampleFolder" -ItemType Directory + New-Item -Path "$env:SystemDrive\SampleFolder" -ItemType Directory Describe "$($script:DSCResourceName)_Integration" { @@ -89,7 +89,7 @@ try } - Remove-Item -Path "C:\SampleFolder" -Recurse -Force -Confirm:$false + Remove-Item -Path "$env:SystemDrive\SampleFolder" -Recurse -Force -Confirm:$false } } finally From 25d95a84caaff1c4a3ec16ccf3a0d2a4c0123ace Mon Sep 17 00:00:00 2001 From: Katie Keim Date: Wed, 21 Sep 2016 13:50:50 -0700 Subject: [PATCH 23/23] Releasing version 1.2.0.0 --- README.md | 4 +++- appveyor.yml | 4 ++-- xSystemSecurity.psd1 | 8 ++++++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index ebfa0d7..05ebb4c 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,8 @@ Please refer to [this article](http://technet.microsoft.com/en-us/library/dd8832 ## Versions ### Unreleased + +### 1.2.0.0 * Converted appveyor.yml to install Pester from PSGallery instead of from Chocolatey. * Added xFileSystemAccessRule resource @@ -169,4 +171,4 @@ Configuration FullControlExample } } } -``` \ No newline at end of file +``` diff --git a/appveyor.yml b/appveyor.yml index 49daf5e..4f3f60a 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,7 +1,7 @@ #---------------------------------# # environment configuration # #---------------------------------# -version: 1.1.{build}.0 +version: 1.2.{build}.0 install: - git clone https://github.com/PowerShell/DscResource.Tests - ps: | @@ -38,7 +38,7 @@ deploy_script: # Creating project artifact $stagingDirectory = (Resolve-Path ..).Path $manifest = Join-Path $pwd "xSystemSecurity.psd1" - (Get-Content $manifest -Raw).Replace("1.1.0.0", $env:APPVEYOR_BUILD_VERSION) | Out-File $manifest + (Get-Content $manifest -Raw).Replace("1.2.0.0", $env:APPVEYOR_BUILD_VERSION) | Out-File $manifest $zipFilePath = Join-Path $stagingDirectory "$(Split-Path $pwd -Leaf).zip" Add-Type -assemblyname System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::CreateFromDirectory($pwd, $zipFilePath) diff --git a/xSystemSecurity.psd1 b/xSystemSecurity.psd1 index 0236578..e2bff42 100644 --- a/xSystemSecurity.psd1 +++ b/xSystemSecurity.psd1 @@ -7,7 +7,7 @@ @{ # Version number of this module. -ModuleVersion = '1.1.0.0' +ModuleVersion = '1.2.0.0' # ID used to uniquely identify this module GUID = 'e30107af-a22a-48fb-b7bc-7d2b98489ac5' @@ -54,10 +54,14 @@ PrivateData = @{ # IconUri = '' # ReleaseNotes of this module - # ReleaseNotes = '' + ReleaseNotes = '* Converted appveyor.yml to install Pester from PSGallery instead of from Chocolatey. +* Added xFileSystemAccessRule resource + +' } # End of PSData hashtable } # End of PrivateData hashtable } +