diff --git a/.appveyor/appveyor.psm1 b/.appveyor/appveyor.psm1 new file mode 100644 index 000000000..58d8d9cec --- /dev/null +++ b/.appveyor/appveyor.psm1 @@ -0,0 +1,127 @@ +function Start-AppveyorInstallTask +{ + Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force + Install-Module -Name Pester -Force + Start-Process -Wait -FilePath "git" -ArgumentList @( + "clone", + "-q", + "https://github.com/PowerShell/DscResource.Tests", + (Join-Path -Path $env:APPVEYOR_BUILD_FOLDER ` + -ChildPath "Modules\SharePointDsc\DscResource.Tests") + ) + Start-Process -Wait -FilePath "git" -ArgumentList @( + "clone", + "-q", + "https://github.com/PowerShell/DscResources", + (Join-Path -Path $env:APPVEYOR_BUILD_FOLDER -ChildPath "DscResources") + ) + $testHelperPath = Join-Path -Path $env:APPVEYOR_BUILD_FOLDER ` + -ChildPath "Modules\SharePointDsc\DscResource.Tests\TestHelper.psm1" + Import-Module -Name $testHelperPath -Force +} + +function Start-AppveyorTestScriptTask +{ + $testResultsFile = ".\TestsResults.xml" + $testHarnessPath = Join-Path -Path $env:APPVEYOR_BUILD_FOLDER ` + -ChildPath "\Tests\Unit\SharePointDsc.TestHarness.psm1" + $dscTestsPath = Join-Path -Path $env:APPVEYOR_BUILD_FOLDER ` + -ChildPath "Modules\SharePointDsc\DscResource.Tests" + Import-Module -Name $testHarnessPath + + $result = Invoke-SPDscUnitTestSuite -TestResultsFile $testResultsFile ` + -DscTestsPath $dscTestsPath + + $webClient = New-Object -TypeName "System.Net.WebClient" + + $testResultsFilePath = Resolve-Path -Path $testResultsFile + $webClient.UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", + $testResultsFilePath) + + if ($result.FailedCount -gt 0) + { + throw "$($result.FailedCount) tests failed." + } +} + +function Start-AppveyorAfterTestTask +{ + # Move the DSC resource tests folder out so it isn't included in the ZIP module that is made + $dscTestsPath = Join-Path -Path $env:APPVEYOR_BUILD_FOLDER ` + -ChildPath "Modules\SharePointDsc\DscResource.Tests" + Move-Item -Path $dscTestsPath -Destination $env:APPVEYOR_BUILD_FOLDER + + # Import the module again from its new location + $testHelperPath = Join-Path -Path $env:APPVEYOR_BUILD_FOLDER ` + -ChildPath "DscResource.Tests\TestHelper.psm1" + Import-Module -Name $testHelperPath -Force + + $mainModulePath = Join-Path -Path $env:APPVEYOR_BUILD_FOLDER -ChildPath "modules\SharePointDsc" + + # Write the PowerShell help files + $docoPath = Join-Path -Path $env:APPVEYOR_BUILD_FOLDER ` + -ChildPath "modules\SharePointDsc\en-US" + New-Item -Path $docoPath -ItemType Directory + $docoHelperPath = Join-Path -Path $env:APPVEYOR_BUILD_FOLDER ` + -ChildPath "DscResources\DscResource.DocumentationHelper" + Import-Module -Name $docoHelperPath + Write-DscResourcePowerShellHelp -OutputPath $docoPath -ModulePath $mainModulePath -Verbose + + # Import so we can create zip files + Add-Type -assemblyname System.IO.Compression.FileSystem + + # Generate the wiki content for the release and zip/publish it to appveyor + $wikiContentPath = Join-Path -Path $env:APPVEYOR_BUILD_FOLDER -ChildPath "wikicontent" + New-Item -Path $wikiContentPath -ItemType Directory + Write-DscResourceWikiSite -OutputPath $wikiContentPath -ModulePath $mainModulePath -Verbose + + $zipFileName = "SharePointDsc_$($env:APPVEYOR_BUILD_VERSION)_wikicontent.zip" + [System.IO.Compression.ZipFile]::CreateFromDirectory($wikiContentPath, + "$env:APPVEYOR_BUILD_FOLDER\$zipFileName") + Get-ChildItem -Path "$env:APPVEYOR_BUILD_FOLDER\$zipFileName" | ForEach-Object -Process { + Push-AppveyorArtifact $_.FullName -FileName $_.Name + } + + # Remove the readme files that are used to generate documentation so they aren't shipped + $readmePaths = "$env:APPVEYOR_BUILD_FOLDER\Modules\**\readme.md" + Get-ChildItem -Path $readmePaths -Recurse | Remove-Item -Confirm:$false + + # Add the appropriate build number to the manifest and zip/publish everything to appveyor + $manifest = Join-Path -Path $env:APPVEYOR_BUILD_FOLDER -ChildPath "modules\SharePointDsc\SharePointDsc.psd1" + (Get-Content $manifest -Raw).Replace("1.4.0.0", $env:APPVEYOR_BUILD_VERSION) | Out-File $manifest + $zipFileName = "SharePointDsc_$($env:APPVEYOR_BUILD_VERSION).zip" + [System.IO.Compression.ZipFile]::CreateFromDirectory($mainModulePath, "$env:APPVEYOR_BUILD_FOLDER\$zipFileName") + New-DscChecksum -Path $env:APPVEYOR_BUILD_FOLDER -Outpath $env:APPVEYOR_BUILD_FOLDER + Get-ChildItem -Path "$env:APPVEYOR_BUILD_FOLDER\$zipFileName" | ForEach-Object -Process { + Push-AppveyorArtifact $_.FullName -FileName $_.Name + } + Get-ChildItem -Path "$env:APPVEYOR_BUILD_FOLDER\$zipFileName.checksum" | ForEach-Object -Process { + Push-AppveyorArtifact $_.FullName -FileName $_.Name + } + + Set-Location -Path $mainModulePath + $nuspecParams = @{ + packageName = "SharePointDsc" + version = $env:APPVEYOR_BUILD_VERSION + author = "Microsoft" + owners = "Microsoft" + licenseUrl = "https://github.com/PowerShell/DscResources/blob/master/LICENSE" + projectUrl = "https://github.com/$($env:APPVEYOR_REPO_NAME)" + packageDescription = "SharePointDsc" + tags = "DesiredStateConfiguration DSC DSCResourceKit" + destinationPath = "." + } + New-Nuspec @nuspecParams + + Start-Process -FilePath "nuget" -Wait -ArgumentList @( + "pack", + ".\SharePointDsc.nuspec", + "-outputdirectory $env:APPVEYOR_BUILD_FOLDER" + ) + $nuGetPackageName = "SharePointDsc." + $env:APPVEYOR_BUILD_VERSION + ".nupkg" + Get-ChildItem "$env:APPVEYOR_BUILD_FOLDER\$nuGetPackageName" | ForEach-Object -Process { + Push-AppveyorArtifact $_.FullName -FileName $_.Name + } +} + +Export-ModuleMember -Function * diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 084f1747b..f426db79b 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -12,7 +12,7 @@ To aid community reviewers in reviewing and merging your PR, please take the tim - [ ] Change details added to Unreleased section of changelog.md? - [ ] Added/updated documentation and descriptions in .schema.mof files where appropriate? - [ ] Examples updated for both the single server and small farm templates in the examples folder? -- [ ] New/changed code adheres to [Style Guidelines]?(https://github.com/PowerShell/DscResources/blob/master/StyleGuidelines.md)? +- [ ] New/changed code adheres to [Style Guidelines](https://github.com/PowerShell/DscResources/blob/master/StyleGuidelines.md)? - [ ] [Unit and Integration tests](https://github.com/PowerShell/DscResources/blob/master/TestsGuidelines.md) created/updated where possible? **DELETE THIS LINE AND BELOW** diff --git a/CHANGELOG.md b/CHANGELOG.md index 263726a34..6017a09f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,41 @@ # Change log for SharePointDsc +### 1.4 + * Set-TargetResource of Service Application now also removes all associated proxies + * Fixed issue with all SPServiceApplication for OS not in En-Us language, add GetType().FullName method in: + - SPAccessServiceApp + - SPAppManagementServiceApp + - SPBCSServiceApp + - SPExcelServiceApp + - SPManagedMetaDataServiceApp + - SPPerformancePointServiceApp + - SPSearchServiceApp + - SPSearchCrawlRule + - SPSecureStoreServiceApp + - SPSubscriptionSettingsServiceApp + - SPUsageApplication + - SPUserProfileServiceApp + - SPVisioServiceApp + - SPWordAutomationServiceApp + - SPWorkManagementServiceApp + * Fixed issue with SPServiceInstance for OS not in En-Us language, add GetType().Name method in: + - SPDistributedCacheService + - SPUserProfileSyncService + * Fixed issue with SPInstallLanguagePack to install before farm creation + * Fixed issue with mounting SPContentDatabase + * Fixed issue with SPShellAdmin and Content Database method + * Fixed issue with SPServiceInstance (Set-TargetResource) for OS not in En-Us language + * Added .Net 4.6 support check to SPInstall and SPInstallPrereqs + * Improved code styling + * SPVisioServiceapplication now creates proxy and lets you specify a name for it + * New resources: SPAppStoreSettings + * Fixed bug with SPInstallPrereqs to allow minor version changes to prereqs for SP2016 + * Refactored unit tests to consolidate and streamline test approaches + * Updated SPExcelServiceApp resource to add support for trusted file locations and most other properties of the service app + * Added support to SPMetadataServiceApp to allow changing content type hub URL on existing service apps + * Fixed a bug that would cause SPSearchResultSource to throw exceptions when the enterprise search centre URL has not been set + * Updated documentation of SPProductUpdate to reflect the required install order of product updates + ### 1.3 * Fixed typo on return value in SPServiceAppProxyGroup * Fixed SPJoinFarm to not write output during successful farm join diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPAccessServiceApp/MSFT_SPAccessServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPAccessServiceApp/MSFT_SPAccessServiceApp.psm1 index b8710ee61..c71cda14f 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPAccessServiceApp/MSFT_SPAccessServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPAccessServiceApp/MSFT_SPAccessServiceApp.psm1 @@ -45,7 +45,7 @@ function Get-TargetResource return $nullReturn } $serviceApp = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "Access Services Web Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Access.Services.MossHost.AccessServicesWebServiceApplication" } if ($null -eq $serviceApp) @@ -91,6 +91,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting Access Services service app '$Name'" + $result = Get-TargetResource @PSBoundParameters if ($result.Ensure -eq "Absent" -and $Ensure -eq "Present") @@ -120,9 +122,19 @@ function Set-TargetResource $params = $args[0] $app = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { - $_.TypeName -eq "Access Services Web Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Access.Services.MossHost.AccessServicesWebServiceApplication" + } + + $proxies = Get-SPServiceApplicationProxy + foreach($proxyInstance in $proxies) + { + if($app.IsConnected($proxyInstance)) + { + $proxyInstance.Delete() + } } - Remove-SPServiceApplication $app -Confirm:$false + + Remove-SPServiceApplication -Identity $app -Confirm:$false } } } @@ -156,7 +168,9 @@ function Test-TargetResource ) Write-Verbose -Message "Testing for Access Service Application '$Name'" + $PSBoundParameters.Ensure = $Ensure + return Test-SPDscParameterState -CurrentValues (Get-TargetResource @PSBoundParameters) ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("Ensure") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPAlternateUrl/MSFT_SPAlternateUrl.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPAlternateUrl/MSFT_SPAlternateUrl.psm1 index 406738b88..fb69fa0b0 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPAlternateUrl/MSFT_SPAlternateUrl.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPAlternateUrl/MSFT_SPAlternateUrl.psm1 @@ -96,9 +96,9 @@ function Set-TargetResource ) - $CurrentValues = Get-TargetResource @PSBoundParameters + Write-Verbose -Message "Setting Alternate URL for $Zone in $WebAppUrl" - Write-Verbose -Message "Updating app domain settings for $SiteUrl" + $CurrentValues = Get-TargetResource @PSBoundParameters if ($Ensure -eq "Present") { @@ -168,9 +168,10 @@ function Test-TargetResource ) - Write-Verbose -Message "Testing alternate URL configuration" + Write-Verbose -Message "Testing Alternate URL for $Zone in $WebAppUrl" $PSBoundParameters.Ensure = $Ensure + if ([string]::IsNullOrEmpty($Url) -and $Ensure -eq "Present") { throw "URL must be specified when ensure is set to present" diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPAntivirusSettings/MSFT_SPAntivirusSettings.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPAntivirusSettings/MSFT_SPAntivirusSettings.psm1 index 2a109fa7e..5d522b19b 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPAntivirusSettings/MSFT_SPAntivirusSettings.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPAntivirusSettings/MSFT_SPAntivirusSettings.psm1 @@ -198,6 +198,7 @@ function Test-TargetResource ) Write-Verbose -Message "Testing antivirus configuration settings" + return Test-SPDscParameterState -CurrentValues (Get-TargetResource @PSBoundParameters) ` -DesiredValues $PSBoundParameters } diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPAppCatalog/MSFT_SPAppCatalog.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPAppCatalog/MSFT_SPAppCatalog.psm1 index 56c85e28b..81e322120 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPAppCatalog/MSFT_SPAppCatalog.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPAppCatalog/MSFT_SPAppCatalog.psm1 @@ -61,7 +61,8 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Updating app domain settings for $SiteUrl" + Write-Verbose -Message "Setting app catalog status of $SiteUrl" + Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { @@ -85,7 +86,8 @@ function Test-TargetResource $InstallAccount ) - Write-Verbose -Message "Testing app domain settings" + Write-Verbose -Message "Testing app catalog status of $SiteUrl" + return Test-SPDscParameterState -CurrentValues (Get-TargetResource @PSBoundParameters) ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("SiteUrl") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPAppDomain/MSFT_SPAppDomain.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPAppDomain/MSFT_SPAppDomain.psm1 index 5b1cb0485..f1f2ea2df 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPAppDomain/MSFT_SPAppDomain.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPAppDomain/MSFT_SPAppDomain.psm1 @@ -17,7 +17,7 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Checking app urls settings" + Write-Verbose -Message "Getting app domain settings" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -53,7 +53,8 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Updating app domain settings " + Write-Verbose -Message "Setting app domain settings" + Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { @@ -83,7 +84,8 @@ function Test-TargetResource $InstallAccount ) - Write-Verbose -Message "Testing app domain settings" + Write-Verbose -Message "Getting app domain settings" + return Test-SPDscParameterState -CurrentValues (Get-TargetResource @PSBoundParameters) ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("AppDomain", "Prefix") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPAppManagementServiceApp/MSFT_SPAppManagementServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPAppManagementServiceApp/MSFT_SPAppManagementServiceApp.psm1 index d7e8fc4b8..dc86a947d 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPAppManagementServiceApp/MSFT_SPAppManagementServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPAppManagementServiceApp/MSFT_SPAppManagementServiceApp.psm1 @@ -33,6 +33,7 @@ function Get-TargetResource [System.Management.Automation.PSCredential] $InstallAccount ) + Write-Verbose -Message "Getting App management service app '$Name'" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` @@ -53,7 +54,7 @@ function Get-TargetResource return $nullReturn } $serviceApp = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "App Management Service Application" + $_.GetType().FullName -eq "Microsoft.SharePoint.AppManagement.AppManagementServiceApplication" } if ($null -eq $serviceApp) @@ -122,6 +123,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting App management service app '$Name'" + $result = Get-TargetResource @PSBoundParameters if ($result.Ensure -eq "Absent" -and $Ensure -eq "Present") @@ -177,7 +180,7 @@ function Set-TargetResource $appPool = Get-SPServiceApplicationPool -Identity $params.ApplicationPool $app = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { - $_.TypeName -eq "App Management Service Application" + $_.GetType().FullName -eq "Microsoft.SharePoint.AppManagement.AppManagementServiceApplication" } $app.ApplicationPool = $appPool $app.Update() @@ -195,9 +198,19 @@ function Set-TargetResource $params = $args[0] $app = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { - $_.TypeName -eq "App Management Service Application" + $_.GetType().FullName -eq "Microsoft.SharePoint.AppManagement.AppManagementServiceApplication" + } + + $proxies = Get-SPServiceApplicationProxy + foreach($proxyInstance in $proxies) + { + if($app.IsConnected($proxyInstance)) + { + $proxyInstance.Delete() + } } - Remove-SPServiceApplication $app -Confirm:$false + + Remove-SPServiceApplication -Identity $app -Confirm:$false } } } @@ -237,10 +250,11 @@ function Test-TargetResource [System.Management.Automation.PSCredential] $InstallAccount ) - - Write-Verbose -Message "Testing for App management Service Application '$Name'" + + Write-Verbose -Message "Testing App management service app '$Name'" $PSBoundParameters.Ensure = $Ensure + return Test-SPDscParameterState -CurrentValues (Get-TargetResource @PSBoundParameters) ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("ApplicationPool", "Ensure") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPAppStoreSettings/MSFT_SPAppStoreSettings.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPAppStoreSettings/MSFT_SPAppStoreSettings.psm1 new file mode 100644 index 000000000..bb0d08d4c --- /dev/null +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPAppStoreSettings/MSFT_SPAppStoreSettings.psm1 @@ -0,0 +1,167 @@ +function Get-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Collections.Hashtable])] + param + ( + [parameter(Mandatory = $true)] + [System.String] + $WebAppUrl, + + [parameter(Mandatory = $false)] + [System.Boolean] + $AllowAppPurchases, + + [parameter(Mandatory = $false)] + [System.Boolean] + $AllowAppsForOffice, + + [parameter(Mandatory = $false)] + [System.Management.Automation.PSCredential] + $InstallAccount + ) + + Write-Verbose -Message "Getting app store settings of $WebAppUrl" + + $result = Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments $PSBoundParameters ` + -ScriptBlock { + $params = $args[0] + + $nullreturn = @{ + WebAppUrl = $null + InstallAccount = $params.InstallAccount + } + + $wa = Get-SPWebApplication -Identity $params.WebAppUrl -ErrorAction SilentlyContinue + if ($null -eq $wa) + { + return $nullreturn + } + + $currentAAP = (Get-SPAppAcquisitionConfiguration -WebApplication $params.WebAppUrl).Enabled + $AllowAppPurchases = [System.Convert]::ToBoolean($currentAAP) + $currentAAFO = (Get-SPOfficeStoreAppsDefaultActivation -WebApplication $params.WebAppUrl).Enable + $AllowAppsForOffice = [System.Convert]::ToBoolean($currentAAFO) + + return @{ + WebAppUrl = $params.WebAppUrl + AllowAppPurchases = $AllowAppPurchases + AllowAppsForOffice = $AllowAppsForOffice + InstallAccount = $params.InstallAccount + } + } + return $result +} + +function Set-TargetResource +{ + [CmdletBinding()] + param + ( + [parameter(Mandatory = $true)] + [System.String] + $WebAppUrl, + + [parameter(Mandatory = $false)] + [System.Boolean] + $AllowAppPurchases, + + [parameter(Mandatory = $false)] + [System.Boolean] + $AllowAppsForOffice, + + [parameter(Mandatory = $false)] + [System.Management.Automation.PSCredential] + $InstallAccount + ) + + Write-Verbose -Message "Setting app store settings of $WebAppUrl" + + Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments $PSBoundParameters ` + -ScriptBlock { + $params = $args[0] + + $wa = Get-SPWebApplication -Identity $params.WebAppUrl -ErrorAction SilentlyContinue + if ($null -eq $wa) + { + throw ("Specified web application does not exist.") + } + + if ($params.ContainsKey("AllowAppPurchases")) + { + $current = (Get-SPAppAcquisitionConfiguration -WebApplication $params.WebAppUrl).Enabled + $AllowAppPurchases = [System.Convert]::ToBoolean($current) + if ($AllowAppPurchases -ne $params.AllowAppPurchases) + { + Set-SPAppAcquisitionConfiguration -WebApplication $params.WebAppUrl ` + -Enable $params.AllowAppPurchases + } + } + + if ($params.ContainsKey("AllowAppsForOffice")) + { + $current = (Get-SPOfficeStoreAppsDefaultActivation -WebApplication $params.WebAppUrl).Enable + $AllowAppsForOffice = [System.Convert]::ToBoolean($current) + if ($AllowAppsForOffice -ne $params.AllowAppsForOffice) + { + Set-SPOfficeStoreAppsDefaultActivation -WebApplication $params.WebAppUrl ` + -Enable $params.AllowAppsForOffice + } + } + } +} + +function Test-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Boolean])] + param + ( + [parameter(Mandatory = $true)] + [System.String] + $WebAppUrl, + + [parameter(Mandatory = $false)] + [System.Boolean] + $AllowAppPurchases, + + [parameter(Mandatory = $false)] + [System.Boolean] + $AllowAppsForOffice, + + [parameter(Mandatory = $false)] + [System.Management.Automation.PSCredential] + $InstallAccount + ) + + Write-Verbose -Message "Testing app store settings of $WebAppUrl" + + $currentValues = Get-TargetResource @PSBoundParameters + + if ($null -eq $currentValues.WebAppUrl) { + Write-Verbose -Message "Specified web application does not exist." + return $false + } + + if ($PSBoundParameters.ContainsKey("AllowAppPurchases")) + { + if ($AllowAppPurchases -ne $currentValues.AllowAppPurchases) + { + return $false + } + } + + if ($PSBoundParameters.ContainsKey("AllowAppsForOffice")) + { + if ($AllowAppsForOffice -ne $currentValues.AllowAppsForOffice) + { + return $false + } + } + + return $true +} + +Export-ModuleMember -Function *-TargetResource diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPAppStoreSettings/MSFT_SPAppStoreSettings.schema.mof b/Modules/SharePointDsc/DSCResources/MSFT_SPAppStoreSettings/MSFT_SPAppStoreSettings.schema.mof new file mode 100644 index 000000000..90b3455c5 --- /dev/null +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPAppStoreSettings/MSFT_SPAppStoreSettings.schema.mof @@ -0,0 +1,8 @@ +[ClassVersion("1.0.0.0"), FriendlyName("SPAppStoreSettings")] +class MSFT_SPAppStoreSettings : OMI_BaseResource +{ + [Key, Description("The URL of the web application")] string WebAppUrl; + [Write, Description("Specifies if App Purchases from the SharePoint Store are allowed")] Boolean AllowAppPurchases; + [Write, Description("Specifies if App Purchases for Office applications are allowed")] Boolean AllowAppsForOffice; + [Write, Description("POWERSHELL 4 ONLY: The account to run this resource as, use PsDscRunAsCredential if using PowerShell 5"), EmbeddedInstance("MSFT_Credential")] String InstallAccount; +}; diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPAppStoreSettings/readme.md b/Modules/SharePointDsc/DSCResources/MSFT_SPAppStoreSettings/readme.md new file mode 100644 index 000000000..fbbed67d4 --- /dev/null +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPAppStoreSettings/readme.md @@ -0,0 +1,3 @@ +**Description** + +This resource will configure the ability to purchase apps for both SharePoint and Office apps. diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPBCSServiceApp/MSFT_SPBCSServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPBCSServiceApp/MSFT_SPBCSServiceApp.psm1 index 843ded80e..27e034e24 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPBCSServiceApp/MSFT_SPBCSServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPBCSServiceApp/MSFT_SPBCSServiceApp.psm1 @@ -29,6 +29,7 @@ function Get-TargetResource [System.Management.Automation.PSCredential] $InstallAccount ) + Write-Verbose -Message "Getting BCS service app '$Name'" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` @@ -50,7 +51,7 @@ function Get-TargetResource return $nullReturn } $serviceApp = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "Business Data Connectivity Service Application" + $_.GetType().FullName -eq "Microsoft.SharePoint.BusinessData.SharedService.BdcServiceApplication" } if ($null -eq $serviceApp) @@ -104,6 +105,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting BCS service app '$Name'" + $result = Get-TargetResource @PSBoundParameters if ($result.Ensure -eq "Absent" -and $Ensure -eq "Present") @@ -139,7 +142,7 @@ function Set-TargetResource Get-SPServiceApplication -Name $params.Name ` | Where-Object -FilterScript { - $_.TypeName -eq "Business Data Connectivity Service Application" + $_.GetType().FullName -eq "Microsoft.SharePoint.BusinessData.SharedService.BdcServiceApplication" } ` | Set-SPBusinessDataCatalogServiceApplication -ApplicationPool $appPool } @@ -156,9 +159,19 @@ function Set-TargetResource $params = $args[0] $app = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { - $_.TypeName -eq "Business Data Connectivity Service Application" + $_.GetType().FullName -eq "Microsoft.SharePoint.BusinessData.SharedService.BdcServiceApplication" + } + + $proxies = Get-SPServiceApplicationProxy + foreach($proxyInstance in $proxies) + { + if($app.IsConnected($proxyInstance)) + { + $proxyInstance.Delete() + } } - Remove-SPServiceApplication $app -Confirm:$false + + Remove-SPServiceApplication -Identity $app -Confirm:$false } } } @@ -195,9 +208,10 @@ function Test-TargetResource $InstallAccount ) - Write-Verbose -Message "Testing for BCS Service Application '$Name'" + Write-Verbose -Message "Testing BCS service app '$Name'" $PSBoundParameters.Ensure = $Ensure + return Test-SPDscParameterState -CurrentValues (Get-TargetResource @PSBoundParameters) ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("ApplicationPool", "Ensure") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPBlobCacheSettings/MSFT_SPBlobCacheSettings.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPBlobCacheSettings/MSFT_SPBlobCacheSettings.psm1 index 0eaa28a98..2c2727e73 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPBlobCacheSettings/MSFT_SPBlobCacheSettings.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPBlobCacheSettings/MSFT_SPBlobCacheSettings.psm1 @@ -37,7 +37,7 @@ function Get-TargetResource [System.Management.Automation.PSCredential] $InstallAccount ) - + Write-Verbose -Message "Getting blob cache settings for $WebAppUrl" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPCacheAccounts/MSFT_SPCacheAccounts.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPCacheAccounts/MSFT_SPCacheAccounts.psm1 index 14a2106f6..3ade9ccb7 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPCacheAccounts/MSFT_SPCacheAccounts.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPCacheAccounts/MSFT_SPCacheAccounts.psm1 @@ -4,11 +4,25 @@ function Get-TargetResource [OutputType([System.Collections.Hashtable])] param ( - [parameter(Mandatory = $true)] [System.String] $WebAppUrl, - [parameter(Mandatory = $true)] [System.String] $SuperUserAlias, - [parameter(Mandatory = $true)] [System.String] $SuperReaderAlias, - [parameter(Mandatory = $false)] [System.Boolean] $SetWebAppPolicy = $true, - [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount + [parameter(Mandatory = $true)] + [System.String] + $WebAppUrl, + + [parameter(Mandatory = $true)] + [System.String] + $SuperUserAlias, + + [parameter(Mandatory = $true)] + [System.String] + $SuperReaderAlias, + + [parameter(Mandatory = $false)] + [System.Boolean] + $SetWebAppPolicy = $true, + + [parameter(Mandatory = $false)] + [System.Management.Automation.PSCredential] + $InstallAccount ) Write-Verbose -Message "Getting cache accounts for $WebAppUrl" @@ -18,13 +32,16 @@ function Get-TargetResource $wa = Get-SPWebApplication -Identity $params.WebAppUrl -ErrorAction SilentlyContinue - if ($null -eq $wa) { return @{ - WebAppUrl = $params.WebAppUrl - SuperUserAlias = $null - SuperReaderAlias = $null - SetWebAppPolicy = $false - InstallAccount = $params.InstallAccount - } } + if ($null -eq $wa) + { + return @{ + WebAppUrl = $params.WebAppUrl + SuperUserAlias = $null + SuperReaderAlias = $null + SetWebAppPolicy = $false + InstallAccount = $params.InstallAccount + } + } $returnVal = @{ InstallAccount = $params.InstallAccount @@ -32,42 +49,85 @@ function Get-TargetResource } $policiesSet = $true - if ($wa.UseClaimsAuthentication -eq $true) { - if ($wa.Properties.ContainsKey("portalsuperuseraccount")) { - $claim = New-SPClaimsPrincipal -Identity $wa.Properties["portalsuperuseraccount"] -IdentityType EncodedClaim -ErrorAction SilentlyContinue - if ($null -ne $claim) { + if ($wa.UseClaimsAuthentication -eq $true) + { + if ($wa.Properties.ContainsKey("portalsuperuseraccount")) + { + $claim = New-SPClaimsPrincipal -Identity $wa.Properties["portalsuperuseraccount"] ` + -IdentityType EncodedClaim ` + -ErrorAction SilentlyContinue + if ($null -ne $claim) + { $returnVal.Add("SuperUserAlias", $claim.Value) - } else { + } + else + { $returnVal.Add("SuperUserAlias", "") } - } else { + } + else + { $returnVal.Add("SuperUserAlias", "") } - if ($wa.Properties.ContainsKey("portalsuperreaderaccount")) { - $claim = New-SPClaimsPrincipal -Identity $wa.Properties["portalsuperreaderaccount"] -IdentityType EncodedClaim -ErrorAction SilentlyContinue - if ($null -ne $claim) { + if ($wa.Properties.ContainsKey("portalsuperreaderaccount")) + { + $claim = New-SPClaimsPrincipal -Identity $wa.Properties["portalsuperreaderaccount"] ` + -IdentityType EncodedClaim ` + -ErrorAction SilentlyContinue + if ($null -ne $claim) + { $returnVal.Add("SuperReaderAlias", $claim.Value) - } else { + } + else + { $returnVal.Add("SuperReaderAlias", "") } - } else { + } + else + { $returnVal.Add("SuperReaderAlias", "") } - if ($wa.Policies.UserName -notcontains ((New-SPClaimsPrincipal -Identity $params.SuperReaderAlias -IdentityType WindowsSamAccountName).ToEncodedString())) { $policiesSet = $false } - if ($wa.Policies.UserName -notcontains ((New-SPClaimsPrincipal -Identity $params.SuperUserAlias -IdentityType WindowsSamAccountName).ToEncodedString())) { $policiesSet = $false } - } else { - if ($wa.Properties.ContainsKey("portalsuperuseraccount")) { + if ($wa.Policies.UserName -notcontains ((New-SPClaimsPrincipal -Identity $params.SuperReaderAlias ` + -IdentityType WindowsSamAccountName).ToEncodedString())) + { + $policiesSet = $false + } + + if ($wa.Policies.UserName -notcontains ((New-SPClaimsPrincipal -Identity $params.SuperUserAlias ` + -IdentityType WindowsSamAccountName).ToEncodedString())) + { + $policiesSet = $false + } + } + else + { + if ($wa.Properties.ContainsKey("portalsuperuseraccount")) + { $returnVal.Add("SuperUserAlias", $wa.Properties["portalsuperuseraccount"]) - } else { + } + else + { $returnVal.Add("SuperUserAlias", "") } - if ($wa.Properties.ContainsKey("portalsuperreaderaccount")) { + + if ($wa.Properties.ContainsKey("portalsuperreaderaccount")) + { $returnVal.Add("SuperReaderAlias", $wa.Properties["portalsuperreaderaccount"]) - } else { + } + else + { $returnVal.Add("SuperReaderAlias", "") } - if ($wa.Policies.UserName -notcontains $params.SuperReaderAlias) { $policiesSet = $false } - if ($wa.Policies.UserName -notcontains $params.SuperUserAlias) { $policiesSet = $false } + + if ($wa.Policies.UserName -notcontains $params.SuperReaderAlias) + { + $policiesSet = $false + } + + if ($wa.Policies.UserName -notcontains $params.SuperUserAlias) + { + $policiesSet = $false + } } $returnVal.Add("SetWebAppPolicy", $policiesSet) @@ -82,12 +142,25 @@ function Set-TargetResource [CmdletBinding()] param ( - [parameter(Mandatory = $true)] [System.String] $WebAppUrl, - [parameter(Mandatory = $true)] [System.String] $SuperUserAlias, - [parameter(Mandatory = $true)] [System.String] $SuperReaderAlias, - [parameter(Mandatory = $false)] [System.Boolean] $SetWebAppPolicy = $true, - [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount - ) + [parameter(Mandatory = $true)] + [System.String] + $WebAppUrl, + + [parameter(Mandatory = $true)] + [System.String] + $SuperUserAlias, + + [parameter(Mandatory = $true)] + [System.String] + $SuperReaderAlias, + + [parameter(Mandatory = $false)] + [System.Boolean] + $SetWebAppPolicy = $true, + + [parameter(Mandatory = $false)] + [System.Management.Automation.PSCredential] + $InstallAccount ) Write-Verbose -Message "Setting cache accounts for $WebAppUrl" @@ -97,44 +170,61 @@ function Set-TargetResource $params = $args[0] $wa = Get-SPWebApplication -Identity $params.WebAppUrl -ErrorAction SilentlyContinue - if ($null -eq $wa) { + if ($null -eq $wa) + { throw [Exception] "The web applications $($params.WebAppUrl) can not be found to set cache accounts" } - if ($wa.UseClaimsAuthentication -eq $true) { - $wa.Properties["portalsuperuseraccount"] = (New-SPClaimsPrincipal -Identity $params.SuperUserAlias -IdentityType WindowsSamAccountName).ToEncodedString() - $wa.Properties["portalsuperreaderaccount"] = (New-SPClaimsPrincipal -Identity $params.SuperReaderAlias -IdentityType WindowsSamAccountName).ToEncodedString() - } else { + if ($wa.UseClaimsAuthentication -eq $true) + { + $wa.Properties["portalsuperuseraccount"] = (New-SPClaimsPrincipal -Identity $params.SuperUserAlias ` + -IdentityType WindowsSamAccountName).ToEncodedString() + $wa.Properties["portalsuperreaderaccount"] = (New-SPClaimsPrincipal -Identity $params.SuperReaderAlias ` + -IdentityType WindowsSamAccountName).ToEncodedString() + } + else + { $wa.Properties["portalsuperuseraccount"] = $params.SuperUserAlias $wa.Properties["portalsuperreaderaccount"] = $params.SuperReaderAlias } - if ($params.SetWebAppPolicy -eq $true) { - if ($wa.UseClaimsAuthentication -eq $true) { - $claimsReader = (New-SPClaimsPrincipal -Identity $params.SuperReaderAlias -IdentityType WindowsSamAccountName).ToEncodedString() - if ($wa.Policies.UserName -contains $claimsReader) { + if ($params.SetWebAppPolicy -eq $true) + { + if ($wa.UseClaimsAuthentication -eq $true) + { + $claimsReader = (New-SPClaimsPrincipal -Identity $params.SuperReaderAlias ` + -IdentityType WindowsSamAccountName).ToEncodedString() + if ($wa.Policies.UserName -contains $claimsReader) + { $wa.Policies.Remove($claimsReader) } $policy = $wa.Policies.Add($claimsReader, "Super Reader (Claims)") $policyRole = $wa.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullRead) $policy.PolicyRoleBindings.Add($policyRole) - $claimsSuper = (New-SPClaimsPrincipal -Identity $params.SuperUserAlias -IdentityType WindowsSamAccountName).ToEncodedString() - if ($wa.Policies.UserName -contains $claimsSuper) { + $claimsSuper = (New-SPClaimsPrincipal -Identity $params.SuperUserAlias ` + -IdentityType WindowsSamAccountName).ToEncodedString() + if ($wa.Policies.UserName -contains $claimsSuper) + { $wa.Policies.Remove($claimsSuper) } $policy = $wa.Policies.Add($claimsSuper, "Super User (Claims)") $policyRole = $wa.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullControl) $policy.PolicyRoleBindings.Add($policyRole) - } else { - if ($wa.Policies.UserName -contains $params.SuperReaderAlias) { + } + else + { + if ($wa.Policies.UserName -contains $params.SuperReaderAlias) + { $wa.Policies.Remove($params.SuperReaderAlias) } + $readPolicy = $wa.Policies.Add($params.SuperReaderAlias, "Super Reader") $readPolicyRole = $wa.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullRead) $readPolicy.PolicyRoleBindings.Add($readPolicyRole) - if ($wa.Policies.UserName -contains $params.SuperUserAlias) { + if ($wa.Policies.UserName -contains $params.SuperUserAlias) + { $wa.Policies.Remove($params.SuperUserAlias) } $policy = $wa.Policies.Add($params.SuperUserAlias, "Super User") @@ -154,17 +244,37 @@ function Test-TargetResource [OutputType([System.Boolean])] param ( - [parameter(Mandatory = $true)] [System.String] $WebAppUrl, - [parameter(Mandatory = $true)] [System.String] $SuperUserAlias, - [parameter(Mandatory = $true)] [System.String] $SuperReaderAlias, - [parameter(Mandatory = $false)] [System.Boolean] $SetWebAppPolicy = $true, - [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount - ) + [parameter(Mandatory = $true)] + [System.String] + $WebAppUrl, + + [parameter(Mandatory = $true)] + [System.String] + $SuperUserAlias, + + [parameter(Mandatory = $true)] + [System.String] + $SuperReaderAlias, + + [parameter(Mandatory = $false)] + [System.Boolean] + $SetWebAppPolicy = $true, + + [parameter(Mandatory = $false)] + [System.Management.Automation.PSCredential] + $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters - $PSBoundParameters.SetWebAppPolicy = $SetWebAppPolicy Write-Verbose -Message "Testing cache accounts for $WebAppUrl" - return Test-SPDscParameterState -CurrentValues $CurrentValues -DesiredValues $PSBoundParameters -ValuesToCheck @("SuperUserAlias", "SuperReaderAlias", "SetWebAppPolicy") + + $PSBoundParameters.SetWebAppPolicy = $SetWebAppPolicy + + $CurrentValues = Get-TargetResource @PSBoundParameters + + return Test-SPDscParameterState -CurrentValues $CurrentValues ` + -DesiredValues $PSBoundParameters ` + -ValuesToCheck @("SuperUserAlias", ` + "SuperReaderAlias", ` + "SetWebAppPolicy") } Export-ModuleMember -Function *-TargetResource diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPConfigWizard/MSFT_SPConfigWizard.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPConfigWizard/MSFT_SPConfigWizard.psm1 index 4e6f38d0b..53937652c 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPConfigWizard/MSFT_SPConfigWizard.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPConfigWizard/MSFT_SPConfigWizard.psm1 @@ -83,7 +83,7 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Testing status of Configuration Wizard" + Write-Verbose -Message "Setting status of Configuration Wizard" $now = Get-Date if ($DatabaseUpgradeDays) @@ -229,6 +229,8 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing status of Configuration Wizard" + if ($Ensure -eq "Absent") { Write-Verbose -Message ("Ensure is set to Absent, so running the Configuration Wizard " + ` @@ -236,8 +238,6 @@ function Test-TargetResource return $true } - Write-Verbose -Message "Testing status of Configuration Wizard" - $currentValues = Get-TargetResource @PSBoundParameters return Test-SPDscParameterState -CurrentValues $CurrentValues ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPContentDatabase/MSFT_SPContentDatabase.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPContentDatabase/MSFT_SPContentDatabase.psm1 index 3c6be4f7f..6d68ce25f 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPContentDatabase/MSFT_SPContentDatabase.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPContentDatabase/MSFT_SPContentDatabase.psm1 @@ -4,14 +4,38 @@ function Get-TargetResource [OutputType([System.Collections.Hashtable])] param ( - [parameter(Mandatory = $true)] [System.String] $Name, - [parameter(Mandatory = $false)] [System.String] $DatabaseServer, - [parameter(Mandatory = $true)] [System.String] $WebAppUrl, - [parameter(Mandatory = $false)] [System.Boolean] $Enabled, - [parameter(Mandatory = $false)] [System.UInt16] $WarningSiteCount, - [parameter(Mandatory = $false)] [System.UInt16] $MaximumSiteCount, - [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", - [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount + [parameter(Mandatory = $true)] + [System.String] + $Name, + + [parameter(Mandatory = $false)] + [System.String] + $DatabaseServer, + + [parameter(Mandatory = $true)] + [System.String] + $WebAppUrl, + + [parameter(Mandatory = $false)] + [System.Boolean] + $Enabled, + + [parameter(Mandatory = $false)] + [System.UInt16] + $WarningSiteCount, + + [parameter(Mandatory = $false)] + [System.UInt16] + $MaximumSiteCount, + + [parameter(Mandatory = $false)] + [ValidateSet("Present","Absent")] + [System.String] + $Ensure = "Present", + + [parameter(Mandatory = $false)] + [System.Management.Automation.PSCredential] + $InstallAccount ) Write-Verbose -Message "Getting content database configuration settings" @@ -74,25 +98,46 @@ function Set-TargetResource [CmdletBinding()] param ( - [parameter(Mandatory = $true)] [System.String] $Name, - [parameter(Mandatory = $false)] [System.String] $DatabaseServer, - [parameter(Mandatory = $true)] [System.String] $WebAppUrl, - [parameter(Mandatory = $false)] [System.Boolean] $Enabled, - [parameter(Mandatory = $false)] [System.UInt16] $WarningSiteCount, - [parameter(Mandatory = $false)] [System.UInt16] $MaximumSiteCount, - [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", - [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount + [parameter(Mandatory = $true)] + [System.String] + $Name, + + [parameter(Mandatory = $false)] + [System.String] + $DatabaseServer, + + [parameter(Mandatory = $true)] + [System.String] + $WebAppUrl, + + [parameter(Mandatory = $false)] + [System.Boolean] + $Enabled, + + [parameter(Mandatory = $false)] + [System.UInt16] + $WarningSiteCount, + + [parameter(Mandatory = $false)] + [System.UInt16] + $MaximumSiteCount, + + [parameter(Mandatory = $false)] + [ValidateSet("Present","Absent")] + [System.String] + $Ensure = "Present", + + [parameter(Mandatory = $false)] + [System.Management.Automation.PSCredential] + $InstallAccount ) Write-Verbose -Message "Setting content database configuration settings" Invoke-SPDSCCommand -Credential $InstallAccount ` - -Arguments @($PSBoundParameters,$PSScriptRoot) ` + -Arguments $PSBoundParameters ` -ScriptBlock { $params = $args[0] - $scriptRoot = $args[1] - - Import-Module (Join-Path $scriptRoot "..\..\Modules\SharePointDsc.ContentDatabase\SPContentDatabase.psm1" -Resolve) # Use Get-SPDatabase instead of Get-SPContentDatabase because the Get-SPContentDatabase # does not return disabled databases. @@ -100,20 +145,24 @@ function Set-TargetResource $_.Type -eq "Content Database" -and $_.Name -eq $params.Name } - if ($params.Ensure -eq "Present") { + if ($params.Ensure -eq "Present") + { # Check if specified web application exists and throw exception when # this is not the case $webapp = Get-SPWebApplication | Where-Object -FilterScript { $_.Url.Trim("/") -eq $params.WebAppUrl.Trim("/") } - if ($null -eq $webapp) { + if ($null -eq $webapp) + { throw "Specified web application does not exist." } # Check if database exists - if ($null -ne $cdb) { - if ($cdb.Server -ne $params.DatabaseServer) { + if ($null -ne $cdb) + { + if ($cdb.Server -ne $params.DatabaseServer) + { throw ("Specified database server does not match the actual database " + ` "server. This resource cannot move the database to a different " + ` "SQL instance.") @@ -121,20 +170,65 @@ function Set-TargetResource # Check and change attached web application. # Dismount and mount to correct web application - if ($params.WebAppUrl.Trim("/") -ne $cdb.WebApplication.Url.Trim("/")) { + if ($params.WebAppUrl.Trim("/") -ne $cdb.WebApplication.Url.Trim("/")) + { Dismount-SPContentDatabase $params.Name -Confirm:$false - if ($params.ContainsKey("Enabled")) + $newParams= @{} + foreach ($param in $params.GetEnumerator()) { - $enabled = $params.Enabled + $skipParams = @("Enabled", "Ensure", "InstallAccount", "MaximumSiteCount", "WebAppUrl") + + if ($skipParams -notcontains $param.Key) + { + $newParams.$($param.Key) = $param.Value + } + + if ($param.Key -eq "MaximumSiteCount") + { + $newParams.MaxSiteCount = $param.Value + } + + if ($param.Key -eq "WebAppUrl") + { + $newParams.WebApplication = $param.Value + } + } + + try + { + $cdb = Mount-SPContentDatabase @newParams -ErrorAction Stop + } + catch + { + throw ("Error occurred while mounting content database. " + ` + "Content database is not mounted. " + ` + "Error details: $($_.Exception.Message)") + } + + if ($cdb.Status -eq "Online") + { + $cdbenabled = $true } else { - $enabled = $true + $cdbenabled = $false } - $parameters = @{} + $params - $cdb = Mount-SPDscContentDatabase $parameters $enabled + if ($params.Enabled -ne $cdbenabled) + { + switch ($params.Enabled) + { + $true + { + $cdb.Status = [Microsoft.SharePoint.Administration.SPObjectStatus]::Online + } + $false + { + $cdb.Status = [Microsoft.SharePoint.Administration.SPObjectStatus]::Disabled + } + } + } } # Check and change database status @@ -176,17 +270,61 @@ function Set-TargetResource else { # Database does not exist, but should. Create/mount database - if ($params.ContainsKey("Enabled")) + $newParams= @{} + foreach ($param in $params.GetEnumerator()) { - $enabled = $params.Enabled + $skipParams = @("Enabled", "Ensure", "InstallAccount", "MaximumSiteCount", "WebAppUrl") + + if ($skipParams -notcontains $param.Key) + { + $newParams.$($param.Key) = $param.Value + } + + if ($param.Key -eq "MaximumSiteCount") + { + $newParams.MaxSiteCount = $param.Value + } + + if ($param.Key -eq "WebAppUrl") + { + $newParams.WebApplication = $param.Value + } + } + + try + { + $cdb = Mount-SPContentDatabase @newParams -ErrorAction Stop + } + catch + { + throw ("Error occurred while mounting content database. " + ` + "Content database is not mounted. " + ` + "Error details: $($_.Exception.Message)") + } + + if ($cdb.Status -eq "Online") + { + $cdbenabled = $true } else { - $enabled = $true + $cdbenabled = $false } - $parameters = @{} + $params - $cdb = Mount-SPDscContentDatabase $parameters $enabled + if ($params.Enabled -ne $cdbenabled) + { + switch ($params.Enabled) + { + $true + { + $cdb.Status = [Microsoft.SharePoint.Administration.SPObjectStatus]::Online + } + $false + { + $cdb.Status = [Microsoft.SharePoint.Administration.SPObjectStatus]::Disabled + } + } + } } $cdb.Update() } @@ -208,17 +346,44 @@ function Test-TargetResource [OutputType([System.Boolean])] param ( - [parameter(Mandatory = $true)] [System.String] $Name, - [parameter(Mandatory = $false)] [System.String] $DatabaseServer, - [parameter(Mandatory = $true)] [System.String] $WebAppUrl, - [parameter(Mandatory = $false)] [System.Boolean] $Enabled, - [parameter(Mandatory = $false)] [System.UInt16] $WarningSiteCount, - [parameter(Mandatory = $false)] [System.UInt16] $MaximumSiteCount, - [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", - [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount + [parameter(Mandatory = $true)] + [System.String] + $Name, + + [parameter(Mandatory = $false)] + [System.String] + $DatabaseServer, + + [parameter(Mandatory = $true)] + [System.String] + $WebAppUrl, + + [parameter(Mandatory = $false)] + [System.Boolean] + $Enabled, + + [parameter(Mandatory = $false)] + [System.UInt16] + $WarningSiteCount, + + [parameter(Mandatory = $false)] + [System.UInt16] + $MaximumSiteCount, + + [parameter(Mandatory = $false)] + [ValidateSet("Present","Absent")] + [System.String] + $Ensure = "Present", + + [parameter(Mandatory = $false)] + [System.Management.Automation.PSCredential] + $InstallAccount ) Write-Verbose -Message "Testing content database configuration settings" + + $PSBoundParameters.Ensure = $Ensure + $CurrentValues = Get-TargetResource @PSBoundParameters if ($CurrentValues.DatabaseServer -ne $DatabaseServer) @@ -229,7 +394,6 @@ function Test-TargetResource return $false } - $PSBoundParameters.Ensure = $Ensure return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters } diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPCreateFarm/MSFT_SPCreateFarm.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPCreateFarm/MSFT_SPCreateFarm.psm1 index a785916f8..bdeae5942 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPCreateFarm/MSFT_SPCreateFarm.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPCreateFarm/MSFT_SPCreateFarm.psm1 @@ -50,7 +50,7 @@ function Get-TargetResource $ServerRole ) - Write-Verbose -Message "Checking for local SP Farm" + Write-Verbose -Message "Getting local SP Farm settings" if (($PSBoundParameters.ContainsKey("ServerRole") -eq $true) ` -and (Get-SPDSCInstalledProductVersion).FileMajorPart -ne 16) @@ -98,7 +98,7 @@ function Get-TargetResource InstallAccount = $params.InstallAccount Passphrase = $params.Passphrase.password AdminContentDatabaseName = $centralAdminSite.ContentDatabases[0].Name - CentralAdministrationPort = (New-Object System.Uri $centralAdminSite.Url).Port + CentralAdministrationPort = (New-Object -TypeName System.Uri $centralAdminSite.Url).Port CentralAdministrationAuth = $params.CentralAdministrationAuth } return $returnValue @@ -157,6 +157,8 @@ function Set-TargetResource $ServerRole ) + Write-Verbose -Message "Setting local SP Farm settings" + if (($PSBoundParameters.ContainsKey("ServerRole") -eq $true) ` -and (Get-SPDSCInstalledProductVersion).FileMajorPart -ne 16) { @@ -226,7 +228,8 @@ function Set-TargetResource Initialize-SPResourceSecurity Install-SPService Install-SPFeature -AllExistingFeatures -Force - New-SPCentralAdministration -Port $params.CentralAdministrationPort -WindowsAuthProvider $params.CentralAdministrationAuth + New-SPCentralAdministration -Port $params.CentralAdministrationPort ` + -WindowsAuthProvider $params.CentralAdministrationAuth Install-SPApplicationContent } | Out-Null } @@ -283,6 +286,8 @@ function Test-TargetResource $ServerRole ) + Write-Verbose -Message "Testing local SP Farm settings" + if (($PSBoundParameters.ContainsKey("ServerRole") -eq $true) ` -and (Get-SPDSCInstalledProductVersion).FileMajorPart -ne 16) { @@ -290,8 +295,12 @@ function Test-TargetResource } $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose "Checking for local farm presence" - if ($null -eq $CurrentValues) { return $false } + + if ($null -eq $CurrentValues) + { + return $false + } + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("FarmConfigDatabaseName") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPDatabaseAAG/MSFT_SPDatabaseAAG.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPDatabaseAAG/MSFT_SPDatabaseAAG.psm1 index 92382b911..182e8fc9a 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPDatabaseAAG/MSFT_SPDatabaseAAG.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPDatabaseAAG/MSFT_SPDatabaseAAG.psm1 @@ -26,7 +26,7 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Getting current AAG config for $DatabaseName" + Write-Verbose -Message "Getting AAG configuration for $DatabaseName" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -90,7 +90,7 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Setting AAG config for $DatabaseName" + Write-Verbose -Message "Setting AAG configuration for $DatabaseName" $CurrentValues = Get-TargetResource @PSBoundParameters @@ -187,10 +187,11 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing AAG configuration for $DatabaseName" + $PSBoundParameters.Ensure = $Ensure - $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Checking AAG configuration for $DatabaseName" + $CurrentValues = Get-TargetResource @PSBoundParameters return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPDesignerSettings/MSFT_SPDesignerSettings.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPDesignerSettings/MSFT_SPDesignerSettings.psm1 index 95fa1fdb8..b82421339 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPDesignerSettings/MSFT_SPDesignerSettings.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPDesignerSettings/MSFT_SPDesignerSettings.psm1 @@ -407,9 +407,13 @@ function Test-TargetResource ) Write-Verbose -Message "Testing SharePoint Designer configuration settings" + $CurrentValues = Get-TargetResource @PSBoundParameters - if ($null -eq $CurrentValues) { return $false } + if ($null -eq $CurrentValues) + { + return $false + } return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPDiagnosticLoggingSettings/MSFT_SPDiagnosticLoggingSettings.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPDiagnosticLoggingSettings/MSFT_SPDiagnosticLoggingSettings.psm1 index 1c497768b..a4eb386d9 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPDiagnosticLoggingSettings/MSFT_SPDiagnosticLoggingSettings.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPDiagnosticLoggingSettings/MSFT_SPDiagnosticLoggingSettings.psm1 @@ -306,11 +306,14 @@ function Test-TargetResource ) Write-Verbose -Message "Testing diagnostic configuration settings" + $CurrentValues = Get-TargetResource @PSBoundParameters + if ($null -eq $CurrentValues) { return $false } + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters } diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPDistributedCacheService/MSFT_SPDistributedCacheService.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPDistributedCacheService/MSFT_SPDistributedCacheService.psm1 index 7ee6f6282..d670c8693 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPDistributedCacheService/MSFT_SPDistributedCacheService.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPDistributedCacheService/MSFT_SPDistributedCacheService.psm1 @@ -20,16 +20,16 @@ function Get-TargetResource [System.Boolean] $CreateFirewallRules, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.String[]] $ServerProvisionOrder, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount ) @@ -63,7 +63,7 @@ function Get-TargetResource -CachePort $cachePort ` -ErrorAction SilentlyContinue - $windowsService = Get-WmiObject "win32_service" -Filter "Name='AppFabricCachingService'" + $windowsService = Get-CimInstance -Class Win32_Service -Filter "Name='AppFabricCachingService'" $firewallRule = Get-NetFirewallRule -DisplayName "SharePoint Distributed Cache" ` -ErrorAction SilentlyContinue @@ -107,20 +107,22 @@ function Set-TargetResource [System.Boolean] $CreateFirewallRules, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.String[]] $ServerProvisionOrder, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount ) + Write-Verbose -Message "Setting the cache host information" + $CurrentState = Get-TargetResource @PSBoundParameters if ($Ensure -eq "Present") @@ -186,7 +188,7 @@ function Set-TargetResource # name, or if we need to use the FQDN $si = Get-SPServiceInstance -Server $currentServer ` | Where-Object -FilterScript { - $_.TypeName -eq "Distributed Cache" + $_.GetType().Name -eq "SPDistributedCacheServiceInstance" } if ($null -eq $si) @@ -198,7 +200,8 @@ function Set-TargetResource Write-Verbose "Waiting for cache on $currentServer" $serviceCheck = Get-SPServiceInstance -Server $currentServer ` | Where-Object -FilterScript { - $_.TypeName -eq "Distributed Cache" -and $_.Status -eq "Online" + $_.GetType().Name -eq "SPDistributedCacheServiceInstance" -and ` + $_.Status -eq "Online" } while (($count -lt $maxCount) -and ($null -eq $serviceCheck)) { @@ -209,14 +212,15 @@ function Set-TargetResource Start-Sleep -Seconds 60 $serviceCheck = Get-SPServiceInstance -Server $currentServer ` | Where-Object -FilterScript { - $_.TypeName -eq "Distributed Cache" -and $_.Status -eq "Online" + $_.GetType().Name -eq "SPDistributedCacheServiceInstance" -and ` + $_.Status -eq "Online" } $count++ } $serviceCheck = Get-SPServiceInstance -Server $currentServer ` | Where-Object -FilterScript { - $_.TypeName -eq "Distributed Cache" ` + $_.GetType().Name -eq "SPDistributedCacheServiceInstance" ` -and $_.Status -eq "Online" } @@ -243,14 +247,15 @@ function Set-TargetResource Add-SPDistributedCacheServiceInstance Get-SPServiceInstance | Where-Object -FilterScript { - $_.TypeName -eq "Distributed Cache" + $_.GetType().Name -eq "SPDistributedCacheServiceInstance" } | Stop-SPServiceInstance -Confirm:$false $count = 0 $maxCount = 30 $serviceCheck = Get-SPServiceInstance | Where-Object -FilterScript { - $_.TypeName -eq "Distributed Cache" -and $_.Status -ne "Disabled" + $_.GetType().Name -eq "SPDistributedCacheServiceInstance" -and ` + $_.Status -ne "Disabled" } while (($count -lt $maxCount) -and ($null -ne $serviceCheck)) { @@ -259,7 +264,8 @@ function Set-TargetResource "(waited $count of $maxCount minutes)") Start-Sleep -Seconds 60 $serviceCheck = Get-SPServiceInstance | Where-Object -FilterScript { - $_.TypeName -eq "Distributed Cache" -and $_.Status -ne "Disabled" + $_.GetType().Name -eq "SPDistributedCacheServiceInstance" -and ` + $_.Status -ne "Disabled" } $count++ } @@ -267,14 +273,15 @@ function Set-TargetResource Update-SPDistributedCacheSize -CacheSizeInMB $params.CacheSizeInMB Get-SPServiceInstance | Where-Object -FilterScript { - $_.TypeName -eq "Distributed Cache" + $_.GetType().Name -eq "SPDistributedCacheServiceInstance" } | Start-SPServiceInstance $count = 0 $maxCount = 30 $serviceCheck = Get-SPServiceInstance | Where-Object -FilterScript { - $_.TypeName -eq "Distributed Cache" -and $_.Status -ne "Online" + $_.GetType().Name -eq "SPDistributedCacheServiceInstance" -and ` + $_.Status -ne "Online" } while (($count -lt $maxCount) -and ($null -ne $serviceCheck)) { @@ -283,7 +290,8 @@ function Set-TargetResource "(waited $count of $maxCount minutes)") Start-Sleep -Seconds 60 $serviceCheck = Get-SPServiceInstance | Where-Object -FilterScript { - $_.TypeName -eq "Distributed Cache" -and $_.Status -ne "Online" + $_.GetType().Name -eq "SPDistributedCacheServiceInstance" -and ` + $_.Status -ne "Online" } $count++ } @@ -310,7 +318,7 @@ function Set-TargetResource Invoke-SPDSCCommand -Credential $InstallAccount -ScriptBlock { $serviceInstance = Get-SPServiceInstance -Server $env:computername ` | Where-Object -FilterScript { - $_.TypeName -eq "Distributed Cache" + $_.GetType().Name -eq "SPDistributedCacheServiceInstance" } if ($null -eq $serviceInstance) @@ -319,7 +327,7 @@ function Set-TargetResource $currentServer = "$($env:computername).$domain" $serviceInstance = Get-SPServiceInstance -Server $currentServer ` | Where-Object -FilterScript { - $_.TypeName -eq "Distributed Cache" + $_.GetType().Name -eq "SPDistributedCacheServiceInstance" } } if ($null -eq $serviceInstance) @@ -369,28 +377,29 @@ function Test-TargetResource [System.Boolean] $CreateFirewallRules, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.String[]] $ServerProvisionOrder, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters + Write-Verbose -Message "Testing the cache host information" + $PSBoundParameters.Ensure = $Ensure - Write-Verbose -Message "Testing for distributed cache configuration" + + $CurrentValues = Get-TargetResource @PSBoundParameters + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("Ensure", "CreateFirewallRules") } - Export-ModuleMember -Function *-TargetResource - diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPExcelServiceApp/MSFT_SPExcelServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPExcelServiceApp/MSFT_SPExcelServiceApp.psm1 index 955ac4adb..63abb389e 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPExcelServiceApp/MSFT_SPExcelServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPExcelServiceApp/MSFT_SPExcelServiceApp.psm1 @@ -1,3 +1,29 @@ +$Script:TrustLocationProperties = @( + "Address", + "LocationType", + "IncludeChildren", + "SessionTimeout", + "ShortSessionTimeout", + "NewWorkbookSessionTimeout", + "RequestDurationMax", + "ChartRenderDurationMax", + "WorkbookSizeMax", + "ChartAndImageSizeMax", + "AutomaticVolatileFunctionCacheLifetime", + "DefaultWorkbookCalcMode", + "ExternalDataAllowed", + "WarnOnDataRefresh", + "DisplayGranularExtDataErrors", + "AbortOnRefreshOnOpenFail", + "PeriodicExtDataCacheLifetime", + "ManualExtDataCacheLifetime", + "ConcurrentDataRequestsPerSessionMax", + "UdfsAllowed", + "Description", + "RESTExternalDataAllowed" +) +$Script:ServiceAppObjectType = "Microsoft.Office.Excel.Server.MossHost.ExcelServerWebServiceApplication" + function Get-TargetResource { [CmdletBinding()] @@ -11,6 +37,77 @@ function Get-TargetResource [System.String] $ApplicationPool, + [parameter(Mandatory = $false)] + [Microsoft.Management.Infrastructure.CimInstance[]] + $TrustedFileLocations, + + [parameter(Mandatory = $false)] + [System.Boolean] + $CachingOfUnusedFilesEnable, + + [parameter(Mandatory = $false)] + [System.Boolean] + $CrossDomainAccessAllowed, + + [parameter(Mandatory = $false)] + [ValidateSet("None","Connection")] + [System.String] + $EncryptedUserConnectionRequired, + + [parameter(Mandatory = $false)] + [System.UInt32] + $ExternalDataConnectionLifetime, + + [parameter(Mandatory = $false)] + [ValidateSet("UseImpersonation","UseFileAccessAccount")] + [System.String] + $FileAccessMethod, + + [parameter(Mandatory = $false)] + [ValidateSet("RoundRobin","Local","WorkbookURL")] + [System.String] + $LoadBalancingScheme, + + [parameter(Mandatory = $false)] + [System.UInt32] + $MemoryCacheThreshold, + + [parameter(Mandatory = $false)] + [System.UInt32] + $PrivateBytesMax, + + [parameter(Mandatory = $false)] + [System.UInt32] + $SessionsPerUserMax, + + [parameter(Mandatory = $false)] + [System.UInt32] + $SiteCollectionAnonymousSessionsMax, + + [parameter(Mandatory = $false)] + [System.Boolean] + $TerminateProcessOnAccessViolation, + + [parameter(Mandatory = $false)] + [System.UInt32] + $ThrottleAccessViolationsPerSiteCollection, + + [parameter(Mandatory = $false)] + [System.String] + $UnattendedAccountApplicationId, + + [parameter(Mandatory = $false)] + [System.UInt32] + $UnusedObjectAgeMax, + + [parameter(Mandatory = $false)] + [System.String] + $WorkbookCache, + + [parameter(Mandatory = $false)] + [System.UInt32] + $WorkbookCacheSizeMax, + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] @@ -21,6 +118,8 @@ function Get-TargetResource $InstallAccount ) + Write-Verbose -Message "Getting Excel Services Application '$Name'" + if ((Get-SPDSCInstalledProductVersion).FileMajorPart -ne 15) { throw [Exception] "Only SharePoint 2013 is supported to deploy Excel Services " + ` @@ -30,12 +129,11 @@ function Get-TargetResource "for more info." } - Write-Verbose -Message "Getting Excel Services service app '$Name'" - $result = Invoke-SPDSCCommand -Credential $InstallAccount ` - -Arguments $PSBoundParameters ` + -Arguments @($PSBoundParameters, $Script:ServiceAppObjectType) ` -ScriptBlock { $params = $args[0] + $serviceAppObjectType = $args[1] $serviceApps = Get-SPServiceApplication -Name $params.Name ` -ErrorAction SilentlyContinue @@ -50,7 +148,7 @@ function Get-TargetResource return $nullReturn } $serviceApp = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "Excel Services Application Web Service Application" + $_.GetType().FullName -eq $serviceAppObjectType } if ($null -eq $serviceApp) @@ -59,10 +157,56 @@ function Get-TargetResource } else { + $fileLocations = Get-SPExcelFileLocation -ExcelServiceApplication $serviceApp + $fileLocationsToReturn = @() + $fileLocations | ForEach-Object -Process { + $fileLocationsToReturn += @{ + Address = $_.Address + LocationType = $_.LocationType + IncludeChildren = [Convert]::ToBoolean($_.IncludeChildren) + SessionTimeout = $_.SessionTimeout + ShortSessionTimeout = $_.ShortSessionTimeout + NewWorkbookSessionTimeout = $_.NewWorkbookSessionTimeout + RequestDurationMax = $_.RequestDurationMax + ChartRenderDurationMax = $_.ChartRenderDurationMax + WorkbookSizeMax = $_.WorkbookSizeMax + ChartAndImageSizeMax = $_.ChartAndImageSizeMax + AutomaticVolatileFunctionCacheLifetime = $_.AutomaticVolatileFunctionCacheLifetime + DefaultWorkbookCalcMode = $_.DefaultWorkbookCalcMode + ExternalDataAllowed = $_.ExternalDataAllowed + WarnOnDataRefresh = [Convert]::ToBoolean($_.WarnOnDataRefresh) + DisplayGranularExtDataErrors = [Convert]::ToBoolean($_.DisplayGranularExtDataErrors) + AbortOnRefreshOnOpenFail = [Convert]::ToBoolean($_.AbortOnRefreshOnOpenFail) + PeriodicExtDataCacheLifetime = $_.PeriodicExtDataCacheLifetime + ManualExtDataCacheLifetime = $_.ManualExtDataCacheLifetime + ConcurrentDataRequestsPerSessionMax = $_.ConcurrentDataRequestsPerSessionMax + UdfsAllowed = [Convert]::ToBoolean($_.UdfsAllowed) + Description = $_.Description + RESTExternalDataAllowed = [Convert]::ToBoolean($_.RESTExternalDataAllowed) + } + } + $returnVal = @{ Name = $serviceApp.DisplayName ApplicationPool = $serviceApp.ApplicationPool.Name Ensure = "Present" + TrustedFileLocations = $fileLocationsToReturn + CachingOfUnusedFilesEnable = $serviceApp.CachingOfUnusedFilesEnable + CrossDomainAccessAllowed = $serviceApp.CrossDomainAccessAllowed + EncryptedUserConnectionRequired = $serviceApp.EncryptedUserConnectionRequired + ExternalDataConnectionLifetime = $serviceApp.ExternalDataConnectionLifetime + FileAccessMethod = $serviceApp.FileAccessMethod + LoadBalancingScheme = $serviceApp.LoadBalancingScheme + MemoryCacheThreshold = $serviceApp.MemoryCacheThreshold + PrivateBytesMax = $serviceApp.PrivateBytesMax + SessionsPerUserMax = $serviceApp.SessionsPerUserMax + SiteCollectionAnonymousSessionsMax = $serviceApp.SiteCollectionAnonymousSessionsMax + TerminateProcessOnAccessViolation = $serviceApp.TerminateProcessOnAccessViolation + ThrottleAccessViolationsPerSiteCollection = $serviceApp.ThrottleAccessViolationsPerSiteCollection + UnattendedAccountApplicationId = $serviceApp.UnattendedAccountApplicationId + UnusedObjectAgeMax = $serviceApp.UnusedObjectAgeMax + WorkbookCache = $serviceApp.WorkbookCache + WorkbookCacheSizeMax = $serviceApp.WorkbookCacheSizeMax InstallAccount = $params.InstallAccount } return $returnVal @@ -84,6 +228,77 @@ function Set-TargetResource [System.String] $ApplicationPool, + [parameter(Mandatory = $false)] + [Microsoft.Management.Infrastructure.CimInstance[]] + $TrustedFileLocations, + + [parameter(Mandatory = $false)] + [System.Boolean] + $CachingOfUnusedFilesEnable, + + [parameter(Mandatory = $false)] + [System.Boolean] + $CrossDomainAccessAllowed, + + [parameter(Mandatory = $false)] + [ValidateSet("None","Connection")] + [System.String] + $EncryptedUserConnectionRequired, + + [parameter(Mandatory = $false)] + [System.UInt32] + $ExternalDataConnectionLifetime, + + [parameter(Mandatory = $false)] + [ValidateSet("UseImpersonation","UseFileAccessAccount")] + [System.String] + $FileAccessMethod, + + [parameter(Mandatory = $false)] + [ValidateSet("RoundRobin","Local","WorkbookURL")] + [System.String] + $LoadBalancingScheme, + + [parameter(Mandatory = $false)] + [System.UInt32] + $MemoryCacheThreshold, + + [parameter(Mandatory = $false)] + [System.UInt32] + $PrivateBytesMax, + + [parameter(Mandatory = $false)] + [System.UInt32] + $SessionsPerUserMax, + + [parameter(Mandatory = $false)] + [System.UInt32] + $SiteCollectionAnonymousSessionsMax, + + [parameter(Mandatory = $false)] + [System.Boolean] + $TerminateProcessOnAccessViolation, + + [parameter(Mandatory = $false)] + [System.UInt32] + $ThrottleAccessViolationsPerSiteCollection, + + [parameter(Mandatory = $false)] + [System.String] + $UnattendedAccountApplicationId, + + [parameter(Mandatory = $false)] + [System.UInt32] + $UnusedObjectAgeMax, + + [parameter(Mandatory = $false)] + [System.String] + $WorkbookCache, + + [parameter(Mandatory = $false)] + [System.UInt32] + $WorkbookCacheSizeMax, + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] @@ -94,6 +309,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting Excel Services Application '$Name'" + if ((Get-SPDSCInstalledProductVersion).FileMajorPart -ne 15) { throw [Exception] "Only SharePoint 2013 is supported to deploy Excel Services " + ` @@ -116,18 +333,138 @@ function Set-TargetResource -ApplicationPool $params.ApplicationPool } } + + if ($Ensure -eq "Present") + { + Write-Verbose -Message "Updating settings for Excel Services Application $Name" + Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments $PSBoundParameters ` + -ScriptBlock { + $params = $args[0] + + $params.Add("Identity", $params.Name) + + # Remove parameters that do not belong on the set method + @("InstallAccount", "Ensure", "TrustedFileLocations", "Name", "ApplicationPool") | + ForEach-Object -Process { + if ($params.ContainsKey($_) -eq $true) + { + $params.Remove($_) | Out-Null + } + } + + Set-SPExcelServiceApplication @params + } + + + # Update trusted locations + if ($null -ne $TrustedFileLocations) + { + $TrustedFileLocations | ForEach-Object -Process { + $desiredLocation = $_ + $matchingCurrentValue = $result.TrustedFileLocations | Where-Object -FilterScript { + $_.Address -eq $desiredLocation.Address + } + if ($null -eq $matchingCurrentValue) + { + Write-Verbose -Message "Adding trusted location '$($desiredLocation.Address)' to service app" + Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments @($PSBoundParameters, $desiredLocation, $Script:TrustLocationProperties, $Script:ServiceAppObjectType) ` + -ScriptBlock { + $params = $args[0] + $desiredLocation = $args[1] + $trustLocationProperties = $args[2] + $serviceAppObjectType = $args[3] + + $newArgs = @{} + $trustLocationProperties | ForEach-Object -Process { + if ($null -ne $desiredLocation.$_) + { + $newArgs.Add($_, $desiredLocation.$_) + } + } + $serviceApp = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { + $_.GetType().FullName -eq $serviceAppObjectType + } + $newArgs.Add("ExcelServiceApplication", $serviceApp) + + New-SPExcelFileLocation @newArgs + } + } + else + { + Write-Verbose -Message "Updating trusted location '$($desiredLocation.Address)' in service app" + Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments @($PSBoundParameters, $desiredLocation, $Script:TrustLocationProperties, $Script:ServiceAppObjectType) ` + -ScriptBlock { + $params = $args[0] + $desiredLocation = $args[1] + $trustLocationProperties = $args[2] + $serviceAppObjectType = $args[3] + + $updateArgs = @{} + $trustLocationProperties | ForEach-Object -Process { + if ($null -ne $desiredLocation.$_) + { + $updateArgs.Add($_, $desiredLocation.$_) + } + } + $serviceApp = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { + $_.GetType().FullName -eq $serviceAppObjectType + } + $updateArgs.Add("Identity", $desiredLocation.Address) + $updateArgs.Add("ExcelServiceApplication", $serviceApp) + + Set-SPExcelFileLocation @updateArgs + } + } + } + + # Remove unlisted trusted locations + $result.TrustedFileLocations | ForEach-Object -Process { + $currentLocation = $_ + $matchingDesiredValue = $TrustedFileLocations | Where-Object -FilterScript { + $_.Address -eq $currentLocation.Address + } + if ($null -eq $matchingDesiredValue) + { + Write-Verbose -Message "Removing trusted location '$($currentLocation.Address)' from service app" + Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments @($Name, $currentLocation) ` + -ScriptBlock { + $name = $args[0] + $currentLocation = $args[1] + + Remove-SPExcelFileLocation -ExcelServiceApplication $name -Identity $currentLocation.Address -Confirm:$false + } + } + } + } + } + if ($Ensure -eq "Absent") { Write-Verbose -Message "Removing Excel Service Application $Name" Invoke-SPDSCCommand -Credential $InstallAccount ` - -Arguments $PSBoundParameters ` + -Arguments @($PSBoundParameters, $Script:ServiceAppObjectType) ` -ScriptBlock { $params = $args[0] - - $appService = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { - $_.TypeName -eq "Excel Services Application Web Service Application" + $serviceAppObjectType = $args[1] + + $serviceApp = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { + $_.GetType().FullName -eq $serviceAppObjectType + } + + $proxies = Get-SPServiceApplicationProxy + foreach($proxyInstance in $proxies) + { + if($serviceApp.IsConnected($proxyInstance)) + { + $proxyInstance.Delete() + } } - Remove-SPServiceApplication $appService -Confirm:$false + + Remove-SPServiceApplication -Identity $serviceApp -Confirm:$false } } } @@ -146,6 +483,77 @@ function Test-TargetResource [System.String] $ApplicationPool, + [parameter(Mandatory = $false)] + [Microsoft.Management.Infrastructure.CimInstance[]] + $TrustedFileLocations, + + [parameter(Mandatory = $false)] + [System.Boolean] + $CachingOfUnusedFilesEnable, + + [parameter(Mandatory = $false)] + [System.Boolean] + $CrossDomainAccessAllowed, + + [parameter(Mandatory = $false)] + [ValidateSet("None","Connection")] + [System.String] + $EncryptedUserConnectionRequired, + + [parameter(Mandatory = $false)] + [System.UInt32] + $ExternalDataConnectionLifetime, + + [parameter(Mandatory = $false)] + [ValidateSet("UseImpersonation","UseFileAccessAccount")] + [System.String] + $FileAccessMethod, + + [parameter(Mandatory = $false)] + [ValidateSet("RoundRobin","Local","WorkbookURL")] + [System.String] + $LoadBalancingScheme, + + [parameter(Mandatory = $false)] + [System.UInt32] + $MemoryCacheThreshold, + + [parameter(Mandatory = $false)] + [System.UInt32] + $PrivateBytesMax, + + [parameter(Mandatory = $false)] + [System.UInt32] + $SessionsPerUserMax, + + [parameter(Mandatory = $false)] + [System.UInt32] + $SiteCollectionAnonymousSessionsMax, + + [parameter(Mandatory = $false)] + [System.Boolean] + $TerminateProcessOnAccessViolation, + + [parameter(Mandatory = $false)] + [System.UInt32] + $ThrottleAccessViolationsPerSiteCollection, + + [parameter(Mandatory = $false)] + [System.String] + $UnattendedAccountApplicationId, + + [parameter(Mandatory = $false)] + [System.UInt32] + $UnusedObjectAgeMax, + + [parameter(Mandatory = $false)] + [System.String] + $WorkbookCache, + + [parameter(Mandatory = $false)] + [System.UInt32] + $WorkbookCacheSizeMax, + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] @@ -156,6 +564,10 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing Excel Services Application '$Name'" + + $PSBoundParameters.Ensure = $Ensure + if ((Get-SPDSCInstalledProductVersion).FileMajorPart -ne 15) { throw [Exception] "Only SharePoint 2013 is supported to deploy Excel Services " + ` @@ -165,12 +577,96 @@ function Test-TargetResource "for more info." } - $PSBoundParameters.Ensure = $Ensure - Write-Verbose -Message "Testing for Excel Services Application '$Name'" $CurrentValues = Get-TargetResource @PSBoundParameters - return Test-SPDscParameterState -CurrentValues $CurrentValues ` - -DesiredValues $PSBoundParameters ` - -ValuesToCheck @("Ensure") + + $mainCheck = Test-SPDscParameterState -CurrentValues $CurrentValues ` + -DesiredValues $PSBoundParameters ` + -ValuesToCheck @( + "Ensure", + "CachingOfUnusedFilesEnable", + "CrossDomainAccessAllowed", + "EncryptedUserConnectionRequired", + "ExternalDataConnectionLifetime", + "FileAccessMethod", + "LoadBalancingScheme", + "MemoryCacheThreshold", + "PrivateBytesMax", + "SessionsPerUserMax", + "SiteCollectionAnonymousSessionsMax", + "TerminateProcessOnAccessViolation", + "ThrottleAccessViolationsPerSiteCollection", + "UnattendedAccountApplicationId", + "UnusedObjectAgeMax", + "WorkbookCache", + "WorkbookCacheSizeMax" + ) + + + if ($Ensure -eq "Present" -and $mainCheck -eq $true -and $null -ne $TrustedFileLocations) + { + # Check that all the desired types are in the current values and match + $locationCheck = $TrustedFileLocations | ForEach-Object -Process { + $desiredLocation = $_ + $matchingCurrentValue = $CurrentValues.TrustedFileLocations | Where-Object -FilterScript { + $_.Address -eq $desiredLocation.Address + } + if ($null -eq $matchingCurrentValue) + { + Write-Verbose -Message ("Trusted file location '$($_.Address)' was not found " + ` + "in the Excel service app. Desired state is false.") + return $false + } + else + { + $Script:TrustLocationProperties | ForEach-Object -Process { + if ($desiredLocation.CimInstanceProperties.Name -contains $_) + { + if ($desiredLocation.$_ -ne $matchingCurrentValue.$_) + { + Write-Verbose -Message ("Trusted file location '$($desiredLocation.Address)' did not match " + ` + "desired property '$_'. Desired value is " + ` + "'$($desiredLocation.$_)' but the current value is " + ` + "'$($matchingCurrentValue.$_)'") + return $false + } + } + } + } + return $true + } + if ($locationCheck -contains $false) + { + return $false + } + + # Check that any other existing trusted locations are in the desired state + $locationCheck = $CurrentValues.TrustedFileLocations | ForEach-Object -Process { + $currentLocation = $_ + $matchingDesiredValue = $TrustedFileLocations | Where-Object -FilterScript { + $_.Address -eq $currentLocation.Address + } + if ($null -eq $matchingDesiredValue) + { + Write-Verbose -Message ("Existing trusted file location '$($_.Address)' was not " + ` + "found in the desired state for this service " + ` + "application. Desired state is false.") + return $false + } + return $true + } + if ($locationCheck -contains $false) + { + return $false + } + + # at this point if no other value has been returned, all desired entires exist and are + # correct, and no existing entries exist that are not in desired state, so return true + return $true + } + else + { + return $mainCheck + } } Export-ModuleMember -Function *-TargetResource diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPExcelServiceApp/MSFT_SPExcelServiceApp.schema.mof b/Modules/SharePointDsc/DSCResources/MSFT_SPExcelServiceApp/MSFT_SPExcelServiceApp.schema.mof index d5bfeed87..371736fc2 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPExcelServiceApp/MSFT_SPExcelServiceApp.schema.mof +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPExcelServiceApp/MSFT_SPExcelServiceApp.schema.mof @@ -1,8 +1,50 @@ +[ClassVersion("1.0.0.0")] +Class MSFT_SPExcelFileLocation +{ + [Key, Description("The address of the file location")] String Address; + [Required, Description("The type of the trusted file location"), ValueMap{"SharePoint","UNC", "HTTP"}, Values{"SharePoint","UNC", "HTTP"}] String LocationType; + [Write, Description("Specifies that the loading of a Excel Services Application file automatically fails if an automatic data refresh operation fails when the file is opened.")] Boolean AbortOnRefreshOnOpenFail; + [Write, Description("Specifies the maximum time, in seconds, that a computed value for a volatile function is cached for automatic recalculations.")] Uint32 AutomaticVolatileFunctionCacheLifetime; + [Write, Description("Specifies the maximum size, in megabytes, of a chart or image that can be opened.")] Uint32 ChartAndImageSizeMax; + [Write, Description("Specifies the maximum number of concurrent external data requests allowed in each session.")] Uint32 ConcurrentDataRequestsPerSessionMax; + [Write, Description("Specifies the calculation mode of workbooks."), ValueMap{"File","Manual", "Auto", "AutoDataTables"}, Values{"File","Manual", "Auto", "AutoDataTables"}] String DefaultWorkbookCalcMode; + [Write, Description("Specifies a friendly description for the new file location.")] String Description; + [Write, Description("Displays granular error messages for external data failures for files in this location.")] Boolean DisplayGranularExtDataErrors; + [Write, Description("Specifies the type of external data access allowed for workbooks."), ValueMap{"None","Dcl", "DclandEmbedded"}, Values{"None","Dcl", "DclandEmbedded"}] String ExternalDataAllowed; + [Write, Description("Indicates that subordinate URLs, directories and libraries are trusted.")] Boolean IncludeChildren; + [Write, Description("Specifies the time, in seconds, that Excel Services Application waits before it re-issues a manual, or user-initiated, external data request.")] Uint32 ManualExtDataCacheLifetime; + [Write, Description("Specifies the time, in seconds, that a session for a new, unsaved, workbook remains active on Excel Services Application with no user activity.")] Uint32 NewWorkbookSessionTimeout; + [Write, Description("Specifies the time, in seconds, that Excel Services Application waits before it re-issues an on-open or periodic (that is, automatic) external data request.")] Uint32 PeriodicExtDataCacheLifetime; + [Write, Description("Specifies the maximum duration, in seconds, for a single request in a session.")] Uint32 RequestDurationMax; + [Write, Description("Specifies whether requests from the Representational State Transfer (REST) Application Programming Interface (API) are permitted to refresh external data connections.")] Boolean RESTExternalDataAllowed; + [Write, Description("Specifies the time, in seconds, that a session remains active on Excel Services Application with no user activity.")] Uint32 SessionTimeout; + [Write, Description("Specifies the time, in seconds, that a user has to make the initial interaction with a spreadsheet.")] Uint32 ShortSessionTimeout; + [Write, Description("Specifies that user-defined functions can be called by workbooks that are loaded from the trusted file location that is specified in Address.")] Boolean UdfsAllowed; + [Write, Description("Specifies that a warning is displayed to the user on the first refresh of data for the workbook.")] Boolean WarnOnDataRefresh; + [Write, Description("Specifies the maximum size, in megabytes, of a workbook that can be loaded.")] Uint32 WorkbookSizeMax; +}; [ClassVersion("1.0.0.0"), FriendlyName("SPExcelServiceApp")] class MSFT_SPExcelServiceApp : OMI_BaseResource { [Key, Description("The name of the service application")] string Name; [Required, Description("The name of the application pool to run the service app in")] string ApplicationPool; + [Write, Description("Trusted file locations for the service app"), EmbeddedInstance("MSFT_SPExcelFileLocation")] string TrustedFileLocations[]; + [Write, Description("Specifies that files that are no longer used by Excel Services Application can remain in the cache for later use.")] Boolean CachingOfUnusedFilesEnable; + [Write, Description("Specifies that trusted workbooks and data connection files can be requested and rendered by Web Parts or pages that reside in other HTTP domains.")] Boolean CrossDomainAccessAllowed; + [Write, Description("Requires that encryption is used between the end-user and the server running Excel Services Application."), ValueMap{"None","Connection"}, Values{"None","Connection"}] String EncryptedUserConnectionRequired; + [Write, Description("Specifies the maximum number of seconds that an external data connection can remain open in the connection pool.")] Uint32 ExternalDataConnectionLifetime; + [Write, Description("Specifies the authentication method that Excel Services Application uses to retrieve files."), ValueMap{"UseImpersonation","UseFileAccessAccount"}, Values{"UseImpersonation","UseFileAccessAccount"}] String FileAccessMethod; + [Write, Description("Specifies the load-balancing schema that is used by the Excel Services Application Web service application to send requests to different back-end Excel Services Application computers."), ValueMap{"RoundRobin","Local","WorkbookURL"}, Values{"RoundRobin","Local","WorkbookURL"}] String LoadBalancingScheme; + [Write, Description("Specifies the percentage of the maximum private bytes that can be allocated to inactive objects.")] Uint32 MemoryCacheThreshold; + [Write, Description("Specifies the maximum private bytes, in megabytes, that are used by Excel Services Application.")] Uint32 PrivateBytesMax; + [Write, Description("Specifies the maximum number of sessions allowed for a user.")] Uint32 SessionsPerUserMax; + [Write, Description("Specifies the maximum number of anonymous sessions allowed per site collection.")] Uint32 SiteCollectionAnonymousSessionsMax; + [Write, Description("Terminates Excel Services Application when an access violation occurs in the process.")] Boolean TerminateProcessOnAccessViolation; + [Write, Description("Specifies that if a workbook causes an access violation error on Excel Services Application, all files originating from that workbook’s site collection are blocked from loading for the specified period (in seconds).")] Uint32 ThrottleAccessViolationsPerSiteCollection; + [Write, Description("Specifies that the application ID that is used to look up the unattended service account credentials from the secure storage service that is specified by the UnattendedAccountSecureServiceAppName parameter.")] String UnattendedAccountApplicationId; + [Write, Description("Specifies the maximum amount of time, in minutes, that objects not currently used in a session are kept in the memory cache.")] Uint32 UnusedObjectAgeMax; + [Write, Description("Specifies the local file system location of the cache that is used to store workbooks that are used by Excel Services Application.")] String WorkbookCache; + [Write, Description("Specifies the maximum allowable size, in megabytes, of an individual session.")] Uint32 WorkbookCacheSizeMax; [Write, Description("Present ensures service app exists, absent ensures it is removed"), ValueMap{"Present","Absent"}, Values{"Present","Absent"}] string Ensure; [Write, Description("POWERSHELL 4 ONLY: The account to run this resource as, use PsDscRunAsCredential if using PowerShell 5"), EmbeddedInstance("MSFT_Credential")] String InstallAccount; }; diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPFarmAdministrators/MSFT_SPFarmAdministrators.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPFarmAdministrators/MSFT_SPFarmAdministrators.psm1 index 09f6802c0..57e81b4ad 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPFarmAdministrators/MSFT_SPFarmAdministrators.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPFarmAdministrators/MSFT_SPFarmAdministrators.psm1 @@ -25,6 +25,8 @@ function Get-TargetResource $InstallAccount ) + Write-Verbose -Message "Getting Farm Administrators configuration" + if ($Members -and (($MembersToInclude) -or ($MembersToExclude))) { throw ("Cannot use the Members parameter together with the " + ` @@ -37,8 +39,6 @@ function Get-TargetResource "Members, MembersToInclude, MembersToExclude") } - Write-Verbose -Message "Getting all Farm Administrators" - $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { @@ -95,7 +95,7 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Setting Farm Administrator config" + Write-Verbose -Message "Setting Farm Administrators configuration" if ($Members -and (($MembersToInclude) -or ($MembersToExclude))) { @@ -253,7 +253,7 @@ function Test-TargetResource $InstallAccount ) - Write-Verbose -Message "Testing Farm Administrator settings" + Write-Verbose -Message "Testing Farm Administrators configuration" if ($Members -and (($MembersToInclude) -or ($MembersToExclude))) { @@ -370,4 +370,3 @@ function Merge-SPDscFarmAdminList } Export-ModuleMember -Function *-TargetResource - diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPFarmSolution/MSFT_SPFarmSolution.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPFarmSolution/MSFT_SPFarmSolution.psm1 index 9fa9f52ac..4c4d255dd 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPFarmSolution/MSFT_SPFarmSolution.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPFarmSolution/MSFT_SPFarmSolution.psm1 @@ -39,7 +39,7 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Getting farm solution '$Name'..." + Write-Verbose -Message "Getting farm solution '$Name' settings" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -122,6 +122,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting farm solution '$Name' settings" + $CurrentValues = Get-TargetResource @PSBoundParameters $PSBoundParameters.Ensure = $Ensure @@ -378,11 +380,12 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing solution $Name" + Write-Verbose -Message "Testing farm solution '$Name' settings" $PSBoundParameters.Ensure = $Ensure + $CurrentValues = Get-TargetResource @PSBoundParameters + $valuesToCheck = @("Ensure", "Version", "Deployed") if ($WebApplications.Count -gt 0) { diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPFeature/MSFT_SPFeature.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPFeature/MSFT_SPFeature.psm1 index 2dfbb49fd..41b753b9b 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPFeature/MSFT_SPFeature.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPFeature/MSFT_SPFeature.psm1 @@ -105,6 +105,8 @@ function Set-TargetResource $Version ) + Write-Verbose -Message "Setting feature $Name at $FeatureScope scope" + $CurrentValues = Get-TargetResource @PSBoundParameters $PSBoundParameters.Add("CurrentValues", $CurrentValues) @@ -201,11 +203,12 @@ function Test-TargetResource $Version ) - $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing for feature $Name at $FeatureScope scope" + Write-Verbose -Message "Testing feature $Name at $FeatureScope scope" $PSBoundParameters.Ensure = $Ensure + $CurrentValues = Get-TargetResource @PSBoundParameters + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("Ensure", "Version") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPHealthAnalyzerRuleState/MSFT_SPHealthAnalyzerRuleState.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPHealthAnalyzerRuleState/MSFT_SPHealthAnalyzerRuleState.psm1 index a2aceea8c..3f38c54f3 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPHealthAnalyzerRuleState/MSFT_SPHealthAnalyzerRuleState.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPHealthAnalyzerRuleState/MSFT_SPHealthAnalyzerRuleState.psm1 @@ -249,9 +249,13 @@ function Test-TargetResource ) Write-Verbose -Message "Testing Health Analyzer rule configuration settings" + $CurrentValues = Get-TargetResource @PSBoundParameters - if ($null -eq $CurrentValues) { return $false } + if ($null -eq $CurrentValues) + { + return $false + } return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPInstall/MSFT_SPInstall.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPInstall/MSFT_SPInstall.psm1 index 3f154e510..9ccd7d5ac 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPInstall/MSFT_SPInstall.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPInstall/MSFT_SPInstall.psm1 @@ -26,7 +26,8 @@ function Get-TargetResource $Ensure = "Present" ) - Write-Verbose -Message "Getting install status of SP binaries" + Write-Verbose -Message "Getting install status of SharePoint" + $x86Path = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" $installedItemsX86 = Get-ItemProperty -Path $x86Path | Select-Object -Property DisplayName @@ -89,6 +90,8 @@ function Set-TargetResource $Ensure = "Present" ) + Write-Verbose -Message "Setting install status of SharePoint" + if ($Ensure -eq "Absent") { throw [Exception] ("SharePointDsc does not support uninstalling SharePoint or " + ` @@ -100,18 +103,43 @@ function Set-TargetResource $majorVersion = (Get-SPDSCAssemblyVersion -PathToAssembly $InstallerPath) if ($majorVersion -eq 15) { - $ndp = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' - $dotNet46Check = $ndp | Get-ItemProperty -name Version,Release -EA 0 ` - | Where-Object -FilterScript { - $_.PSChildName -match '^(?!S)\p{L}' -and $_.Version -like "4.6.*" - } - if ($null -ne $dotNet46Check -and $dotNet46Check.Length -gt 0) + $svrsetupDll = Join-Path -Path $BinaryDir -ChildPath "updates\svrsetup.dll" + $checkDotNet = $true + if (Test-Path -Path $svrsetupDll) + { + $svrsetupDllFileInfo = Get-ItemProperty -Path $svrsetupDll + $fileVersion = $svrsetupDllFileInfo.VersionInfo.FileVersion + if ($fileVersion -ge "15.0.4709.1000") + { + $checkDotNet = $false + } + } + + if ($checkDotNet -eq $true) { - throw [Exception] ("A known issue prevents installation of SharePoint 2013 on " + ` - "servers that have .NET 4.6 already installed. See details " + ` - "at https://support.microsoft.com/en-us/kb/3087184") - return - } + $ndpKey = "HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4" + $dotNet46Installed = $false + if (Test-Path -Path $ndpKey) + { + $dotNetv4Keys = Get-ChildItem -Path $ndpKey + foreach ($dotnetInstance in $dotNetv4Keys) + { + if ($dotnetInstance.GetValue("Release") -ge 390000) + { + $dotNet46Installed = $true + break + } + } + } + + if ($dotNet46Installed -eq $true) + { + throw [Exception] ("A known issue prevents installation of SharePoint 2013 on " + ` + "servers that have .NET 4.6 already installed. See details " + ` + "at https://support.microsoft.com/en-us/kb/3087184") + return + } + } } Write-Verbose -Message "Writing install config file" @@ -176,7 +204,7 @@ function Set-TargetResource -or ((Get-Item $pr3 | Get-ItemProperty).PendingFileRenameOperations.count -gt 0) ` ) { - Write-Verbose -Message ("xSPInstall has detected the server has pending " + ` + Write-Verbose -Message ("SPInstall has detected the server has pending " + ` "a reboot. Flagging to the DSC engine that the " + ` "server should reboot before continuing.") $global:DSCMachineStatus = 1 @@ -220,6 +248,10 @@ function Test-TargetResource $Ensure = "Present" ) + Write-Verbose -Message "Testing install status of SharePoint" + + $PSBoundParameters.Ensure = $Ensure + if ($Ensure -eq "Absent") { throw [Exception] ("SharePointDsc does not support uninstalling SharePoint or " + ` @@ -227,11 +259,8 @@ function Test-TargetResource return } - $PSBoundParameters.Ensure = $Ensure $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing for installation of SharePoint" - return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("Ensure") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPInstallLanguagePack/MSFT_SPInstallLanguagePack.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPInstallLanguagePack/MSFT_SPInstallLanguagePack.psm1 index 5a230a09e..3654a1908 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPInstallLanguagePack/MSFT_SPInstallLanguagePack.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPInstallLanguagePack/MSFT_SPInstallLanguagePack.psm1 @@ -45,7 +45,7 @@ function Get-TargetResource $products = Invoke-SPDSCCommand -Credential $InstallAccount ` -ScriptBlock { - return Get-SPDscFarmProductsInfo + return Get-SPDscRegProductsInfo } # Extract language from filename @@ -159,6 +159,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting install status of SharePoint Language Pack" + if ($Ensure -eq "Absent") { throw [Exception] ("SharePointDsc does not support uninstalling SharePoint " + ` @@ -344,6 +346,10 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing install status of SharePoint Language Pack" + + $PSBoundParameters.Ensure = $Ensure + if ($Ensure -eq "Absent") { throw [Exception] ("SharePointDsc does not support uninstalling SharePoint " + ` @@ -351,11 +357,8 @@ function Test-TargetResource return } - $PSBoundParameters.Ensure = $Ensure $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing for installation of the SharePoint Language Pack" - return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("Ensure") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPInstallPrereqs/MSFT_SPInstallPrereqs.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPInstallPrereqs/MSFT_SPInstallPrereqs.psm1 index df98224c3..abfbfd2c1 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPInstallPrereqs/MSFT_SPInstallPrereqs.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPInstallPrereqs/MSFT_SPInstallPrereqs.psm1 @@ -139,7 +139,8 @@ function Get-TargetResource $Ensure = "Present" ) - Write-Verbose -Message "Detecting SharePoint version from binaries" + Write-Verbose -Message "Getting installation status of SharePoint prerequisites" + $majorVersion = (Get-SPDSCAssemblyVersion -PathToAssembly $InstallerPath) if ($majorVersion -eq 15) { @@ -266,24 +267,24 @@ function Get-TargetResource SearchValue = "Microsoft ODBC Driver 11 for SQL Server" }, [PSObject]@{ - Name = "Microsoft Visual C++ 2012 x64 Minimum Runtime - 11.0.61030" - SearchType = "Equals" - SearchValue = "Microsoft Visual C++ 2012 x64 Minimum Runtime - 11.0.61030" + Name = "Microsoft Visual C++ 2012 x64 Minimum Runtime - 11.0" + SearchType = "Like" + SearchValue = "Microsoft Visual C++ 2012 x64 Minimum Runtime - 11.0.*" }, [PSObject]@{ - Name = "Microsoft Visual C++ 2012 x64 Additional Runtime - 11.0.61030" - SearchType = "Equals" - SearchValue = "Microsoft Visual C++ 2012 x64 Additional Runtime - 11.0.61030" + Name = "Microsoft Visual C++ 2012 x64 Additional Runtime - 11.0" + SearchType = "Like" + SearchValue = "Microsoft Visual C++ 2012 x64 Additional Runtime - 11.0.*" }, [PSObject]@{ - Name = "Microsoft Visual C++ 2015 x64 Minimum Runtime - 14.0.23026" - SearchType = "Equals" - SearchValue = "Microsoft Visual C++ 2015 x64 Minimum Runtime - 14.0.23026" + Name = "Microsoft Visual C++ 2015 x64 Minimum Runtime - 14.0" + SearchType = "Like" + SearchValue = "Microsoft Visual C++ 2015 x64 Minimum Runtime - 14.0.*" }, [PSObject]@{ - Name = "Microsoft Visual C++ 2015 x64 Additional Runtime - 14.0.23026" - SearchType = "Equals" - SearchValue = "Microsoft Visual C++ 2015 x64 Additional Runtime - 14.0.23026" + Name = "Microsoft Visual C++ 2015 x64 Additional Runtime - 14.0" + SearchType = "Like" + SearchValue = "Microsoft Visual C++ 2015 x64 Additional Runtime - 14.0.*" } ) } @@ -411,6 +412,8 @@ function Set-TargetResource $Ensure = "Present" ) + Write-Verbose -Message "Setting installation status of SharePoint prerequisites" + if ($Ensure -eq "Absent") { throw [Exception] ("SharePointDsc does not support uninstalling SharePoint or its " + ` @@ -424,18 +427,43 @@ function Set-TargetResource if ($majorVersion -eq 15) { - $ndpKey = "HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP" - $dotNet46Check = Get-ChildItem -Path $ndpKey -Recurse ` - | Get-ItemProperty -name Version,Release -ErrorAction SilentlyContinue ` - | Where-Object -FilterScript { - $_.PSChildName -match '^(?!S)\p{L}' -and $_.Version -like "4.6.*" - } - if ($null -ne $dotNet46Check -and $dotNet46Check.Length -gt 0) + $BinaryDir = Split-Path -Path $InstallerPath + $svrsetupDll = Join-Path -Path $BinaryDir -ChildPath "updates\svrsetup.dll" + $checkDotNet = $true + if (Test-Path -Path $svrsetupDll) { - throw [Exception] ("A known issue prevents installation of SharePoint 2013 on " + ` - "servers that have .NET 4.6 already installed. See details at " + ` - "https://support.microsoft.com/en-us/kb/3087184") - return + $svrsetupDllFileInfo = Get-ItemProperty -Path $svrsetupDll + $fileVersion = $svrsetupDllFileInfo.VersionInfo.FileVersion + if ($fileVersion -ge "15.0.4709.1000") + { + $checkDotNet = $false + } + } + + if ($checkDotNet -eq $true) + { + $ndpKey = "HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4" + $dotNet46Installed = $false + if (Test-Path -Path $ndpKey) + { + $dotNetv4Keys = Get-ChildItem -Path $ndpKey + foreach ($dotnetInstance in $dotNetv4Keys) + { + if ($dotnetInstance.GetValue("Release") -ge 390000) + { + $dotNet46Installed = $true + break + } + } + } + + if ($dotNet46Installed -eq $true) + { + throw [Exception] ("A known issue prevents installation of SharePoint 2013 on " + ` + "servers that have .NET 4.6 already installed. See details " + ` + "at https://support.microsoft.com/en-us/kb/3087184") + return + } } Write-Verbose -Message "Version: SharePoint 2013" @@ -443,6 +471,7 @@ function Set-TargetResource "MSIPCClient","WCFDataServices","KB2671763","WCFDataServices56") $WindowsFeatures = Get-WindowsFeature -Name $Script:SP2013Features } + if ($majorVersion -eq 16) { Write-Verbose -Message "Version: SharePoint 2016" @@ -660,6 +689,10 @@ function Test-TargetResource $Ensure = "Present" ) + Write-Verbose -Message "Testing installation status of SharePoint prerequisites" + + $PSBoundParameters.Ensure = $Ensure + if ($Ensure -eq "Absent") { throw [Exception] ("SharePointDsc does not support uninstalling SharePoint or its " + ` @@ -667,10 +700,7 @@ function Test-TargetResource return } - $PSBoundParameters.Ensure = $Ensure $CurrentValues = Get-TargetResource @PSBoundParameters - - Write-Verbose -Message "Checking installation of SharePoint prerequisites" return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters -ValuesToCheck @("Ensure") @@ -742,4 +772,3 @@ function Test-SPDscPrereqInstallStatus } Export-ModuleMember -Function *-TargetResource - diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPIrmSettings/MSFT_SPIrmSettings.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPIrmSettings/MSFT_SPIrmSettings.psm1 index e9a8b4476..80d6a6785 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPIrmSettings/MSFT_SPIrmSettings.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPIrmSettings/MSFT_SPIrmSettings.psm1 @@ -22,11 +22,11 @@ function Get-TargetResource $InstallAccount ) - write-verbose "Getting SharePoint IRM Settings" + Write-Verbose "Getting SharePoint IRM Settings" - $result = Invoke-SPDSCCommand -Credential $InstallAccount ` - -Arguments $PSBoundParameters ` - -ScriptBlock { + $result = Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments $PSBoundParameters ` + -ScriptBlock { $params = $args[0] try @@ -65,7 +65,6 @@ function Get-TargetResource return $Result } - function Set-TargetResource { [CmdletBinding()] @@ -89,7 +88,7 @@ function Set-TargetResource $InstallAccount ) - write-verbose "Applying SharePoint IRM settings" + Write-Verbose "Setting SharePoint IRM Settings" Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -134,7 +133,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -175,7 +173,6 @@ function Test-TargetResource return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters - } Export-ModuleMember -Function *-TargetResource diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPJoinFarm/MSFT_SPJoinFarm.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPJoinFarm/MSFT_SPJoinFarm.psm1 index 7b79a67de..458e365d9 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPJoinFarm/MSFT_SPJoinFarm.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPJoinFarm/MSFT_SPJoinFarm.psm1 @@ -33,7 +33,7 @@ function Get-TargetResource $ServerRole ) - Write-Verbose -Message "Checking for local SP Farm" + Write-Verbose -Message "Getting local farm presence" if (($PSBoundParameters.ContainsKey("ServerRole") -eq $true) ` -and (Get-SPDSCInstalledProductVersion).FileMajorPart -ne 16) @@ -74,7 +74,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -109,7 +108,7 @@ function Set-TargetResource $ServerRole ) - Write-Verbose -Message "Joining existing farm configuration database" + Write-Verbose -Message "Setting local farm" if (($PSBoundParameters.ContainsKey("ServerRole") -eq $true) ` -and (Get-SPDSCInstalledProductVersion).FileMajorPart -ne 16) @@ -190,7 +189,6 @@ function Set-TargetResource $global:DSCMachineStatus = 1 } - function Test-TargetResource { [CmdletBinding()] @@ -226,6 +224,8 @@ function Test-TargetResource $ServerRole ) + Write-Verbose -Message "Testing for local farm presence" + if (($PSBoundParameters.ContainsKey("ServerRole") -eq $true) ` -and (Get-SPDSCInstalledProductVersion).FileMajorPart -ne 16) { @@ -233,12 +233,10 @@ function Test-TargetResource } $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose "Testing for local farm presence" + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("FarmConfigDatabaseName") } - Export-ModuleMember -Function *-TargetResource - diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPManagedAccount/MSFT_SPManagedAccount.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPManagedAccount/MSFT_SPManagedAccount.psm1 index 461b53f0e..fc14b09fc 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPManagedAccount/MSFT_SPManagedAccount.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPManagedAccount/MSFT_SPManagedAccount.psm1 @@ -34,7 +34,7 @@ function Get-TargetResource $AccountName ) - Write-Verbose -Message "Checking for managed account $AccountName" + Write-Verbose -Message "Getting managed account $AccountName" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -105,6 +105,8 @@ function Set-TargetResource $AccountName ) + Write-Verbose -Message "Setting managed account $AccountName" + if ($Ensure -eq "Present" -and $null -eq $Account) { throw ("You must specify the 'Account' property as a PSCredential to create a " + ` @@ -163,7 +165,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -200,9 +201,12 @@ function Test-TargetResource $AccountName ) - $CurrentValues = Get-TargetResource @PSBoundParameters Write-Verbose -Message "Testing managed account $AccountName" + $PSBoundParameters.Ensure = $Ensure + + $CurrentValues = Get-TargetResource @PSBoundParameters + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("AccountName", diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPManagedMetadataServiceApp/MSFT_SPManagedMetaDataServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPManagedMetadataServiceApp/MSFT_SPManagedMetaDataServiceApp.psm1 index d9d7a41f5..498ea7949 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPManagedMetadataServiceApp/MSFT_SPManagedMetaDataServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPManagedMetadataServiceApp/MSFT_SPManagedMetaDataServiceApp.psm1 @@ -56,8 +56,8 @@ function Get-TargetResource { return $nullReturn } - $serviceApp = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "Managed Metadata Service" + $serviceApp = $serviceApps | Where-Object -FilterScript { + $_.GetType().FullName -eq "Microsoft.SharePoint.Taxonomy.MetadataWebServiceApplication" } if ($null -eq $serviceApp) @@ -77,21 +77,41 @@ function Get-TargetResource $proxyName = $serviceAppProxy.Name } } + + # Get the ContentTypeHubUrl value + $hubUrl = "" + try + { + $propertyFlags = [System.Reflection.BindingFlags]::Instance ` + -bor [System.Reflection.BindingFlags]::NonPublic + + $propData = $serviceApp.GetType().GetMethods($propertyFlags) + $method = $propData | Where-Object -FilterScript { + $_.Name -eq "GetContentTypeSyndicationHubLocal" + } + $defaultPartitionId = [Guid]::Parse("0C37852B-34D0-418e-91C6-2AC25AF4BE5B") + $hubUrl = $method.Invoke($serviceApp, $defaultPartitionId).AbsoluteUri + } + catch [System.Exception] + { + $hubUrl = "" + } + return @{ - Name = $serviceApp.DisplayName - ProxyName = $proxyName - Ensure = "Present" - ApplicationPool = $serviceApp.ApplicationPool.Name - DatabaseName = $serviceApp.Database.Name - DatabaseServer = $serviceApp.Database.Server.Name - InstallAccount = $params.InstallAccount + Name = $serviceApp.DisplayName + ProxyName = $proxyName + Ensure = "Present" + ApplicationPool = $serviceApp.ApplicationPool.Name + DatabaseName = $serviceApp.Database.Name + DatabaseServer = $serviceApp.Database.Server.Name + ContentTypeHubUrl = $hubUrl.TrimEnd('/') + InstallAccount = $params.InstallAccount } } } return $result } - function Set-TargetResource { [CmdletBinding()] @@ -131,6 +151,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting managed metadata service application $Name" + $result = Get-TargetResource @PSBoundParameters if ($result.Ensure -eq "Absent" -and $Ensure -eq "Present") @@ -188,13 +210,30 @@ function Set-TargetResource $params = $args[0] $serviceApp = Get-SPServiceApplication -Name $params.Name ` - | Where-Object -FilterScript { - $_.TypeName -eq "Managed Metadata Service" + | Where-Object -FilterScript { + $_.GetType().FullName -eq "Microsoft.SharePoint.Taxonomy.MetadataWebServiceApplication" } $appPool = Get-SPServiceApplicationPool -Identity $params.ApplicationPool Set-SPMetadataServiceApplication -Identity $serviceApp -ApplicationPool $appPool } } + + if (($PSBoundParameters.ContainsKey("ContentTypeHubUrl") -eq $true) ` + -and ($ContentTypeHubUrl.TrimEnd('/') -ne $result.ContentTypeHubUrl.TrimEnd('/'))) + { + Write-Verbose -Message "Updating Content type hub for Managed Metadata Service Application $Name" + Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments $PSBoundParameters ` + -ScriptBlock { + $params = $args[0] + + $serviceApp = Get-SPServiceApplication -Name $params.Name ` + | Where-Object -FilterScript { + $_.GetType().FullName -eq "Microsoft.SharePoint.Taxonomy.MetadataWebServiceApplication" + } + Set-SPMetadataServiceApplication -Identity $serviceApp -HubUri $params.ContentTypeHubUrl + } + } } if ($Ensure -eq "Absent") @@ -204,17 +243,27 @@ function Set-TargetResource Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { - $params = $args[0] - + $params = $args[0] + $serviceApp = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { - $_.TypeName -eq "Managed Metadata Service" + $_.GetType().FullName -eq "Microsoft.SharePoint.Taxonomy.MetadataWebServiceApplication" + } - Remove-SPServiceApplication $serviceApp -Confirm:$false + + $proxies = Get-SPServiceApplicationProxy + foreach($proxyInstance in $proxies) + { + if($serviceApp.IsConnected($proxyInstance)) + { + $proxyInstance.Delete() + } + } + + Remove-SPServiceApplication -Identity $serviceApp -Confirm:$false } } } - function Test-TargetResource { [CmdletBinding()] @@ -255,13 +304,21 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing for Managed Metadata Service Application '$Name'" + Write-Verbose -Message "Testing managed metadata service application $Name" + $PSBoundParameters.Ensure = $Ensure + if ($PSBoundParameters.ContainsKey("ContentTypeHubUrl") -eq $true) + { + $PSBoundParameters.ContentTypeHubUrl = $ContentTypeHubUrl.TrimEnd('/') + } + + $CurrentValues = Get-TargetResource @PSBoundParameters + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` - -ValuesToCheck @("ApplicationPool", "Ensure") + -ValuesToCheck @("ApplicationPool", + "ContentTypeHubUrl", + "Ensure") } - Export-ModuleMember -Function *-TargetResource diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPManagedPath/MSFT_SPManagedPath.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPManagedPath/MSFT_SPManagedPath.psm1 index 4609c4909..efc15cbb6 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPManagedPath/MSFT_SPManagedPath.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPManagedPath/MSFT_SPManagedPath.psm1 @@ -30,7 +30,7 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Looking up the managed path $RelativeUrl in $WebAppUrl" + Write-Verbose -Message "Getting managed path $RelativeUrl in $WebAppUrl" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -73,7 +73,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -105,6 +104,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting managed path $RelativeUrl in $WebAppUrl" + $CurrentResults = Get-TargetResource @PSBoundParameters if ($CurrentResults.Ensure -eq "Absent" -and $Ensure -eq "Present") @@ -156,7 +157,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -189,9 +189,12 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Looking up the managed path $RelativeUrl in $WebAppUrl" + Write-Verbose -Message "Testing managed path $RelativeUrl in $WebAppUrl" + $PSBoundParameters.Ensure = $Ensure + + $CurrentValues = Get-TargetResource @PSBoundParameters + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("WebAppUrl", @@ -202,4 +205,3 @@ function Test-TargetResource } Export-ModuleMember -Function *-TargetResource - diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPOfficeOnlineServerBinding/MSFT_SPOfficeOnlineServerBinding.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPOfficeOnlineServerBinding/MSFT_SPOfficeOnlineServerBinding.psm1 index 184422e0a..6ee071c24 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPOfficeOnlineServerBinding/MSFT_SPOfficeOnlineServerBinding.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPOfficeOnlineServerBinding/MSFT_SPOfficeOnlineServerBinding.psm1 @@ -23,7 +23,7 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Looking up the Office Online Server details for '$Zone' zone" + Write-Verbose -Message "Getting Office Online Server details for '$Zone' zone" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -55,7 +55,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -80,6 +79,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting Office Online Server details for '$Zone' zone" + $CurrentResults = Get-TargetResource @PSBoundParameters if ($Ensure -eq "Present") @@ -129,7 +130,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -155,10 +155,11 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters + Write-Verbose -Message "Testing Office Online Server details for '$Zone' zone" + $PSBoundParameters.Ensure = $Ensure - Write-Verbose -Message "Testing Office Online Server details for '$Zone' zone" + $CurrentValues = Get-TargetResource @PSBoundParameters $paramsToCheck = @("Ensure") if ($Ensure -eq "Present") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPOutgoingEmailSettings/MSFT_SPOutgoingEmailSettings.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPOutgoingEmailSettings/MSFT_SPOutgoingEmailSettings.psm1 index fd12873ec..5cd4d011b 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPOutgoingEmailSettings/MSFT_SPOutgoingEmailSettings.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPOutgoingEmailSettings/MSFT_SPOutgoingEmailSettings.psm1 @@ -29,7 +29,7 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Retrieving outgoing email settings configuration " + Write-Verbose -Message "Getting outgoing email settings configuration for $WebAppUrl" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -91,7 +91,8 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Updating outgoing email settings configuration for $WebAppUrl" + Write-Verbose -Message "Setting outgoing email settings configuration for $WebAppUrl" + Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { @@ -112,7 +113,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -144,9 +144,14 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Getting outgoing email settings configuration for $WebAppUrl" + $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Comparing Current and Target Outgoing email settings" - if ($null -eq $CurrentValues) { return $false } + + if ($null -eq $CurrentValues) + { + return $false + } return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPPasswordChangeSettings/MSFT_SPPasswordChangeSettings.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPPasswordChangeSettings/MSFT_SPPasswordChangeSettings.psm1 index 0d8d4c001..30d625ffe 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPPasswordChangeSettings/MSFT_SPPasswordChangeSettings.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPPasswordChangeSettings/MSFT_SPPasswordChangeSettings.psm1 @@ -28,7 +28,7 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Retrieving farm wide automatic password change settings" + Write-Verbose -Message "Getting farm wide automatic password change settings" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -79,7 +79,8 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Updating farm wide automatic password change settings" + Write-Verbose -Message "Setting farm wide automatic password change settings" + Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { @@ -108,7 +109,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -139,9 +139,14 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing farm wide automatic password change settings" + $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing retrieving farm wide automatic password change settings" - if ($null -eq $CurrentValues) { return $false } + + if ($null -eq $CurrentValues) + { + return $false + } return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPPerformancePointServiceApp/MSFT_SPPerformancePointServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPPerformancePointServiceApp/MSFT_SPPerformancePointServiceApp.psm1 index e7fa1f71b..e09ae9459 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPPerformancePointServiceApp/MSFT_SPPerformancePointServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPPerformancePointServiceApp/MSFT_SPPerformancePointServiceApp.psm1 @@ -34,11 +34,11 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Getting Performance Point service app '$Name'" + Write-Verbose -Message "Getting for PerformancePoint Service Application '$Name'" - $result = Invoke-SPDSCCommand -Credential $InstallAccount ` - -Arguments $PSBoundParameters ` - -ScriptBlock { + $result = Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments $PSBoundParameters ` + -ScriptBlock { $params = $args[0] $serviceApps = Get-SPServiceApplication -Name $params.Name -ErrorAction SilentlyContinue @@ -52,8 +52,8 @@ function Get-TargetResource { return $nullReturn } - $serviceApp = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "PerformancePoint Service Application" + $serviceApp = $serviceApps | Where-Object -FilterScript { + $_.GetType().FullName -eq "Microsoft.PerformancePoint.Scorecards.BIMonitoringServiceApplication" } if ($null -eq $serviceApp) @@ -121,6 +121,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting PerformancePoint Service Application '$Name'" + $result = Get-TargetResource @PSBoundParameters if ($result.Ensure -eq "Absent" -and $Ensure -eq "Present") @@ -172,7 +174,7 @@ function Set-TargetResource Get-SPServiceApplication -Name $params.Name ` | Where-Object -FilterScript { - $_.TypeName -eq "PerformancePoint Service Application" + $_.GetType().FullName -eq "Microsoft.PerformancePoint.Scorecards.BIMonitoringServiceApplication" } | Set-SPPerformancePointServiceApplication -ApplicationPool $appPool } } @@ -186,9 +188,19 @@ function Set-TargetResource $params = $args[0] $app = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { - $_.TypeName -eq "PerformancePoint Service Application" + $_.GetType().FullName -eq "Microsoft.PerformancePoint.Scorecards.BIMonitoringServiceApplication" + } + + $proxies = Get-SPServiceApplicationProxy + foreach($proxyInstance in $proxies) + { + if($app.IsConnected($proxyInstance)) + { + $proxyInstance.Delete() + } } - Remove-SPServiceApplication $app -Confirm:$false + + Remove-SPServiceApplication -Identity $app -Confirm:$false } } } @@ -229,9 +241,12 @@ function Test-TargetResource $InstallAccount ) - Write-Verbose -Message "Testing for PerformancePoint Service Application '$Name'" - $CurrentValues = Get-TargetResource @PSBoundParameters + Write-Verbose -Message "Testing PerformancePoint Service Application '$Name'" + $PSBoundParameters.Ensure = $Ensure + + $CurrentValues = Get-TargetResource @PSBoundParameters + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("ApplicationPool", "Ensure") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPProductUpdate/MSFT_SPProductUpdate.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPProductUpdate/MSFT_SPProductUpdate.psm1 index c06f2f2c6..695389309 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPProductUpdate/MSFT_SPProductUpdate.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPProductUpdate/MSFT_SPProductUpdate.psm1 @@ -31,6 +31,12 @@ function Get-TargetResource $InstallAccount ) + if ($Ensure -eq "Absent") + { + throw [Exception] "SharePoint does not support uninstalling updates." + return + } + Write-Verbose -Message "Getting install status of SP binaries" $languagepack = $false @@ -214,6 +220,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting install status of SP Update binaries" + if ($Ensure -eq "Absent") { throw [Exception] "SharePoint does not support uninstalling updates." @@ -455,7 +463,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -489,17 +496,18 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing install status of SP Update binaries" + + $PSBoundParameters.Ensure = $Ensure + if ($Ensure -eq "Absent") { throw [Exception] "SharePoint does not support uninstalling updates." return } - $PSBoundParameters.Ensure = $Ensure $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing for installation of the SharePoint Update" - return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("Ensure") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPProductUpdate/readme.md b/Modules/SharePointDsc/DSCResources/MSFT_SPProductUpdate/readme.md index 375497494..3b461105e 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPProductUpdate/readme.md +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPProductUpdate/readme.md @@ -5,3 +5,12 @@ The SetupFile parameter should point to the update file. The ShutdownServices parameter is used to indicate if some services (Timer, Search and IIS services) have to be stopped before installation of the update. This will speed up the installation. The BinaryInstallDays and BinaryInstallTime parameters specify a window in which the update can be installed. This module requires the Configuration Wizard resource to fully complete the installation of the update, which can be done through the use of SPConfigWizard. + +IMPORTANT: +This resource retrieves build information from the Configuration Database. Therefore it requires SharePoint to be installed and a farm created. +If you like to deploy a new farm and install updates automatically, you need to implement the following order: +1. Install the SharePoint Binaries (SPInstall) +2. (Optional) Install SharePoint Language Pack(s) Binaries (SPInstallLanguagePack) +3. Create SPFarm (SPCreateFarm) +4. Install Cumulative Updates (SPProductUpdate) +5. Run the Configuration Wizard (SPConfigWizard) diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPQuotaTemplate/MSFT_SPQuotaTemplate.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPQuotaTemplate/MSFT_SPQuotaTemplate.psm1 index a06dad8b8..43f04e54f 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPQuotaTemplate/MSFT_SPQuotaTemplate.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPQuotaTemplate/MSFT_SPQuotaTemplate.psm1 @@ -34,7 +34,8 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Getting Quota Template settings" + Write-Verbose -Message "Getting Quota Template settings for quota $Name" + if ($StorageMaxInMB -lt $StorageWarningInMB) { Throw "StorageMaxInMB must be larger than StorageWarningInMB." @@ -99,7 +100,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -135,7 +135,7 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Setting quota template settings" + Write-Verbose -Message "Setting Quota Template settings for quota $Name" if ($StorageMaxInMB -lt $StorageWarningInMB) { @@ -261,7 +261,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -298,7 +297,8 @@ function Test-TargetResource $InstallAccount ) - Write-Verbose -Message "Testing quota template settings" + Write-Verbose -Message "Testing Quota Template settings for quota $Name" + if ($StorageMaxInMB -le $StorageWarningInMB) { Throw "StorageMaxInMB must be equal to or larger than StorageWarningInMB." diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPRemoteFarmTrust/MSFT_SPRemoteFarmTrust.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPRemoteFarmTrust/MSFT_SPRemoteFarmTrust.psm1 index 466f8b695..9b0be7ce8 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPRemoteFarmTrust/MSFT_SPRemoteFarmTrust.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPRemoteFarmTrust/MSFT_SPRemoteFarmTrust.psm1 @@ -24,7 +24,7 @@ function Get-TargetResource() $InstallAccount ) - Write-Verbose -Message "Looking for remote farm trust '$Name'" + Write-Verbose -Message "Getting remote farm trust '$Name'" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -91,6 +91,8 @@ function Set-TargetResource() $InstallAccount ) + Write-Verbose -Message "Setting remote farm trust '$Name'" + if ($Ensure -eq "Present") { Write-Verbose -Message "Adding remote farm trust '$Name'" @@ -199,6 +201,8 @@ function Test-TargetResource() $InstallAccount ) + Write-Verbose -Message "Testing remote farm trust '$Name'" + $CurrentValues = Get-TargetResource @PSBoundParameters return Test-SPDscParameterState -CurrentValues $CurrentValues ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPSearchContentSource/MSFT_SPSearchContentSource.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPSearchContentSource/MSFT_SPSearchContentSource.psm1 index f09a57342..06bc16f25 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPSearchContentSource/MSFT_SPSearchContentSource.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPSearchContentSource/MSFT_SPSearchContentSource.psm1 @@ -65,6 +65,8 @@ function Get-TargetResource $InstallAccount ) + Write-Verbose -Message "Getting Content Source Setting for '$Name'" + $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments @($PSBoundParameters, $PSScriptRoot) ` -ScriptBlock { @@ -251,7 +253,10 @@ function Set-TargetResource $InstallAccount ) - switch ($ContentSourceType) { + Write-Verbose -Message "Setting Content Source Setting for '$Name'" + + switch ($ContentSourceType) + { "SharePoint" { if ($PSBoundParameters.ContainsKey("LimitPageDepth") -eq $true) { @@ -656,7 +661,12 @@ function Test-TargetResource $InstallAccount ) - switch ($ContentSourceType) { + Write-Verbose -Message "Testing Content Source Setting for '$Name'" + + $PSBoundParameters.Ensure = $Ensure + + switch ($ContentSourceType) + { "SharePoint" { if ($PSBoundParameters.ContainsKey("LimitPageDepth") -eq $true) { @@ -705,8 +715,6 @@ function Test-TargetResource } $CurrentValues = Get-TargetResource @PSBoundParameters - $PSBoundParameters.Ensure = $Ensure - if ($Ensure -eq "Absent" -or $CurrentValues.Ensure -eq "Absent") { return Test-SPDscParameterState -CurrentValues $CurrentValues ` @@ -729,7 +737,6 @@ function Test-TargetResource return $false } } - if (($PSBoundParameters.ContainsKey("FullSchedule") -eq $true) -and ($null -ne $FullSchedule)) { @@ -745,12 +752,12 @@ function Test-TargetResource $currentAddresses = @() foreach ($address in $CurrentValues.Addresses) { - $currentAddresses += New-Object System.Uri -ArgumentList $address + $currentAddresses += New-Object -TypeName System.Uri -ArgumentList $address } $desiredAddresses = @() foreach ($address in $Addresses) { - $desiredAddresses += New-Object System.Uri -ArgumentList $address + $desiredAddresses += New-Object -TypeName System.Uri -ArgumentList $address } if ($null -ne (Compare-Object -ReferenceObject $currentAddresses ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPSearchCrawlRule/MSFT_SPSearchCrawlRule.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPSearchCrawlRule/MSFT_SPSearchCrawlRule.psm1 index 4aacb8289..d44e9c96c 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPSearchCrawlRule/MSFT_SPSearchCrawlRule.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPSearchCrawlRule/MSFT_SPSearchCrawlRule.psm1 @@ -129,7 +129,7 @@ function Get-TargetResource } $serviceApp = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "Search Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication" } if ($null -eq $serviceApp) @@ -276,6 +276,9 @@ function Set-TargetResource [System.Management.Automation.PSCredential] $InstallAccount ) + + Write-Verbose -Message "Setting Search Crawl Rule '$Path'" + $result = Get-TargetResource @PSBoundParameters # AuthenticationType=CertificateName and CertificateRuleAccess parameters not specified @@ -502,10 +505,12 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters Write-Verbose -Message "Testing Search Crawl Rule '$Path'" - + $PSBoundParameters.Ensure = $Ensure + + $CurrentValues = Get-TargetResource @PSBoundParameters + if ($Ensure -eq "Present") { if ($CrawlConfigurationRules) diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPSearchIndexPartition/MSFT_SPSearchIndexPartition.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPSearchIndexPartition/MSFT_SPSearchIndexPartition.psm1 index 2850abae6..f8afd8b5a 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPSearchIndexPartition/MSFT_SPSearchIndexPartition.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPSearchIndexPartition/MSFT_SPSearchIndexPartition.psm1 @@ -25,6 +25,8 @@ function Get-TargetResource $InstallAccount ) + Write-Verbose -Message "Getting Search Index Partition '$Index' settings" + $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { @@ -77,6 +79,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting Search Index Partition '$Index' settings" + $CurrentValues = Get-TargetResource @PSBoundParameters Invoke-SPDSCCommand -Credential $InstallAccount ` @@ -244,7 +248,11 @@ function Test-TargetResource [System.Management.Automation.PSCredential] $InstallAccount ) + + Write-Verbose -Message "Testing Search Index Partition '$Index' settings" + $CurrentValues = Get-TargetResource @PSBoundParameters + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("Servers") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPSearchResultSource/MSFT_SPSearchResultSource.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPSearchResultSource/MSFT_SPSearchResultSource.psm1 index a0ed818e7..45eece8b8 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPSearchResultSource/MSFT_SPSearchResultSource.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPSearchResultSource/MSFT_SPSearchResultSource.psm1 @@ -47,10 +47,27 @@ function Get-TargetResource -ScriptBlock { $params = $args[0] [void] [Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.Search") - + + $nullReturn = @{ + Name = $params.Name + SearchServiceAppName = $params.SearchServiceAppName + Query = $null + ProviderType = $null + ConnectionUrl = $null + Ensure = "Absent" + InstallAccount = $params.InstallAccount + } $serviceApp = Get-SPEnterpriseSearchServiceApplication -Identity $params.SearchServiceAppName $searchSiteUrl = $serviceApp.SearchCenterUrl -replace "/pages" - $searchSite = Get-SPWeb -Identity $searchSiteUrl + $searchSite = Get-SPWeb -Identity $searchSiteUrl -ErrorAction SilentlyContinue + + if ($null -eq $searchSite) + { + Write-Verbose -Message ("Search centre site collection does not exist at " + ` + "$searchSiteUrl. Unable to create search context " + ` + "to determine result source details.") + return $nullReturn + } $adminNamespace = "Microsoft.Office.Server.Search.Administration" $queryNamespace = "Microsoft.Office.Server.Search.Administration.Query" @@ -83,21 +100,12 @@ function Get-TargetResource } else { - return @{ - Name = $params.Name - SearchServiceAppName = $params.SearchServiceAppName - Query = $null - ProviderType = $null - ConnectionUrl = $null - Ensure = "Absent" - InstallAccount = $params.InstallAccount - } + return $nullReturn } } return $result } - function Set-TargetResource { [CmdletBinding()] @@ -139,11 +147,12 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting search result source '$Name'" + $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Creating search result source '$Name'" - - if ($CurrentValues.Ensure -eq "Absent" -and $Ensure -eq "Present") { + if ($CurrentValues.Ensure -eq "Absent" -and $Ensure -eq "Present") + { Write-Verbose -Message "Creating search result source $Name" Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -155,7 +164,15 @@ function Set-TargetResource -Identity $params.SearchServiceAppName $searchSiteUrl = $serviceApp.SearchCenterUrl -replace "/pages" - $searchSite = Get-SPWeb -Identity $searchSiteUrl + $searchSite = Get-SPWeb -Identity $searchSiteUrl -ErrorAction SilentlyContinue + + if ($null -eq $searchSite) + { + throw ("Search centre site collection does not exist at " + ` + "$searchSiteUrl. Unable to create search context " + ` + "to set result source.") + return + } $adminNamespace = "Microsoft.Office.Server.Search.Administration" $queryNamespace = "Microsoft.Office.Server.Search.Administration.Query" @@ -185,7 +202,9 @@ function Set-TargetResource $resultSource.Commit() } } - if ($Ensure -eq "Absent") { + + if ($Ensure -eq "Absent") + { Write-Verbose -Message "Removing search result source $Name" Invoke-SPDSCCommand -Credential $InstallAccount -Arguments $PSBoundParameters -ScriptBlock { $params = $args[0] @@ -259,12 +278,15 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters Write-Verbose -Message "Testing search result source '$Name'" + $PSBoundParameters.Ensure = $Ensure + + $CurrentValues = Get-TargetResource @PSBoundParameters - return Test-SPDscParameterState -CurrentValues $CurrentValues -DesiredValues $PSBoundParameters -ValuesToCheck @("Ensure") + return Test-SPDscParameterState -CurrentValues $CurrentValues ` + -DesiredValues $PSBoundParameters ` + -ValuesToCheck @("Ensure") } Export-ModuleMember -Function *-TargetResource - diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPSearchServiceApp/MSFT_SPSearchServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPSearchServiceApp/MSFT_SPSearchServiceApp.psm1 index 0a7ea6d30..73dd863ef 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPSearchServiceApp/MSFT_SPSearchServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPSearchServiceApp/MSFT_SPSearchServiceApp.psm1 @@ -78,7 +78,7 @@ function Get-TargetResource return $nullReturn } $serviceApp = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "Search Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication" } if ($null -eq $serviceApp) @@ -183,6 +183,9 @@ function Set-TargetResource [System.Management.Automation.PSCredential] $InstallAccount ) + + Write-Verbose -Message "Setting Search service application '$Name'" + $result = Get-TargetResource @PSBoundParameters if ($result.Ensure -eq "Absent" -and $Ensure -eq "Present") @@ -254,7 +257,7 @@ function Set-TargetResource { $serviceApp = Get-SPServiceApplication -Name $params.Name | ` Where-Object -FilterScript { - $_.TypeName -eq "Search Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication" } $serviceApp.SearchCenterUrl = $params.SearchCenterUrl $serviceApp.Update() @@ -274,7 +277,7 @@ function Set-TargetResource $serviceApp = Get-SPServiceApplication -Name $params.Name | ` Where-Object -FilterScript { - $_.TypeName -eq "Search Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication" } $appPool = Get-SPServiceApplicationPool -Identity $params.ApplicationPool $setParams = @{ @@ -293,7 +296,7 @@ function Set-TargetResource { $serviceApp = Get-SPServiceApplication -Name $params.Name | ` Where-Object -FilterScript { - $_.TypeName -eq "Search Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication" } $serviceApp.SearchCenterUrl = $params.SearchCenterUrl $serviceApp.Update() @@ -311,9 +314,20 @@ function Set-TargetResource $params = $args[0] $serviceApp = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { - $_.TypeName -eq "Search Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication" + + } + + $proxies = Get-SPServiceApplicationProxy + foreach($proxyInstance in $proxies) + { + if($serviceApp.IsConnected($proxyInstance)) + { + $proxyInstance.Delete() + } } - Remove-SPServiceApplication $serviceApp -Confirm:$false + + Remove-SPServiceApplication -Identity $serviceApp -Confirm:$false } } } @@ -366,9 +380,12 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters Write-Verbose -Message "Testing Search service application '$Name'" + $PSBoundParameters.Ensure = $Ensure + + $CurrentValues = Get-TargetResource @PSBoundParameters + if ($PSBoundParameters.ContainsKey("DefaultContentAccessAccount") ` -and $Ensure -eq "Present") { @@ -379,7 +396,6 @@ function Test-TargetResource } } - $PSBoundParameters.Ensure = $Ensure if ($Ensure -eq "Present") { return Test-SPDscParameterState -CurrentValues $CurrentValues ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPSearchTopology/MSFT_SPSearchTopology.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPSearchTopology/MSFT_SPSearchTopology.psm1 index f15d24492..723a8882d 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPSearchTopology/MSFT_SPSearchTopology.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPSearchTopology/MSFT_SPSearchTopology.psm1 @@ -41,6 +41,8 @@ function Get-TargetResource $InstallAccount ) + Write-Verbose -Message "Getting Search Topology for '$ServiceAppName'" + $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { @@ -152,7 +154,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -195,6 +196,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting Search Topology for '$ServiceAppName'" + $CurrentValues = Get-TargetResource @PSBoundParameters Invoke-SPDSCCommand -Credential $InstallAccount ` @@ -400,7 +403,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -444,8 +446,15 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing Search Topology for '$ServiceAppName'" + $CurrentValues = Get-TargetResource @PSBoundParameters - if ($null -eq $CurrentValues) { return $false } + + if ($null -eq $CurrentValues) + { + return $false + } + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @( diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPSecureStoreServiceApp/MSFT_SPSecureStoreServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPSecureStoreServiceApp/MSFT_SPSecureStoreServiceApp.psm1 index 824a3f0d4..353cb31f4 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPSecureStoreServiceApp/MSFT_SPSecureStoreServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPSecureStoreServiceApp/MSFT_SPSecureStoreServiceApp.psm1 @@ -83,7 +83,7 @@ function Get-TargetResource return $nullReturn } $serviceApp = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "Secure Store Service Application" + $_.GetType().FullName -eq "Microsoft.Office.SecureStoreService.Server.SecureStoreServiceApplication" } if ($null -eq $serviceApp) @@ -117,7 +117,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -182,6 +181,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting secure store service application '$Name'" + $result = Get-TargetResource @PSBoundParameters $params = $PSBoundParameters @@ -247,7 +248,7 @@ function Set-TargetResource $params = $args[0] $serviceApp = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { - $_.TypeName -eq "Secure Store Service Application" + $_.GetType().FullName -eq "Microsoft.Office.SecureStoreService.Server.SecureStoreServiceApplication" } $appPool = Get-SPServiceApplicationPool -Identity $params.ApplicationPool Set-SPSecureStoreServiceApplication -Identity $serviceApp -ApplicationPool $appPool @@ -265,14 +266,24 @@ function Set-TargetResource $params = $args[0] $serviceApp = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { - $_.TypeName -eq "Secure Store Service Application" + $_.GetType().FullName -eq "Microsoft.Office.SecureStoreService.Server.SecureStoreServiceApplication" + } + + # Remove the connected proxy(ies) + $proxies = Get-SPServiceApplicationProxy + foreach($proxyInstance in $proxies) + { + if($serviceApp.IsConnected($proxyInstance)) + { + $proxyInstance.Delete() + } } + Remove-SPServiceApplication $serviceApp -Confirm:$false } } } - function Test-TargetResource { [CmdletBinding()] @@ -338,13 +349,15 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters Write-Verbose -Message "Testing secure store service application $Name" + $PSBoundParameters.Ensure = $Ensure + + $CurrentValues = Get-TargetResource @PSBoundParameters + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("ApplicationPool", "Ensure") } - Export-ModuleMember -Function *-TargetResource diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPServiceAppPool/MSFT_SPServiceAppPool.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPServiceAppPool/MSFT_SPServiceAppPool.psm1 index c0f91a40d..2da3f966e 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPServiceAppPool/MSFT_SPServiceAppPool.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPServiceAppPool/MSFT_SPServiceAppPool.psm1 @@ -50,7 +50,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -74,10 +73,10 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting service application pool '$Name'" + $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Creating service application pool '$Name'" - if ($CurrentValues.Ensure -eq "Absent" -and $Ensure -eq "Present") { Write-Verbose -Message "Creating Service Application Pool $Name" @@ -154,9 +153,12 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters Write-Verbose -Message "Testing service application pool '$Name'" + $PSBoundParameters.Ensure = $Ensure + + $CurrentValues = Get-TargetResource @PSBoundParameters + if ($Ensure -eq "Present") { return Test-SPDscParameterState -CurrentValues $CurrentValues ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPServiceAppProxyGroup/MSFT_SPServiceAppProxyGroup.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPServiceAppProxyGroup/MSFT_SPServiceAppProxyGroup.psm1 index 16d00205e..74e1d1c47 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPServiceAppProxyGroup/MSFT_SPServiceAppProxyGroup.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPServiceAppProxyGroup/MSFT_SPServiceAppProxyGroup.psm1 @@ -30,6 +30,8 @@ function Get-TargetResource $InstallAccount ) + Write-Verbose -Message "Getting Service Application Proxy Group $Name" + if (($Ensure -eq "Present") ` -and $ServiceAppProxies ` -and (($ServiceAppProxiesToInclude) -or ($ServiceAppProxiesToExclude))) @@ -50,9 +52,7 @@ function Get-TargetResource "ServiceAppProxiesToExclude") return $null } - - Write-Verbose -Message "Getting Service Application Proxy Group $Name" - + $result = Invoke-SPDSCCommand -Credential $InstallAccount -Arguments $PSBoundParameters -ScriptBlock { $params = $args[0] @@ -85,8 +85,6 @@ function Get-TargetResource return $result } - - function Set-TargetResource { [CmdletBinding()] @@ -333,7 +331,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -366,7 +363,7 @@ function Test-TargetResource $InstallAccount ) - write-verbose "Testing Service Application Proxy Group $Name" + Write-Verbose -Message "Testing Service Application Proxy Group $Name" $CurrentValues = Get-TargetResource @PSBoundParameters diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPServiceAppSecurity/MSFT_SPServiceAppSecurity.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPServiceAppSecurity/MSFT_SPServiceAppSecurity.psm1 index 211f25cdf..a87d12e76 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPServiceAppSecurity/MSFT_SPServiceAppSecurity.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPServiceAppSecurity/MSFT_SPServiceAppSecurity.psm1 @@ -30,6 +30,8 @@ function Get-TargetResource $InstallAccount ) + Write-Verbose -Message "Getting all security options for $SecurityType in $ServiceAppName" + if ($Members -and (($MembersToInclude) -or ($MembersToExclude))) { throw ("Cannot use the Members parameter together with the MembersToInclude or " + ` @@ -42,8 +44,6 @@ function Get-TargetResource "MembersToInclude, MembersToExclude") } - Write-Verbose -Message "Getting all security options for $SecurityType in $ServiceAppName" - $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { @@ -104,7 +104,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -136,7 +135,7 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Setting service app security config" + Write-Verbose -Message "Setting all security options for $SecurityType in $ServiceAppName" if ($Members -and (($MembersToInclude) -or ($MembersToExclude))) { @@ -303,7 +302,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -336,7 +334,7 @@ function Test-TargetResource $InstallAccount ) - Write-Verbose -Message "Testing service app security config" + Write-Verbose -Message "Testing all security options for $SecurityType in $ServiceAppName" $CurrentValues = Get-TargetResource @PSBoundParameters diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPServiceInstance/MSFT_SPServiceInstance.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPServiceInstance/MSFT_SPServiceInstance.psm1 index fe6dad29c..383a60b80 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPServiceInstance/MSFT_SPServiceInstance.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPServiceInstance/MSFT_SPServiceInstance.psm1 @@ -8,11 +8,11 @@ function Get-TargetResource [System.String] $Name, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present" @@ -73,7 +73,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -83,16 +82,18 @@ function Set-TargetResource [System.String] $Name, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present" ) + Write-Verbose -Message "Setting service instance '$Name'" + $newName = (Get-SPDscServiceTypeName -DisplayName $Name) $invokeArgs = @{ Credential = $InstallAccount @@ -105,6 +106,7 @@ function Set-TargetResource Invoke-SPDSCCommand @invokeArgs -ScriptBlock { $params = $args[0] + $newName = $args[1] $si = Get-SPServiceInstance -Server $env:COMPUTERNAME | Where-Object -FilterScript { $_.TypeName -eq $params.Name -or ` @@ -134,6 +136,7 @@ function Set-TargetResource Invoke-SPDSCCommand @invokeArgs -ScriptBlock { $params = $args[0] + $newName = $args[1] $si = Get-SPServiceInstance -Server $env:COMPUTERNAME | Where-Object -FilterScript { $_.TypeName -eq $params.Name -or ` @@ -159,7 +162,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -170,17 +172,18 @@ function Test-TargetResource [System.String] $Name, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present" ) Write-Verbose -Message "Testing service instance '$Name'" + $PSBoundParameters.Ensure = $Ensure $testArgs = @{ diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPSessionStateService/MSFT_SPSessionStateService.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPSessionStateService/MSFT_SPSessionStateService.psm1 index 55e1bd788..e139a48bb 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPSessionStateService/MSFT_SPSessionStateService.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPSessionStateService/MSFT_SPSessionStateService.psm1 @@ -49,7 +49,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -77,6 +76,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting SPSessionStateService info" + if($SessionTimeout -eq 0) { $SessionTimeout = 60 @@ -155,9 +156,12 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters + Write-Verbose -Message "Testing SPSessionStateService info" + $PSBoundParameters.Ensure = $Ensure + $CurrentValues = Get-TargetResource @PSBoundParameters + if ($Ensure -eq "Present") { return Test-SPDscParameterState -CurrentValues $CurrentValues ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPShellAdmins/MSFT_SPShellAdmins.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPShellAdmins/MSFT_SPShellAdmins.psm1 index 9974fa9ca..74f5e8b46 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPShellAdmins/MSFT_SPShellAdmins.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPShellAdmins/MSFT_SPShellAdmins.psm1 @@ -33,6 +33,8 @@ function Get-TargetResource $InstallAccount ) + Write-Verbose -Message "Getting Shell Admins config" + if ($Members -and (($MembersToInclude) -or ($MembersToExclude))) { Write-Verbose -Message ("Cannot use the Members parameter together with the " + ` @@ -81,8 +83,6 @@ function Get-TargetResource return $null } - Write-Verbose -Message "Getting all Shell Admins" - $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments @($PSBoundParameters, $PSScriptRoot) ` -ScriptBlock { @@ -106,7 +106,7 @@ function Get-TargetResource $allContentDatabases = $true $cdbPermissions = @() - $databases = Get-SPDSCContentDatabase + $databases = Get-SPContentDatabase foreach ($contentDatabase in $databases) { $cdbPermission = @{} @@ -380,7 +380,7 @@ function Set-TargetResource # Check if configured database exists, throw error if not Write-Verbose -Message "Processing Content Database: $($contentDatabase.Name)" - $currentCDB = Get-SPDSCContentDatabase | Where-Object -FilterScript { + $currentCDB = Get-SPContentDatabase | Where-Object -FilterScript { $_.Name -eq $contentDatabase.Name } if ($null -ne $currentCDB) @@ -529,7 +529,7 @@ function Set-TargetResource { Write-Verbose -Message "Processing AllContentDatabases parameter" - foreach ($contentDatabase in (Get-SPDSCContentDatabase)) + foreach ($contentDatabase in (Get-SPContentDatabase)) { $dbShellAdmins = Get-SPShellAdmin -database $contentDatabase.Id if ($params.Members) @@ -679,7 +679,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -954,10 +953,4 @@ function Test-TargetResource return $true } -# This wrapepr exists as Pester tests seem to have an issue with this being called with no -# parameters. This allows us to mock the wrapper and test the logic correctly. -function Get-SPDSCContentDatabase { - return Get-SPContentDatabase -} - Export-ModuleMember -Function *-TargetResource diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPSite/MSFT_SPSite.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPSite/MSFT_SPSite.psm1 index 6b9d5ea38..81a330d77 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPSite/MSFT_SPSite.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPSite/MSFT_SPSite.psm1 @@ -137,7 +137,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -200,7 +199,7 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Creating site collection $Url" + Write-Verbose -Message "Setting site collection $Url" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -218,7 +217,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -282,8 +280,10 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters Write-Verbose -Message "Testing site collection $Url" + + $CurrentValues = Get-TargetResource @PSBoundParameters + if ($null -eq $CurrentValues) { return $false @@ -294,4 +294,3 @@ function Test-TargetResource } Export-ModuleMember -Function *-TargetResource - diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPStateServiceApp/MSFT_SPStateServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPStateServiceApp/MSFT_SPStateServiceApp.psm1 index f3067b5a8..408372727 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPStateServiceApp/MSFT_SPStateServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPStateServiceApp/MSFT_SPStateServiceApp.psm1 @@ -60,7 +60,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -92,6 +91,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting state service application '$Name'" + if ($Ensure -eq "Present") { Write-Verbose -Message "Creating State Service Application $Name" @@ -132,7 +133,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -165,13 +165,15 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters Write-Verbose -Message "Testing for state service application $Name" + $PSBoundParameters.Ensure = $Ensure + + $CurrentValues = Get-TargetResource @PSBoundParameters + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("Name", "Ensure") } - Export-ModuleMember -Function *-TargetResource diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPSubscriptionSettingsServiceApp/MSFT_SPSubscriptionSettingsServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPSubscriptionSettingsServiceApp/MSFT_SPSubscriptionSettingsServiceApp.psm1 index d6e6a33d8..3646b916b 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPSubscriptionSettingsServiceApp/MSFT_SPSubscriptionSettingsServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPSubscriptionSettingsServiceApp/MSFT_SPSubscriptionSettingsServiceApp.psm1 @@ -12,23 +12,24 @@ function Get-TargetResource [System.String] $ApplicationPool, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.String] $DatabaseName, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.String] $DatabaseServer, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount ) + Write-Verbose -Message "Getting Subscription Settings Service '$Name'" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` @@ -49,7 +50,7 @@ function Get-TargetResource return $nullReturn } $serviceApp = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "Microsoft SharePoint Foundation Subscription Settings Service Application" + $_.GetType().FullName -eq "Microsoft.SharePoint.SPSubscriptionSettingsServiceApplication" } if ($null -eq $serviceApp) @@ -71,7 +72,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -85,24 +85,26 @@ function Set-TargetResource [System.String] $ApplicationPool, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.String] $DatabaseName, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.String] $DatabaseServer, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount ) + Write-Verbose -Message "Setting Subscription Settings Service '$Name'" + $result = Get-TargetResource @PSBoundParameters if ($result.Ensure -eq "Absent" -and $Ensure -eq "Present") @@ -142,7 +144,7 @@ function Set-TargetResource $appPool = Get-SPServiceApplicationPool -Identity $params.ApplicationPool $service = Get-SPServiceApplication -Name $params.Name ` | Where-Object -FilterScript { - $_.TypeName -eq "Microsoft SharePoint Foundation Subscription Settings Service Application" + $_.GetType().FullName -eq "Microsoft.SharePoint.SPSubscriptionSettingsServiceApplication" } $service.ApplicationPool = $appPool $service.Update() @@ -159,7 +161,7 @@ function Set-TargetResource $service = Get-SPServiceApplication -Name $params.Name ` | Where-Object -FilterScript { - $_.TypeName -eq "Microsoft SharePoint Foundation Subscription Settings Service Application" + $_.GetType().FullName -eq "Microsoft.SharePoint.SPSubscriptionSettingsServiceApplication" } Remove-SPServiceApplication $service -Confirm:$false } @@ -180,28 +182,30 @@ function Test-TargetResource [System.String] $ApplicationPool, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.String] $DatabaseName, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.String] $DatabaseServer, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount ) - Write-Verbose -Message "Testing for Subscription Settings Service Application '$Name'" - $CurrentValues = Get-TargetResource @PSBoundParameters + Write-Verbose -Message "Testing Subscription Settings Service '$Name'" + $PSBoundParameters.Ensure = $Ensure + $CurrentValues = Get-TargetResource @PSBoundParameters + if ($Ensure -eq "Present") { return Test-SPDscParameterState -CurrentValues $CurrentValues ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPTimerJobState/MSFT_SPTimerJobState.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPTimerJobState/MSFT_SPTimerJobState.psm1 index 286c0dc36..6bb22384f 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPTimerJobState/MSFT_SPTimerJobState.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPTimerJobState/MSFT_SPTimerJobState.psm1 @@ -25,7 +25,7 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Getting timer job settings" + Write-Verbose -Message "Getting timer job settings for job '$Name'" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -117,7 +117,7 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Setting timer job settings" + Write-Verbose -Message "Setting timer job settings for job '$Name'" Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -242,7 +242,8 @@ function Test-TargetResource $InstallAccount ) - Write-Verbose -Message "Testing timer job settings" + Write-Verbose -Message "Testing timer job settings for job '$Name'" + $CurrentValues = Get-TargetResource @PSBoundParameters if ($null -eq $CurrentValues) diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPTrustedIdentityTokenIssuer/MSFT_SPTrustedIdentityTokenIssuer.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPTrustedIdentityTokenIssuer/MSFT_SPTrustedIdentityTokenIssuer.psm1 index 6c8d24193..c74bc10d3 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPTrustedIdentityTokenIssuer/MSFT_SPTrustedIdentityTokenIssuer.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPTrustedIdentityTokenIssuer/MSFT_SPTrustedIdentityTokenIssuer.psm1 @@ -50,7 +50,7 @@ $InstallAccount ) - Write-Verbose -Message "Getting SPTrustedIdentityTokenIssuer '$Name'..." + Write-Verbose -Message "Getting SPTrustedIdentityTokenIssuer '$Name' settings" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -157,13 +157,15 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting SPTrustedIdentityTokenIssuer '$Name' settings" + $CurrentValues = Get-TargetResource @PSBoundParameters if ($Ensure -eq "Present") { if ($CurrentValues.Ensure -eq "Absent") { - Write-Verbose -Message "Creating SPTrustedIdentityTokenIssuer '$Name'..." + Write-Verbose -Message "Creating SPTrustedIdentityTokenIssuer '$Name'" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { @@ -237,7 +239,7 @@ function Set-TargetResource if ($params.ProviderSignOutUri) { - $trust.ProviderSignOutUri = New-Object System.Uri ($params.ProviderSignOutUri) + $trust.ProviderSignOutUri = New-Object -TypeName System.Uri ($params.ProviderSignOutUri) } $trust.Update() } @@ -245,7 +247,7 @@ function Set-TargetResource } else { - Write-Verbose "Removing SPTrustedIdentityTokenIssuer '$Name'..." + Write-Verbose "Removing SPTrustedIdentityTokenIssuer '$Name'" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { @@ -275,7 +277,7 @@ function Set-TargetResource { Write-Verbose -Message ("Removing SPTrustedAuthenticationProvider " + ` "'$Name' from web app '$webAppUrl' in zone " + ` - "'$zone'...") + "'$zone'") $wa.GetIisSettingsWithFallback($zone).ClaimsAuthenticationProviders.Remove($trustedProviderToRemove) | Out-Null $update = $true } @@ -347,8 +349,10 @@ function Test-TargetResource $InstallAccount ) - Write-Verbose -Message "Testing if SPTrustedIdentityTokenIssuer '$Name' exists ..." + Write-Verbose -Message "Testing SPTrustedIdentityTokenIssuer '$Name' settings" + $CurrentValues = Get-TargetResource @PSBoundParameters + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("Ensure") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPUsageApplication/MSFT_SPUsageApplication.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPUsageApplication/MSFT_SPUsageApplication.psm1 index 83f0fcf5b..773ad7827 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPUsageApplication/MSFT_SPUsageApplication.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPUsageApplication/MSFT_SPUsageApplication.psm1 @@ -69,7 +69,7 @@ function Get-TargetResource return $nullReturn } $serviceApp = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "Usage and Health Data Collection Service Application" + $_.GetType().FullName -eq "Microsoft.SharePoint.Administration.SPUsageApplication" } if ($null -eq $serviceApp) @@ -79,7 +79,7 @@ function Get-TargetResource else { $spUsageApplicationProxy = Get-SPServiceApplicationProxy | Where-Object -FilterScript { - $_.TypeName -eq "Usage and Health Data Collection Proxy" + $_.GetType().FullName -eq "Microsoft.SharePoint.Administration.SPUsageApplicationProxy" } $ensure = "Present" @@ -107,7 +107,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -203,7 +202,7 @@ function Set-TargetResource $params = $args[0] $spUsageApplicationProxy = Get-SPServiceApplicationProxy | Where-Object -FilterScript { - $_.TypeName -eq "Usage and Health Data Collection Proxy" + $_.GetType().FullName -eq "Microsoft.SharePoint.Administration.SPUsageApplicationProxy" } if($spUsageApplicationProxy.Status -eq "Disabled") @@ -243,14 +242,13 @@ function Set-TargetResource $service = Get-SPServiceApplication -Name $params.Name ` | Where-Object -FilterScript { - $_.TypeName -eq "Usage and Health Data Collection Service Application" + $_.GetType().FullName -eq "Microsoft.SharePoint.Administration.SPUsageApplication" } Remove-SPServiceApplication $service -Confirm:$false } } } - function Test-TargetResource { [CmdletBinding()] @@ -303,9 +301,12 @@ function Test-TargetResource $UsageLogMaxSpaceGB ) - $CurrentValues = Get-TargetResource @PSBoundParameters Write-Verbose -Message "Testing for usage application '$Name'" + $PSBoundParameters.Ensure = $Ensure + + $CurrentValues = Get-TargetResource @PSBoundParameters + if ($Ensure -eq "Present") { return Test-SPDscParameterState -CurrentValues $CurrentValues ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileProperty/MSFT_SPUserProfileProperty.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileProperty/MSFT_SPUserProfileProperty.psm1 index 9957aca76..a5a5abcc1 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileProperty/MSFT_SPUserProfileProperty.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileProperty/MSFT_SPUserProfileProperty.psm1 @@ -120,7 +120,7 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Getting user profile service application $Name" + Write-Verbose -Message "Getting user profile property $Name" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -139,13 +139,11 @@ function Get-TargetResource return $nullReturn } - $caURL = (Get-SpWebApplication -IncludeCentralAdministration | Where-Object -FilterScript { + $caURL = (Get-SPWebApplication -IncludeCentralAdministration | Where-Object -FilterScript { $_.IsAdministrationWebApplication -eq $true }).Url $context = Get-SPServiceContext -Site $caURL - $userProfileConfigManager = New-Object -TypeName "Microsoft.Office.Server.UserProfiles.UserProfileConfigManager" ` - -ArgumentList $context $userProfileSubTypeManager = Get-SPDSCUserProfileSubTypeManager -Context $context $userProfileSubType = $userProfileSubTypeManager.GetProfileSubtype("UserProfile") @@ -173,6 +171,9 @@ function Get-TargetResource PropertyName ="" Direction = "" } + + $userProfileConfigManager = New-Object -TypeName "Microsoft.Office.Server.UserProfiles.UserProfileConfigManager" ` + -ArgumentList $context $syncConnection = $userProfileConfigManager.ConnectionManager | ` Where-Object -FilterScript { $null -ne $_.PropertyMapping.Item($params.Name) @@ -347,7 +348,8 @@ function Set-TargetResource # Note for integration test: CA can take a couple of minutes to notice the change. don't try # refreshing properties page. Go through from a fresh "flow" from Service apps page - Write-Verbose -Message "Creating user profile property $Name" + Write-Verbose -Message "Setting user profile property $Name" + $PSBoundParameters.Ensure = $Ensure $test = $PSBoundParameters @@ -383,7 +385,7 @@ function Set-TargetResource return $null } - $caURL = (Get-SpWebApplication -IncludeCentralAdministration | Where-Object -FilterScript { + $caURL = (Get-SPWebApplication -IncludeCentralAdministration | Where-Object -FilterScript { $_.IsAdministrationWebApplication -eq $true }).Url $context = Get-SPServiceContext $caURL @@ -398,13 +400,8 @@ function Set-TargetResource } $coreProperties = $userProfileConfigManager.ProfilePropertyManager.GetCoreProperties() - $userProfilePropertyManager = $userProfileConfigManager.ProfilePropertyManager - $userProfileTypeProperties = $userProfilePropertyManager.GetProfileTypeProperties([Microsoft.Office.Server.UserProfiles.ProfileType]::User) - $userProfileSubTypeManager = Get-SPDSCUserProfileSubTypeManager $context $userProfileSubType = $userProfileSubTypeManager.GetProfileSubtype("UserProfile") - - $userProfileSubTypeProperties = $userProfileSubType.Properties $userProfileProperty = $userProfileSubType.Properties.GetPropertyByName($params.Name) @@ -419,11 +416,11 @@ function Set-TargetResource if ($params.ContainsKey("TermSet")) { - $currentTermSet=$userProfileProperty.CoreProperty.TermSet; + $currentTermSet = $userProfileProperty.CoreProperty.TermSet; if($currentTermSet.Name -ne $params.TermSet -or $currentTermSet.Group.Name -ne $params.TermGroup -or - $currentTermSet.TermStore.Name -ne $params.TermStore){ - + $currentTermSet.TermStore.Name -ne $params.TermStore) + { $session = New-Object -TypeName Microsoft.SharePoint.Taxonomy.TaxonomySession ` -ArgumentList $caURL @@ -479,6 +476,10 @@ function Set-TargetResource $coreProperty.TermSet = $termSet } + $userProfilePropertyManager = $userProfileConfigManager.ProfilePropertyManager + $userProfileTypeProperties = $userProfilePropertyManager.GetProfileTypeProperties([Microsoft.Office.Server.UserProfiles.ProfileType]::User) + $userProfileSubTypeProperties = $userProfileSubType.Properties + $CoreProperties.Add($coreProperty) $upTypeProperty = $userProfileTypeProperties.Create($coreProperty) $userProfileTypeProperties.Add($upTypeProperty) @@ -737,9 +738,12 @@ function Test-TargetResource ) - $CurrentValues = Get-TargetResource @PSBoundParameters Write-Verbose -Message "Testing for user profile property $Name" + $PSBoundParameters.Ensure = $Ensure + + $CurrentValues = Get-TargetResource @PSBoundParameters + if ($Ensure -eq "Present") { return Test-SPDscParameterState -CurrentValues $CurrentValues ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileSection/MSFT_SPUserProfileSection.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileSection/MSFT_SPUserProfileSection.psm1 index 951b05687..d0cce7b4e 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileSection/MSFT_SPUserProfileSection.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileSection/MSFT_SPUserProfileSection.psm1 @@ -30,7 +30,7 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Getting user profile service application $Name" + Write-Verbose -Message "Getting user profile section $Name" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -109,9 +109,10 @@ function Set-TargetResource # note for integration test: CA can take a couple of minutes to notice the change. # don't try refreshing properties page. go through from a fresh "flow" from Service apps page + Write-Verbose -Message "Setting user profile section $Name" + $PSBoundParameters.Ensure = $Ensure - Write-Verbose -Message "Creating user profile property $Name" Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { @@ -208,13 +209,17 @@ function Test-TargetResource ) + Write-Verbose -Message "Testing user profile section $Name" + + $PSBoundParameters.Ensure = $Ensure + $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing for user profile property $Name" + if ($null -eq $CurrentValues) { return $false } - $PSBoundParameters.Ensure = $Ensure + if ($Ensure -eq "Present") { return Test-SPDscParameterState -CurrentValues $CurrentValues ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileServiceApp/MSFT_SPUserProfileServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileServiceApp/MSFT_SPUserProfileServiceApp.psm1 index 513b56d22..057381434 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileServiceApp/MSFT_SPUserProfileServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileServiceApp/MSFT_SPUserProfileServiceApp.psm1 @@ -79,7 +79,7 @@ function Get-TargetResource return $nullReturn } $serviceApp = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "User Profile Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Server.Administration.UserProfileApplication" } if ($null -eq $serviceApp) @@ -214,6 +214,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting user profile service application $Name" + if ($Ensure -eq "Present") { if ($PSBoundParameters.ContainsKey("FarmAccount") -eq $false) @@ -312,16 +314,25 @@ function Set-TargetResource $params = $args[0] - $service = Get-SPServiceApplication -Name $params.Name ` + $app = Get-SPServiceApplication -Name $params.Name ` | Where-Object -FilterScript { - $_.TypeName -eq "User Profile Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Server.Administration.UserProfileApplication" } - Remove-SPServiceApplication $service -Confirm:$false + + $proxies = Get-SPServiceApplicationProxy + foreach($proxyInstance in $proxies) + { + if($app.IsConnected($proxyInstance)) + { + $proxyInstance.Delete() + } + } + + Remove-SPServiceApplication -Identity $app -Confirm:$false } } } - function Test-TargetResource { [CmdletBinding()] @@ -386,10 +397,12 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters Write-Verbose -Message "Testing for user profile service application $Name" + $PSBoundParameters.Ensure = $Ensure + $CurrentValues = Get-TargetResource @PSBoundParameters + if($Ensure -eq "Present") { return Test-SPDscParameterState -CurrentValues $CurrentValues ` @@ -405,4 +418,3 @@ function Test-TargetResource } Export-ModuleMember -Function *-TargetResource - diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileServiceAppPermissions/MSFT_SPUserProfileServiceAppPermissions.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileServiceAppPermissions/MSFT_SPUserProfileServiceAppPermissions.psm1 index 2a739524d..6ffb27974 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileServiceAppPermissions/MSFT_SPUserProfileServiceAppPermissions.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileServiceAppPermissions/MSFT_SPUserProfileServiceAppPermissions.psm1 @@ -25,10 +25,10 @@ function Get-TargetResource $InstallAccount ) - Confirm-SPDscUpaPermissionsConfig -Parameters $PSBoundParameters - Write-Verbose -Message "Getting permissions for user profile service proxy '$ProxyName" + Confirm-SPDscUpaPermissionsConfig -Parameters $PSBoundParameters + $result = Invoke-SPDSCCommand -Credential $InstallAccount -Arguments $PSBoundParameters -ScriptBlock { $params = $args[0] @@ -137,6 +137,7 @@ function Set-TargetResource ) Write-Verbose -Message "Setting permissions for user profile service proxy '$ProxyName" + Confirm-SPDscUpaPermissionsConfig -Parameters $PSBoundParameters $CurrentValues = Get-TargetResource @PSBoundParameters @@ -330,6 +331,7 @@ function Test-TargetResource Confirm-SPDscUpaPermissionsConfig -Parameters $PSBoundParameters $CurrentValues = Get-TargetResource @PSBoundParameters + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("CreatePersonalSite", ` diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileSyncConnection/MSFT_SPUserProfileSyncConnection.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileSyncConnection/MSFT_SPUserProfileSyncConnection.psm1 index c0738e0bb..94b8d4883 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileSyncConnection/MSFT_SPUserProfileSyncConnection.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileSyncConnection/MSFT_SPUserProfileSyncConnection.psm1 @@ -50,7 +50,7 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Getting user profile service sync connection $ConnectionDomain" + Write-Verbose -Message "Getting user profile service sync connection $Name" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -152,7 +152,7 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Creating user profile service application $Name" + Write-Verbose -Message "Setting user profile service sync connection $Name" Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments @($PSBoundParameters, $PSScriptRoot) ` @@ -287,8 +287,6 @@ function Set-TargetResource } } - - function Test-TargetResource { [CmdletBinding()] @@ -341,16 +339,20 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters Write-Verbose -Message "Testing for user profile service sync connection $Name" + + $CurrentValues = Get-TargetResource @PSBoundParameters + if ($null -eq $CurrentValues) { return $false } + if ($Force -eq $true) { return $false } + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("Name", @@ -382,7 +384,7 @@ function New-SPDSCDirectoryServiceNamingContext function New-SPDSCDirectoryServiceNamingContextList { param () - return New-Object System.Collections.Generic.List[[Microsoft.Office.Server.UserProfiles.DirectoryServiceNamingContext]] + return New-Object -TypeName System.Collections.Generic.List[[Microsoft.Office.Server.UserProfiles.DirectoryServiceNamingContext]] } Export-ModuleMember -Function *-TargetResource, Get-SPDSCADSIObject, New-SPDSCDirectoryServiceNamingContext, New-SPDSCDirectoryServiceNamingContextList diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileSyncService/MSFT_SPUserProfileSyncService.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileSyncService/MSFT_SPUserProfileSyncService.psm1 index 8d50e8467..46f7f4713 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileSyncService/MSFT_SPUserProfileSyncService.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPUserProfileSyncService/MSFT_SPUserProfileSyncService.psm1 @@ -8,7 +8,7 @@ function Get-TargetResource [System.String] $UserProfileServiceAppName, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", @@ -16,7 +16,7 @@ function Get-TargetResource [System.Management.Automation.PSCredential] $FarmAccount, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.Boolean] $RunOnlyWhenWriteable, @@ -25,30 +25,45 @@ function Get-TargetResource $InstallAccount ) + Write-Verbose -Message "Getting user profile sync service for $UserProfileServiceAppName" + if ((Get-SPDSCInstalledProductVersion).FileMajorPart -ne 15) { throw [Exception] ("Only SharePoint 2013 is supported to deploy the user profile sync " + ` "service via DSC, as 2016 does not use the FIM based sync service.") } - Write-Verbose -Message "Getting the local user profile sync service instance" - $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { $params = $args[0] - $syncService = Get-SPServiceInstance -Server $env:COMPUTERNAME ` - | Where-Object -FilterScript { - $_.TypeName -eq "User Profile Synchronization Service" + $syncServices = Get-SPServiceInstance -Server $env:COMPUTERNAME ` + -ErrorAction SilentlyContinue + + if ($null -eq $syncServices) + { + return @{ + UserProfileServiceAppName = $params.UserProfileServiceAppName + Ensure = "Absent" + FarmAccount = $params.FarmAccount + RunOnlyWhenWriteable = $params.RunOnlyWhenWriteable + InstallAccount = $params.InstallAccount + } + } + + $syncService = $syncServices | Where-Object -FilterScript { + $_.GetType().Name -eq "UserProfileServiceInstance" } + if ($null -eq $syncService) { $domain = (Get-CimInstance -ClassName Win32_ComputerSystem).Domain $currentServer = "$($env:COMPUTERNAME).$domain" - $syncService = Get-SPServiceInstance -Server $currentServer ` - | Where-Object -FilterScript { - $_.TypeName -eq "User Profile Synchronization Service" + $syncServices = Get-SPServiceInstance -Server $currentServer ` + -ErrorAction SilentlyContinue + $syncService = $syncServices | Where-Object -FilterScript { + $_.GetType().Name -eq "UserProfileServiceInstance" } } @@ -109,7 +124,7 @@ function Set-TargetResource [System.String] $UserProfileServiceAppName, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", @@ -117,7 +132,7 @@ function Set-TargetResource [System.Management.Automation.PSCredential] $FarmAccount, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.Boolean] $RunOnlyWhenWriteable, @@ -126,7 +141,10 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting user profile sync service for $UserProfileServiceAppName" + $PSBoundParameters.Ensure = $Ensure + if ((Get-SPDSCInstalledProductVersion).FileMajorPart -ne 15) { throw [Exception] ("Only SharePoint 2013 is supported to deploy the user profile sync " + ` @@ -151,8 +169,6 @@ function Set-TargetResource } } - Write-Verbose -Message "Setting User Profile Synchronization Service" - # Add the FarmAccount to the local Admins group, if it's not already there $isLocalAdmin = Test-SPDSCUserIsLocalAdmin -UserName $FarmAccount.UserName @@ -170,17 +186,18 @@ function Set-TargetResource $params = $args[0] $currentServer = $env:COMPUTERNAME - $syncService = Get-SPServiceInstance -Server $currentServer ` - | Where-Object -FilterScript { - $_.TypeName -eq "User Profile Synchronization Service" + + $syncServices = Get-SPServiceInstance -Server $currentServer ` + -ErrorAction SilentlyContinue + $syncService = $syncServices | Where-Object -FilterScript { + $_.GetType().Name -eq "UserProfileServiceInstance" } if ($null -eq $syncService) { $domain = (Get-CimInstance -ClassName Win32_ComputerSystem).Domain $currentServer = "$currentServer.$domain" - $syncService = Get-SPServiceInstance -Server $currentServer ` - | Where-Object -FilterScript { - $_.TypeName -eq "User Profile Synchronization Service" + $syncService = $syncServices | Where-Object -FilterScript { + $_.GetType().Name -eq "UserProfileServiceInstance" } } if ($null -eq $syncService) @@ -195,10 +212,10 @@ function Set-TargetResource -ErrorAction SilentlyContinue if ($null -eq $serviceApps) { throw [Exception] ("No user profile service was found " + ` - "named $($params.UserProfileServiceAppName)") + "named $($params.UserProfileServiceAppName)") } $ups = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "User Profile Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Server.Administration.UserProfileApplication" } $userName = $params.FarmAccount.UserName @@ -229,9 +246,8 @@ function Set-TargetResource Write-Verbose ("$([DateTime]::Now.ToShortTimeString()) - Waiting for user profile " + ` "sync service to become '$desiredState' (waited $count of " + ` "$maxCount minutes)") - $syncService = Get-SPServiceInstance -Server $currentServer ` - | Where-Object -FilterScript { - $_.TypeName -eq "User Profile Synchronization Service" + $syncService = $syncServices | Where-Object -FilterScript { + $_.GetType().Name -eq "UserProfileServiceInstance" } $count++ } @@ -257,7 +273,7 @@ function Test-TargetResource [System.String] $UserProfileServiceAppName, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", @@ -265,7 +281,7 @@ function Test-TargetResource [System.Management.Automation.PSCredential] $FarmAccount, - [parameter(Mandatory = $false)] + [parameter(Mandatory = $false)] [System.Boolean] $RunOnlyWhenWriteable, @@ -274,6 +290,10 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing user profile sync service for $UserProfileServiceAppName" + + $PSBoundParameters.Ensure = $Ensure + if ((Get-SPDSCInstalledProductVersion).FileMajorPart -ne 15) { throw [Exception] ("Only SharePoint 2013 is supported to deploy the user profile sync " + ` @@ -281,7 +301,7 @@ function Test-TargetResource } $CurrentValues = Get-TargetResource @PSBoundParameters - $PSBoundParameters.Ensure = $Ensure + if ($PSBoundParameters.ContainsKey("RunOnlyWhenWriteable") -eq $true) { $databaseReadOnly = Test-SPDscUserProfileDBReadOnly ` @@ -332,7 +352,7 @@ function Test-SPDscUserProfileDBReadOnly() "named $UserProfileServiceAppName") } $ups = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "User Profile Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Server.Administration.UserProfileApplication" } $propType = $ups.GetType() diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPVisioServiceApp/MSFT_SPVisioServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPVisioServiceApp/MSFT_SPVisioServiceApp.psm1 index bba746fc8..e0682617f 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPVisioServiceApp/MSFT_SPVisioServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPVisioServiceApp/MSFT_SPVisioServiceApp.psm1 @@ -12,6 +12,10 @@ function Get-TargetResource [System.String] $ApplicationPool, + [parameter(Mandatory = $false)] + [System.String] + $ProxyName, + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] @@ -41,7 +45,7 @@ function Get-TargetResource return $nullReturn } $serviceApp = $serviceApps | Where-Object -FilterScript { - $_.TypeName -eq "Visio Graphics Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Visio.Server.Administration.VisioGraphicsServiceApplication" } if ($null -eq $serviceApp) @@ -74,6 +78,10 @@ function Set-TargetResource [System.String] $ApplicationPool, + [parameter(Mandatory = $false)] + [System.String] + $ProxyName, + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] @@ -84,6 +92,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting Visio Graphics service app '$Name'" + $result = Get-TargetResource @PSBoundParameters if ($result.Ensure -eq "Absent" -and $Ensure -eq "Present") @@ -94,8 +104,21 @@ function Set-TargetResource -ScriptBlock { $params = $args[0] - New-SPVisioServiceApplication -Name $params.Name ` + $visioApp = New-SPVisioServiceApplication -Name $params.Name ` -ApplicationPool $params.ApplicationPool + if ($params.ContainsKey("ProxyName")) + { + $pName = $params.ProxyName + $params.Remove("ProxyName") | Out-Null + } + + if ($null -eq $pName) { + $pName = "$($params.Name) Proxy" + } + if ($null -ne $visioApp) + { + $visioProxy = New-SPVisioServiceApplicationProxy -Name $pName -ServiceApplication $params.Name + } } } if ($result.Ensure -eq "Present" -and $Ensure -eq "Present") @@ -112,7 +135,7 @@ function Set-TargetResource Get-SPServiceApplication -Name $params.Name ` | Where-Object -FilterScript { - $_.TypeName -eq "Visio Graphics Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Visio.Server.Administration.VisioGraphicsServiceApplication" } | Set-SPVisioServiceApplication -ServiceApplicationPool $appPool } } @@ -126,11 +149,21 @@ function Set-TargetResource -ScriptBlock { $params = $args[0] - $service = Get-SPServiceApplication -Name $params.Name ` + $app = Get-SPServiceApplication -Name $params.Name ` | Where-Object -FilterScript { - $_.TypeName -eq "Visio Graphics Service Application" + $_.GetType().FullName -eq "Microsoft.Office.Visio.Server.Administration.VisioGraphicsServiceApplication" } - Remove-SPServiceApplication $service -Confirm:$false + + $proxies = Get-SPServiceApplicationProxy + foreach($proxyInstance in $proxies) + { + if($app.IsConnected($proxyInstance)) + { + $proxyInstance.Delete() + } + } + + Remove-SPServiceApplication -Identity $app -Confirm:$false } } } @@ -149,6 +182,10 @@ function Test-TargetResource [System.String] $ApplicationPool, + [parameter(Mandatory = $false)] + [System.String] + $ProxyName, + [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] @@ -159,9 +196,12 @@ function Test-TargetResource $InstallAccount ) - Write-Verbose -Message "Testing for Visio Graphics Service Application '$Name'" - $CurrentValues = Get-TargetResource @PSBoundParameters + Write-Verbose -Message "Testing Visio Graphics service app '$Name'" + $PSBoundParameters.Ensure = $Ensure + + $CurrentValues = Get-TargetResource @PSBoundParameters + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("ApplicationPool", "Ensure") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPVisioServiceApp/MSFT_SPVisioServiceApp.schema.mof b/Modules/SharePointDsc/DSCResources/MSFT_SPVisioServiceApp/MSFT_SPVisioServiceApp.schema.mof index 8dea70a7d..a6f716584 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPVisioServiceApp/MSFT_SPVisioServiceApp.schema.mof +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPVisioServiceApp/MSFT_SPVisioServiceApp.schema.mof @@ -3,6 +3,7 @@ class MSFT_SPVisioServiceApp : OMI_BaseResource { [Key, Description("The name of the service application")] string Name; [Required, Description("The name of the application pool to run the service app in")] string ApplicationPool; + [Write, Description("The name of the Visio Service Application Proxy")] string ProxyName; [Write, Description("Present if the service app should exist, absent if it should not"), ValueMap{"Present","Absent"}, Values{"Present","Absent"}] string Ensure; [Write, Description("POWERSHELL 4 ONLY: The account to run this resource as, use PsDscRunAsCredential if using PowerShell 5"), EmbeddedInstance("MSFT_Credential")] String InstallAccount; }; diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPWeb/MSFT_SPWeb.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPWeb/MSFT_SPWeb.psm1 index f9e1658bb..0ae2dc4e1 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPWeb/MSFT_SPWeb.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPWeb/MSFT_SPWeb.psm1 @@ -85,7 +85,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -137,7 +136,7 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Creating SPWeb '$Url'" + Write-Verbose -Message "Setting SPWeb '$Url'" $PSBoundParameters.Ensure = $Ensure @@ -211,7 +210,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -264,12 +262,12 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing SPWeb '$Url'" + $PSBoundParameters.Ensure = $Ensure $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing SPWeb '$Url'" - $valuesToCheck = @("Url", "Name", "Description", diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppBlockedFileTypes/MSFT_SPWebAppBlockedFileTypes.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppBlockedFileTypes/MSFT_SPWebAppBlockedFileTypes.psm1 index a608b7403..b5e2d43c9 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppBlockedFileTypes/MSFT_SPWebAppBlockedFileTypes.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppBlockedFileTypes/MSFT_SPWebAppBlockedFileTypes.psm1 @@ -75,6 +75,7 @@ function Set-TargetResource ) Write-Verbose -Message "Setting web application '$Url' blocked file types" + $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments @($PSBoundParameters,$PSScriptRoot) ` -ScriptBlock { @@ -95,7 +96,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -123,9 +123,14 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters Write-Verbose -Message "Testing for web application '$Url' blocked file types" - if ($null -eq $CurrentValues) { return $false } + + $CurrentValues = Get-TargetResource @PSBoundParameters + + if ($null -eq $CurrentValues) + { + return $false + } $modulePath = "..\..\Modules\SharePointDsc.WebApplication\SPWebApplication.BlockedFileTypes.psm1" Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath $modulePath -Resolve) @@ -134,5 +139,4 @@ function Test-TargetResource -DesiredSettings $PSBoundParameters } - Export-ModuleMember -Function *-TargetResource diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppGeneralSettings/MSFT_SPWebAppGeneralSettings.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppGeneralSettings/MSFT_SPWebAppGeneralSettings.psm1 index e544654aa..fdb8f6672 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppGeneralSettings/MSFT_SPWebAppGeneralSettings.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppGeneralSettings/MSFT_SPWebAppGeneralSettings.psm1 @@ -115,7 +115,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -207,7 +206,7 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Applying general settings '$Url'" + Write-Verbose -Message "Setting web application '$url' general settings" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments @($PSBoundParameters,$PSScriptRoot) ` @@ -230,7 +229,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -323,8 +321,10 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing web application '$url' general settings" + $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing for web application general settings '$Url'" + if ($null -eq $CurrentValues) { return $false @@ -336,6 +336,4 @@ function Test-TargetResource return Test-SPDSCWebApplicationGeneralConfig -CurrentSettings $CurrentValues -DesiredSettings $PSBoundParameters } - Export-ModuleMember -Function *-TargetResource - diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppPermissions/MSFT_SPWebAppPermissions.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppPermissions/MSFT_SPWebAppPermissions.psm1 index c372a00ba..b7d3e05cb 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppPermissions/MSFT_SPWebAppPermissions.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppPermissions/MSFT_SPWebAppPermissions.psm1 @@ -42,6 +42,7 @@ function Get-TargetResource ) Write-Verbose -Message "Getting permissions for Web Application '$WebAppUrl'" + Test-SPDSCInput @PSBoundParameters $result = Invoke-SPDSCCommand -Credential $InstallAccount ` @@ -231,7 +232,9 @@ function Set-TargetResource [System.Management.Automation.PSCredential] $InstallAccount ) + Write-Verbose -Message "Setting permissions for Web Application '$WebAppUrl'" + Test-SPDSCInput @PSBoundParameters $result = Get-TargetResource @PSBoundParameters @@ -439,6 +442,7 @@ function Test-TargetResource ) Write-Verbose -Message "Testing permissions for Web Application '$WebAppUrl'" + Test-SPDSCInput @PSBoundParameters $CurrentValues = Get-TargetResource @PSBoundParameters diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppPolicy/MSFT_SPWebAppPolicy.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppPolicy/MSFT_SPWebAppPolicy.psm1 index d2a5cd216..f188bf7f1 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppPolicy/MSFT_SPWebAppPolicy.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppPolicy/MSFT_SPWebAppPolicy.psm1 @@ -29,6 +29,8 @@ function Get-TargetResource $InstallAccount ) + Write-Verbose -Message "Getting web app policy for $WebAppUrl" + if ($Members -and (($MembersToInclude) -or ($MembersToExclude))) { Write-Verbose -Message ("Cannot use the Members parameter together with " + ` @@ -66,8 +68,6 @@ function Get-TargetResource } } - Write-Verbose -Message "Getting web app policy for $UserName at $WebAppUrl" - $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { @@ -82,7 +82,7 @@ function Get-TargetResource } $SetCacheAccountsPolicy = $false - if ($param.SetCacheAccountsPolicy) + if ($params.SetCacheAccountsPolicy) { if (($wa.Properties.ContainsKey("portalsuperuseraccount") -eq $true) -and ` ($wa.Properties.ContainsKey("portalsuperreaderaccount") -eq $true)) @@ -160,7 +160,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -191,7 +190,7 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Setting web app policy for $UserName at $WebAppUrl" + Write-Verbose -Message "Setting web app policy for $WebAppUrl" if ($Members -and (($MembersToInclude) -or ($MembersToExclude))) { @@ -565,10 +564,10 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing web app policy for $WebAppUrl" + $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing web app policy for '$WebAppUrl'" - $modulePath = "..\..\Modules\SharePointDsc.WebAppPolicy\SPWebAppPolicy.psm1" Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath $modulePath -Resolve) diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppProxyGroup/MSFT_SPWebAppProxyGroup.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppProxyGroup/MSFT_SPWebAppProxyGroup.psm1 index a93039ecb..f63330d9c 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppProxyGroup/MSFT_SPWebAppProxyGroup.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppProxyGroup/MSFT_SPWebAppProxyGroup.psm1 @@ -125,3 +125,5 @@ function Test-TargetResource return $false } } + +Export-ModuleMember -Function *-TargetResource diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppSiteUseAndDeletion/MSFT_SPWebAppSiteUseAndDeletion.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppSiteUseAndDeletion/MSFT_SPWebAppSiteUseAndDeletion.psm1 index 8513222be..83bf936c2 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppSiteUseAndDeletion/MSFT_SPWebAppSiteUseAndDeletion.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppSiteUseAndDeletion/MSFT_SPWebAppSiteUseAndDeletion.psm1 @@ -69,7 +69,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -103,7 +102,6 @@ function Set-TargetResource Write-Verbose -Message "Setting web application '$Url' Site Use and Deletion settings" - Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { @@ -154,7 +152,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -187,8 +184,10 @@ function Test-TargetResource $InstallAccount ) - Write-Verbose -Message "Testing for web application '$Url' Site Use and Deletion" + Write-Verbose -Message "Testing web application '$url' site use and deletion settings" + $CurrentValues = Get-TargetResource @PSBoundParameters + if ($null -eq $CurrentValues) { return $false diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppThrottlingSettings/MSFT_SPWebAppThrottlingSettings.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppThrottlingSettings/MSFT_SPWebAppThrottlingSettings.psm1 index ee47a51c6..bfcd8103c 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppThrottlingSettings/MSFT_SPWebAppThrottlingSettings.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppThrottlingSettings/MSFT_SPWebAppThrottlingSettings.psm1 @@ -81,7 +81,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -141,7 +140,9 @@ function Set-TargetResource ) Write-Verbose -Message "Setting web application '$Url' throttling settings" + $paramArgs = @($PSBoundParameters,$PSScriptRoot) + $result = Invoke-SPDSCCommand -Credential $InstallAccount -Arguments $paramArgs -ScriptBlock { $params = $args[0] $ScriptRoot = $args[1] @@ -168,7 +169,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -228,8 +228,10 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing web application '$url' throttling settings" + $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing for web application '$Url' throttling settings" + if ($null -eq $CurrentValues) { return $false diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppWorkflowSettings/MSFT_SPWebAppWorkflowSettings.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppWorkflowSettings/MSFT_SPWebAppWorkflowSettings.psm1 index 9aa590bc5..2c6484ea2 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppWorkflowSettings/MSFT_SPWebAppWorkflowSettings.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPWebAppWorkflowSettings/MSFT_SPWebAppWorkflowSettings.psm1 @@ -50,7 +50,6 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] @@ -96,7 +95,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -124,8 +122,10 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing web application '$Url' workflow settings" + $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing for web application '$Url' workflow settings" + if ($null -eq $CurrentValues) { return $false } $relPath = "..\..\Modules\SharePointDsc.WebApplication\SPWebApplication.Workflow.psm1" @@ -134,5 +134,4 @@ function Test-TargetResource -DesiredSettings $PSBoundParameters } - Export-ModuleMember -Function *-TargetResource diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPWebApplication/MSFT_SPWebApplication.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPWebApplication/MSFT_SPWebApplication.psm1 index 7138961ed..db8cb1a07 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPWebApplication/MSFT_SPWebApplication.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPWebApplication/MSFT_SPWebApplication.psm1 @@ -63,7 +63,7 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Getting web application '$Name'" + Write-Verbose -Message "Getting web application '$Name' config" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments @($PSBoundParameters,$PSScriptRoot) ` @@ -101,11 +101,11 @@ function Get-TargetResource AllowAnonymous = $authProvider.AllowAnonymous DatabaseName = $wa.ContentDatabases[0].Name DatabaseServer = $wa.ContentDatabases[0].Server - HostHeader = (New-Object System.Uri $wa.Url).Host + HostHeader = (New-Object -TypeName System.Uri $wa.Url).Host Path = $wa.IisSettings[0].Path - Port = (New-Object System.Uri $wa.Url).Port + Port = (New-Object -TypeName System.Uri $wa.Url).Port AuthenticationMethod = $localAuthMode - UseSSL = (New-Object System.Uri $wa.Url).Scheme -eq "https" + UseSSL = (New-Object -TypeName System.Uri $wa.Url).Scheme -eq "https" InstallAccount = $params.InstallAccount Ensure = "Present" } @@ -178,7 +178,7 @@ function Set-TargetResource $InstallAccount ) - Write-Verbose -Message "Creating web application '$Name'" + Write-Verbose -Message "Setting web application '$Name' config" if ($Ensure -eq "Present") { @@ -295,7 +295,6 @@ function Set-TargetResource } } - function Test-TargetResource { [CmdletBinding()] @@ -361,15 +360,16 @@ function Test-TargetResource $InstallAccount ) - $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing for web application '$Name'" + Write-Verbose -Message "Testing for web application '$Name' config" + $PSBoundParameters.Ensure = $Ensure + + $CurrentValues = Get-TargetResource @PSBoundParameters + $testReturn = Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("Ensure") return $testReturn } - Export-ModuleMember -Function *-TargetResource - diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPWebApplicationAppDomain/MSFT_SPWebApplicationAppDomain.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPWebApplicationAppDomain/MSFT_SPWebApplicationAppDomain.psm1 index 1e365215a..8ac2d4712 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPWebApplicationAppDomain/MSFT_SPWebApplicationAppDomain.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPWebApplicationAppDomain/MSFT_SPWebApplicationAppDomain.psm1 @@ -30,7 +30,7 @@ function Get-TargetResource $InstallAccount ) - Write-Verbose -Message "Checking app urls settings" + Write-Verbose -Message "Getting app domain settings for '$AppDomain'" $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` @@ -89,8 +89,9 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting app domain settings for '$AppDomain'" + $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Updating app domain settings " Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments @($PSBoundParameters, $CurrentValues) ` @@ -155,12 +156,15 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing app domain settings for '$AppDomain'" + $CurrentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message "Testing app domain settings" + if ($null -eq $CurrentValues) { return $false } + return Test-SPDscParameterState -CurrentValues $CurrentValues ` -DesiredValues $PSBoundParameters ` -ValuesToCheck @("AppDomain", "Port", "SSL") diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPWordAutomationServiceApp/MSFT_SPWordAutomationServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPWordAutomationServiceApp/MSFT_SPWordAutomationServiceApp.psm1 index ddbce4fbf..6c7fb3d99 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPWordAutomationServiceApp/MSFT_SPWordAutomationServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPWordAutomationServiceApp/MSFT_SPWordAutomationServiceApp.psm1 @@ -93,7 +93,9 @@ function Get-TargetResource ) Write-Verbose -Message "Getting Word Automation service app '$Name'" + $PSBoundParameters.Ensure = $Ensure + if (($ApplicationPool ` -or $DatabaseName ` -or $DatabaseServer ` @@ -124,85 +126,74 @@ function Get-TargetResource $result = Invoke-SPDSCCommand -Credential $InstallAccount ` -Arguments $PSBoundParameters ` -ScriptBlock { - $params = $args[0] - - $serviceApp = Get-SPServiceApplication ` - -Name $params.Name ` - -ErrorAction SilentlyContinue | Where-Object -FilterScript { - $_.TypeName -eq "Word Automation Services" - } - - switch ($params.Ensure) - { - "Present" { - if ($null -eq $serviceApp) - { - return $null - } - else - { - $supportedFileFormats = @() - if ($serviceApp.WordServiceFormats.OpenXmlDocument) - { - $supportedFileFormats += "docx" - } - if ($serviceApp.WordServiceFormats.Word972003Document) - { - $supportedFileFormats += "doc" - } - if ($serviceApp.WordServiceFormats.RichTextFormat) - { - $supportedFileFormats += "rtf" - } - if ($serviceApp.WordServiceFormats.WebPage) - { - $supportedFileFormats += "mht" - } - if ($serviceApp.WordServiceFormats.Word2003Xml) - { - $supportedFileFormats += "xml" - } + $params = $args[0] + + $serviceApps = Get-SPServiceApplication -Name $params.Name ` + -ErrorAction SilentlyContinue + $nullReturn = @{ + Name = $params.Name + Ensure = "Absent" + ApplicationPool = $params.ApplicationPool + } - $returnVal = @{ - Name = $serviceApp.DisplayName - Ensure = $params.Ensure - ApplicationPool = $serviceApp.ApplicationPool.Name - DatabaseName = $serviceApp.Database.Name - DatabaseServer = $serviceApp.Database.Server.Name - SupportedFileFormats = $supportedFileFormats - DisableEmbeddedFonts = $serviceApp.DisableEmbeddedFonts - MaximumMemoryUsage = $serviceApp.MaximumMemoryUsage - RecycleThreshold = $serviceApp.RecycleProcessThreshold - DisableBinaryFileScan = $serviceApp.DisableBinaryFileScan - ConversionProcesses = $serviceApp.TotalActiveProcesses - JobConversionFrequency = $serviceApp.TimerJobFrequency.TotalMinutes - NumberOfConversionsPerProcess = $serviceApp.ConversionsPerInstance - TimeBeforeConversionIsMonitored = $serviceApp.ConversionTimeout.TotalMinutes - MaximumConversionAttempts = $serviceApp.MaximumConversionAttempts - MaximumSyncConversionRequests = $serviceApp.MaximumSyncConversionRequests - KeepAliveTimeout = $serviceApp.KeepAliveTimeout.TotalSeconds - MaximumConversionTime = $serviceApp.MaximumConversionTime.TotalSeconds - InstallAccount = $params.InstallAccount - } - return $returnVal - } - } - "Absent" { - if ($null -ne $serviceApp) - { - return $null - } - else - { - $returnVal = @{ - Name = $params.Name - Ensure = $params.Ensure - InstallAccount = $params.InstallAccount - } - return $returnVal - } - } + if ($null -eq $serviceApps) + { + return $nullReturn + } + + $serviceApp = $serviceApps | Where-Object -FilterScript { + $_.GetType().FullName -eq "Microsoft.Office.Word.Server.Service.WordServiceApplication" + } + + if ($null -eq $serviceApp) + { + return $nullReturn + } + + $supportedFileFormats = @() + if ($serviceApp.WordServiceFormats.OpenXmlDocument) + { + $supportedFileFormats += "docx" + } + if ($serviceApp.WordServiceFormats.Word972003Document) + { + $supportedFileFormats += "doc" + } + if ($serviceApp.WordServiceFormats.RichTextFormat) + { + $supportedFileFormats += "rtf" + } + if ($serviceApp.WordServiceFormats.WebPage) + { + $supportedFileFormats += "mht" + } + if ($serviceApp.WordServiceFormats.Word2003Xml) + { + $supportedFileFormats += "xml" + } + + $returnVal = @{ + Name = $serviceApp.DisplayName + Ensure = "Present" + ApplicationPool = $serviceApp.ApplicationPool.Name + DatabaseName = $serviceApp.Database.Name + DatabaseServer = $serviceApp.Database.Server.Name + SupportedFileFormats = $supportedFileFormats + DisableEmbeddedFonts = $serviceApp.DisableEmbeddedFonts + MaximumMemoryUsage = $serviceApp.MaximumMemoryUsage + RecycleThreshold = $serviceApp.RecycleProcessThreshold + DisableBinaryFileScan = $serviceApp.DisableBinaryFileScan + ConversionProcesses = $serviceApp.TotalActiveProcesses + JobConversionFrequency = $serviceApp.TimerJobFrequency.TotalMinutes + NumberOfConversionsPerProcess = $serviceApp.ConversionsPerInstance + TimeBeforeConversionIsMonitored = $serviceApp.ConversionTimeout.TotalMinutes + MaximumConversionAttempts = $serviceApp.MaximumConversionAttempts + MaximumSyncConversionRequests = $serviceApp.MaximumSyncConversionRequests + KeepAliveTimeout = $serviceApp.KeepAliveTimeout.TotalSeconds + MaximumConversionTime = $serviceApp.MaximumConversionTime.TotalSeconds + InstallAccount = $params.InstallAccount } + return $returnVal } return $result @@ -301,6 +292,8 @@ function Set-TargetResource $InstallAccount ) + Write-Verbose -Message "Setting Word Automation service app '$Name'" + if (($ApplicationPool ` -or $DatabaseName ` -or $DatabaseServer ` @@ -321,102 +314,95 @@ function Set-TargetResource { throw "You cannot use any of the parameters when Ensure is specified as Absent" } + $PSBoundParameters.Ensure = $Ensure + if (($Ensure -eq "Present") -and -not ($ApplicationPool -and $DatabaseName)) { throw ("An Application Pool and Database Name are required to configure the Word " + ` "Automation Service Application") } - switch ($Ensure) + $result = Get-TargetResource @PSBoundParameters + if ($result.Ensure -eq "Absent" -and $Ensure -eq "Present") + { + Write-Verbose -Message "Creating Word Automation Service Application $Name" + Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments $PSBoundParameters ` + -ScriptBlock { + $params = $args[0] + + $appPool = Get-SPServiceApplicationPool -Identity $params.ApplicationPool + if ($appPool) + { + $cmdletparams = @{} + $cmdletparams.Name = $params.Name + if ($params.Name) + { + $cmdletparams.DatabaseName = $params.DatabaseName + } + if ($params.Name) + { + $cmdletparams.DatabaseServer = $params.DatabaseServer + } + if ($params.Name) + { + $cmdletparams.ApplicationPool = $params.ApplicationPool + } + + $serviceApp = New-SPWordConversionServiceApplication @cmdletparams + } + else + { + throw "Specified application pool does not exist" + } + } + } + + if ($result.Ensure -eq "Present" -and $Ensure -eq "Present") { - "Present" { - Write-Verbose -Message "Creating and/or configuring Word Automation Service Application $Name" - Invoke-SPDSCCommand -Credential $InstallAccount ` - -Arguments $PSBoundParameters ` - -ScriptBlock { - $params = $args[0] - - $serviceApp = Get-SPServiceApplication ` - -Name $params.Name ` - -ErrorAction SilentlyContinue | Where-Object -FilterScript { - $_.TypeName -eq "Word Automation Services" - } + Write-Verbose -Message "Updating Word Automation Service Application $Name" + Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments $PSBoundParameters ` + -ScriptBlock { + $params = $args[0] - if ($null -eq $serviceApp) + $serviceApp = Get-SPServiceApplication -Name $params.Name ` + | Where-Object -FilterScript { + $_.GetType().FullName -eq "Microsoft.Office.Word.Server.Service.WordServiceApplication" + } + + # Check if the specified Application Pool is different and change if so + if ([string]::IsNullOrEmpty($ApplicationPool) -eq $false ` + -and $ApplicationPool -ne $result.ApplicationPool) + { + $appPool = Get-SPServiceApplicationPool -Identity $params.ApplicationPool + Set-SPWordConversionServiceApplication -Identity $serviceApp -ApplicationPool $appPool + } + # Check if the specified Database Name and Server are different and change if so + if ($params.DatabaseName) + { + if ($params.DatabaseServer) { - # Service application does not exist, create it - $appPool = Get-SPServiceApplicationPool -Identity $params.ApplicationPool - if ($appPool) - { - $cmdletparams = @{} - $cmdletparams.Name = $params.Name - if ($params.Name) - { - $cmdletparams.DatabaseName = $params.DatabaseName - } - if ($params.Name) - { - $cmdletparams.DatabaseServer = $params.DatabaseServer - } - if ($params.Name) - { - $cmdletparams.ApplicationPool = $params.ApplicationPool - } - - $serviceApp = New-SPWordConversionServiceApplication @cmdletparams - } - else - { - throw "Specified application pool does not exist" + if ($serviceApp.Database.Server.Name -ne $params.DatabaseServer) + { + Set-SPWordConversionServiceApplication -Identity $serviceApp ` + -DatabaseServer $params.DatabaseServer ` + -DatabaseName $params.DatabaseName } } else { - # Service application existed - # Check if the specified Application Pool is different and change if so - if ($params.ApplicationPool) - { - if ($serviceApp.ApplicationPool.Name -ne $params.ApplicationPool) - { - $appPool = Get-SPServiceApplicationPool -Identity $params.ApplicationPool - if ($appPool) - { - Set-SPWordConversionServiceApplication -Identity $serviceApp ` - -ApplicationPool $appPool - } - else - { - throw "Specified application pool does not exist" - } - } - } - - # Check if the specified Database Name and Server are different and change if so - if ($params.DatabaseName) - { - if ($params.DatabaseServer) - { - if ($serviceApp.Database.Server.Name -ne $params.DatabaseServer) - { - Set-SPWordConversionServiceApplication -Identity $serviceApp ` - -DatabaseServer $params.DatabaseServer ` - -DatabaseName $params.DatabaseName - } - } - else - { - if ($serviceApp.Database.Name -ne $params.DatabaseName) - { - Set-SPWordConversionServiceApplication -Identity $serviceApp ` - -DatabaseName $params.DatabaseName - } - } + if ($serviceApp.Database.Name -ne $params.DatabaseName) + { + Set-SPWordConversionServiceApplication -Identity $serviceApp ` + -DatabaseName $params.DatabaseName } } + } - if ($params.SupportedFileFormats) - { + if ($params.SupportedFileFormats) + { if ($params.SupportedFileFormats.Contains("docx")) { $serviceApp.WordServiceFormats.OpenXmlDocument = $true @@ -459,28 +445,28 @@ function Set-TargetResource } } - if ($params.DisableEmbeddedFonts) - { - $serviceApp.DisableEmbeddedFonts = $params.DisableEmbeddedFonts - } - if ($params.MaximumMemoryUsage) - { - $serviceApp.MaximumMemoryUsage = $params.MaximumMemoryUsage - } - if ($params.RecycleThreshold) - { - $serviceApp.RecycleProcessThreshold = $params.RecycleThreshold - } - if ($params.DisableBinaryFileScan) - { - $serviceApp.DisableBinaryFileScan = $params.DisableBinaryFileScan - } - if ($params.ConversionProcesses) - { - $serviceApp.TotalActiveProcesses = $params.ConversionProcesses - } - if ($params.JobConversionFrequency) - { + if ($params.DisableEmbeddedFonts) + { + $serviceApp.DisableEmbeddedFonts = $params.DisableEmbeddedFonts + } + if ($params.MaximumMemoryUsage) + { + $serviceApp.MaximumMemoryUsage = $params.MaximumMemoryUsage + } + if ($params.RecycleThreshold) + { + $serviceApp.RecycleProcessThreshold = $params.RecycleThreshold + } + if ($params.DisableBinaryFileScan) + { + $serviceApp.DisableBinaryFileScan = $params.DisableBinaryFileScan + } + if ($params.ConversionProcesses) + { + $serviceApp.TotalActiveProcesses = $params.ConversionProcesses + } + if ($params.JobConversionFrequency) + { # Check for TimerJob and change schedule $wordAutomationTimerjob = Get-SPTimerJob $params.Name if ($wordAutomationTimerjob.Count -eq 1) @@ -493,54 +479,62 @@ function Set-TargetResource throw "Timerjob could not be found" } } - if ($params.NumberOfConversionsPerProcess) - { - $serviceApp.ConversionsPerInstance = $params.NumberOfConversionsPerProcess - } - if ($params.TimeBeforeConversionIsMonitored) - { - $timespan = New-TimeSpan -Minutes $params.TimeBeforeConversionIsMonitored - $serviceApp.ConversionTimeout = $timespan - } - if ($params.MaximumConversionAttempts) - { - $serviceApp.MaximumConversionAttempts = $params.MaximumConversionAttempts - } - if ($params.MaximumSyncConversionRequests) - { - $serviceApp.MaximumSyncConversionRequests = $params.MaximumSyncConversionRequests - } - if ($params.KeepAliveTimeout) - { - $timespan = New-TimeSpan -Seconds $params.KeepAliveTimeout - $serviceApp.KeepAliveTimeout = $timespan - } - if ($params.MaximumConversionTime) + if ($params.NumberOfConversionsPerProcess) + { + $serviceApp.ConversionsPerInstance = $params.NumberOfConversionsPerProcess + } + if ($params.TimeBeforeConversionIsMonitored) + { + $timespan = New-TimeSpan -Minutes $params.TimeBeforeConversionIsMonitored + $serviceApp.ConversionTimeout = $timespan + } + if ($params.MaximumConversionAttempts) + { + $serviceApp.MaximumConversionAttempts = $params.MaximumConversionAttempts + } + if ($params.MaximumSyncConversionRequests) + { + $serviceApp.MaximumSyncConversionRequests = $params.MaximumSyncConversionRequests + } + if ($params.KeepAliveTimeout) + { + $timespan = New-TimeSpan -Seconds $params.KeepAliveTimeout + $serviceApp.KeepAliveTimeout = $timespan + } + if ($params.MaximumConversionTime) + { + $timespan = New-TimeSpan -Seconds $params.MaximumConversionTime + $serviceApp.MaximumConversionTime = $timespan + } + + $serviceApp.Update() + } + } + + if ($Ensure -eq "Absent") + { + Write-Verbose -Message "Removing Word Automation Service Application $Name" + Invoke-SPDSCCommand -Credential $InstallAccount -Arguments $PSBoundParameters -ScriptBlock { + $params = $args[0] + + $serviceApp = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { + $_.GetType().FullName -eq "Microsoft.Office.Word.Server.Service.WordServiceApplication" + } + if ($null -ne $serviceApp) + { + $proxies = Get-SPServiceApplicationProxy + foreach($proxyInstance in $proxies) { - $timespan = New-TimeSpan -Seconds $params.MaximumConversionTime - $serviceApp.MaximumConversionTime = $timespan + if($serviceApp.IsConnected($proxyInstance)) + { + $proxyInstance.Delete() + } } - $serviceApp.Update() + # Service app existed, deleting + Remove-SPServiceApplication -Identity $serviceApp -RemoveData -Confirm:$false } } - "Absent" { - Write-Verbose -Message "Removing Word Automation Service Application $Name" - Invoke-SPDSCCommand -Credential $InstallAccount -Arguments $PSBoundParameters -ScriptBlock { - $params = $args[0] - - $serviceApp = Get-SPServiceApplication ` - -Name $params.Name ` - -ErrorAction SilentlyContinue | Where-Object -FilterScript { - $_.TypeName -eq "Word Automation Services" - } - if ($null -ne $serviceApp) - { - # Service app existed, deleting - Remove-SPServiceApplication $serviceApp -RemoveData -Confirm:$false - } - } - } } } @@ -638,6 +632,10 @@ function Test-TargetResource $InstallAccount ) + Write-Verbose -Message "Testing Word Automation service app '$Name'" + + $PSBoundParameters.Ensure = $Ensure + if (($ApplicationPool ` -or $DatabaseName ` -or $DatabaseServer ` @@ -659,15 +657,12 @@ function Test-TargetResource throw "You cannot use any of the parameters when Ensure is specified as Absent" } - $PSBoundParameters.Ensure = $Ensure - if (($Ensure -eq "Present") -and -not ($ApplicationPool -and $DatabaseName)) { - throw ("An Application Pool and Database Name are required to configure the Word " + ` + throw ("An Application Pool and Database Name are required to configure the Word " + ` "Automation Service Application") } - Write-Verbose -Message "Testing for Word Automation Service Application '$Name'" $CurrentValues = Get-TargetResource @PSBoundParameters if ($null -eq $CurrentValues) diff --git a/Modules/SharePointDsc/DSCResources/MSFT_SPWorkManagementServiceApp/MSFT_SPWorkManagementServiceApp.psm1 b/Modules/SharePointDsc/DSCResources/MSFT_SPWorkManagementServiceApp/MSFT_SPWorkManagementServiceApp.psm1 index 485a3f3c6..c1b988f05 100644 --- a/Modules/SharePointDsc/DSCResources/MSFT_SPWorkManagementServiceApp/MSFT_SPWorkManagementServiceApp.psm1 +++ b/Modules/SharePointDsc/DSCResources/MSFT_SPWorkManagementServiceApp/MSFT_SPWorkManagementServiceApp.psm1 @@ -4,41 +4,93 @@ function Get-TargetResource [OutputType([System.Collections.Hashtable])] param ( - [parameter(Mandatory = $true)] [System.String] $Name, - [parameter(Mandatory = $false)] [System.String] $ProxyName, - [parameter(Mandatory = $false)] [System.String] $ApplicationPool, - [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", - [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount, - [parameter(Mandatory = $false)] [System.UInt32] $MinimumTimeBetweenEwsSyncSubscriptionSearches, - [parameter(Mandatory = $false)] [System.UInt32] $MinimumTimeBetweenProviderRefreshes, - [parameter(Mandatory = $false)] [System.UInt32] $MinimumTimeBetweenSearchQueries, - [parameter(Mandatory = $false)] [System.UInt32] $NumberOfSubscriptionSyncsPerEwsSyncRun, - [parameter(Mandatory = $false)] [System.UInt32] $NumberOfUsersEwsSyncWillProcessAtOnce, - [parameter(Mandatory = $false)] [System.UInt32] $NumberOfUsersPerEwsSyncBatch + [parameter(Mandatory = $true)] + [System.String] + $Name, + + [parameter(Mandatory = $false)] + [System.String] + $ProxyName, + + [parameter(Mandatory = $false)] + [System.String] + $ApplicationPool, + + [parameter(Mandatory = $false)] + [System.UInt32] + $MinimumTimeBetweenEwsSyncSubscriptionSearches, + + [parameter(Mandatory = $false)] + [System.UInt32] + $MinimumTimeBetweenProviderRefreshes, + + [parameter(Mandatory = $false)] + [System.UInt32] + $MinimumTimeBetweenSearchQueries, + + [parameter(Mandatory = $false)] + [System.UInt32] + $NumberOfSubscriptionSyncsPerEwsSyncRun, + + [parameter(Mandatory = $false)] + [System.UInt32] + $NumberOfUsersEwsSyncWillProcessAtOnce, + + [parameter(Mandatory = $false)] + [System.UInt32] + $NumberOfUsersPerEwsSyncBatch, + + [parameter(Mandatory = $false)] + [ValidateSet("Present","Absent")] + [System.String] + $Ensure = "Present", + + [parameter(Mandatory = $false)] + [System.Management.Automation.PSCredential] + $InstallAccount ) + Write-Verbose -Message "Getting Work management service app '$Name'" - $result = Invoke-SPDSCCommand -Credential $InstallAccount -Arguments $PSBoundParameters -ScriptBlock { + $result = Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments $PSBoundParameters ` + -ScriptBlock { $params = $args[0] $serviceApps = Get-SPServiceApplication -Name $params.Name -ErrorAction SilentlyContinue + $nullReturn = @{ - Name = $params.Name - Ensure = "Absent" + Name = $params.Name + Ensure = "Absent" + ApplicationPool = $params.ApplicationPool } - if ($null -eq $serviceApps) { + + if ($null -eq $serviceApps) + { return $nullReturn } - $serviceApp = $serviceApps | Where-Object -FilterScript { $_.TypeName -eq "Work Management Service Application" } + $serviceApp = $serviceApps | Where-Object -FilterScript { + $_.GetType().FullName -eq "Microsoft.Office.Server.WorkManagement.WorkManagementServiceApplication" + } - If ($null -eq $serviceApp) { - return $nullReturn - } else { + if ($null -eq $serviceApp) + { + return $nullReturn + } + else + { + $serviceAppProxies = Get-SPServiceApplicationProxy -ErrorAction SilentlyContinue if ($null -ne $serviceAppProxies) { - $serviceAppProxy = $serviceAppProxies | Where-Object { $serviceApp.IsConnected($_)} - if ($null -ne $serviceAppProxy) { $proxyName = $serviceAppProxy.Name} + $serviceAppProxy = $serviceAppProxies | Where-Object -FilterScript { + $serviceApp.IsConnected($_) + } + if ($null -ne $serviceAppProxy) + { + $proxyName = $serviceAppProxy.Name + } } + return @{ Name = $serviceApp.DisplayName ProxyName = $proxyName @@ -56,117 +108,291 @@ function Get-TargetResource return $result } - function Set-TargetResource { [CmdletBinding()] param ( - [parameter(Mandatory = $true)] [System.String] $Name, - [parameter(Mandatory = $false)] [System.String] $ProxyName, - [parameter(Mandatory = $false)] [System.String] $ApplicationPool, - [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", - [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount, - [parameter(Mandatory = $false)] [System.UInt32] $MinimumTimeBetweenEwsSyncSubscriptionSearches, - [parameter(Mandatory = $false)] [System.UInt32] $MinimumTimeBetweenProviderRefreshes, - [parameter(Mandatory = $false)] [System.UInt32] $MinimumTimeBetweenSearchQueries, - [parameter(Mandatory = $false)] [System.UInt32] $NumberOfSubscriptionSyncsPerEwsSyncRun, - [parameter(Mandatory = $false)] [System.UInt32] $NumberOfUsersEwsSyncWillProcessAtOnce, - [parameter(Mandatory = $false)] [System.UInt32] $NumberOfUsersPerEwsSyncBatch + [parameter(Mandatory = $true)] + [System.String] + $Name, + + [parameter(Mandatory = $false)] + [System.String] + $ProxyName, + + [parameter(Mandatory = $false)] + [System.String] + $ApplicationPool, + + [parameter(Mandatory = $false)] + [System.UInt32] + $MinimumTimeBetweenEwsSyncSubscriptionSearches, + + [parameter(Mandatory = $false)] + [System.UInt32] + $MinimumTimeBetweenProviderRefreshes, + + [parameter(Mandatory = $false)] + [System.UInt32] + $MinimumTimeBetweenSearchQueries, + + [parameter(Mandatory = $false)] + [System.UInt32] + $NumberOfSubscriptionSyncsPerEwsSyncRun, + + [parameter(Mandatory = $false)] + [System.UInt32] + $NumberOfUsersEwsSyncWillProcessAtOnce, + + [parameter(Mandatory = $false)] + [System.UInt32] + $NumberOfUsersPerEwsSyncBatch, + + [parameter(Mandatory = $false)] + [ValidateSet("Present","Absent")] + [System.String] + $Ensure = "Present", + + [parameter(Mandatory = $false)] + [System.Management.Automation.PSCredential] + $InstallAccount ) - if($Ensure -ne "Absent" -and $null -eq $ApplicationPool){ + + Write-Verbose -Message "Setting Work management service app '$Name'" + $PSBoundParameters.Ensure = $Ensure + + if ($Ensure -ne "Absent" -and $null -eq $ApplicationPool) + { throw "Parameter ApplicationPool is required unless service is being removed(Ensure='Absent')" } - Write-Verbose -Message "Creating work management Service Application $Name" - $PSBoundParameters.Ensure = $Ensure - Invoke-SPDSCCommand -Credential $InstallAccount -Arguments $PSBoundParameters -ScriptBlock { - $params = $args[0] - $appService = Get-SPServiceApplication -Name $params.Name -ErrorAction SilentlyContinue ` - | Where-Object { $_.TypeName -eq "Work Management Service Application" } + $result = Get-TargetResource @PSBoundParameters - if($null -ne $appService -and $params.ContainsKey("Ensure") -and $params.Ensure -eq "Absent") - { - #remove existing app - - Remove-SPServiceApplication $appService - return - } elseif ($null -eq $appService){ - $newParams = @{} - $newParams.Add("Name", $params.Name) - $newParams.Add("ApplicationPool", $params.ApplicationPool) - - $appService = New-SPWorkManagementServiceApplication @newParams - if ($null -eq $params.ProxyName) {$pName = "$($params.Name) Proxy"} Else {$pName = $params.ProxyName} - New-SPWorkManagementServiceApplicationProxy -Name $pName -DefaultProxyGroup -ServiceApplication $appService | Out-Null - Start-Sleep -Milliseconds 200 + if ($result.Ensure -eq "Absent" -and $Ensure -eq "Present") + { + Write-Verbose -Message "Creating work management Service Application $Name" + Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments $PSBoundParameters ` + -ScriptBlock { + $params = $args[0] + if ($params.ContainsKey("Ensure")) + { + $params.Remove("Ensure") | Out-Null + } + if ($params.ContainsKey("InstallAccount")) + { + $params.Remove("InstallAccount") | Out-Null + } + if ($params.ContainsKey("ProxyName")) + { + $pName = $params.ProxyName + $params.Remove("ProxyName") | Out-Null + } + if ($null -eq $pName) { + $pName = "$($params.Name) Proxy" + } + + $app = New-SPWorkManagementServiceApplication @params + if ($null -ne $app) + { + New-SPWorkManagementServiceApplicationProxy -Name $pName ` + -ServiceApplication $app ` + -DefaultProxyGroup + Start-Sleep -Milliseconds 200 + } } - $setParams = @{} - if ($params.ContainsKey("MinimumTimeBetweenEwsSyncSubscriptionSearches")) { $setParams.Add("MinimumTimeBetweenEwsSyncSubscriptionSearches", $params.MinimumTimeBetweenEwsSyncSubscriptionSearches) } - if ($params.ContainsKey("MinimumTimeBetweenProviderRefreshes")) { $setParams.Add("MinimumTimeBetweenProviderRefreshes", $params.MinimumTimeBetweenProviderRefreshes) } - if ($params.ContainsKey("MinimumTimeBetweenSearchQueries")) { $setParams.Add("MinimumTimeBetweenSearchQueries", $params.MinimumTimeBetweenSearchQueries) } - if ($params.ContainsKey("NumberOfSubscriptionSyncsPerEwsSyncRun")) { $setParams.Add("NumberOfSubscriptionSyncsPerEwsSyncRun", $params.NumberOfSubscriptionSyncsPerEwsSyncRun) } - if ($params.ContainsKey("NumberOfUsersEwsSyncWillProcessAtOnce")) { $setParams.Add("NumberOfUsersEwsSyncWillProcessAtOnce", $params.NumberOfUsersEwsSyncWillProcessAtOnce) } - if ($params.ContainsKey("NumberOfUsersPerEwsSyncBatch")) { $setParams.Add("NumberOfUsersPerEwsSyncBatch", $params.NumberOfUsersPerEwsSyncBatch) } - - $setParams.Add("Name", $params.Name) - $setParams.Add("ApplicationPool", $params.ApplicationPool) - - if ($setParams.ContainsKey("MinimumTimeBetweenEwsSyncSubscriptionSearches")) { - $setParams.MinimumTimeBetweenEwsSyncSubscriptionSearches = New-TimeSpan -Days $setParams.MinimumTimeBetweenEwsSyncSubscriptionSearches + } + + if ($result.Ensure -eq "Present" -and $Ensure -eq "Present") + { + if ([string]::IsNullOrEmpty($ApplicationPool) -eq $false ` + -and $ApplicationPool -ne $result.ApplicationPool) + { + Write-Verbose -Message "Updating Application Pool of Work Management Service Application $Name" + Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments $PSBoundParameters ` + -ScriptBlock { + $params = $args[0] + + $serviceApp = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { + $_.GetType().FullName -eq "Microsoft.Office.Server.WorkManagement.WorkManagementServiceApplication" + } + $appPool = Get-SPServiceApplicationPool -Identity $params.ApplicationPool + Set-SPWorkManagementServiceApplication -Identity $serviceApp -ApplicationPool $appPool + } } - if ($setParams.ContainsKey("MinimumTimeBetweenProviderRefreshes")) { - $setParams.MinimumTimeBetweenProviderRefreshes = New-TimeSpan -Days $setParams.MinimumTimeBetweenProviderRefreshes + else + { + Write-Verbose -Message "Updating Application Pool of Work Management Service Application $Name" + Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments $PSBoundParameters ` + -ScriptBlock { + $params = $args[0] + + $setParams = @{} + if ($params.ContainsKey("MinimumTimeBetweenEwsSyncSubscriptionSearches")) + { + $setParams.Add("MinimumTimeBetweenEwsSyncSubscriptionSearches", + $params.MinimumTimeBetweenEwsSyncSubscriptionSearches) + } + if ($params.ContainsKey("MinimumTimeBetweenProviderRefreshes")) + { + $setParams.Add("MinimumTimeBetweenProviderRefreshes", + $params.MinimumTimeBetweenProviderRefreshes) + } + if ($params.ContainsKey("MinimumTimeBetweenSearchQueries")) + { + $setParams.Add("MinimumTimeBetweenSearchQueries", + $params.MinimumTimeBetweenSearchQueries) + } + if ($params.ContainsKey("NumberOfSubscriptionSyncsPerEwsSyncRun")) + { + $setParams.Add("NumberOfSubscriptionSyncsPerEwsSyncRun", + $params.NumberOfSubscriptionSyncsPerEwsSyncRun) + } + if ($params.ContainsKey("NumberOfUsersEwsSyncWillProcessAtOnce")) + { + $setParams.Add("NumberOfUsersEwsSyncWillProcessAtOnce", + $params.NumberOfUsersEwsSyncWillProcessAtOnce) + } + if ($params.ContainsKey("NumberOfUsersPerEwsSyncBatch")) + { + $setParams.Add("NumberOfUsersPerEwsSyncBatch", + $params.NumberOfUsersPerEwsSyncBatch) + } + + $setParams.Add("Name", $params.Name) + $setParams.Add("ApplicationPool", $params.ApplicationPool) + + if ($setParams.ContainsKey("MinimumTimeBetweenEwsSyncSubscriptionSearches")) + { + $setParams.MinimumTimeBetweenEwsSyncSubscriptionSearches = New-TimeSpan -Days $setParams.MinimumTimeBetweenEwsSyncSubscriptionSearches + } + if ($setParams.ContainsKey("MinimumTimeBetweenProviderRefreshes")) + { + $setParams.MinimumTimeBetweenProviderRefreshes = New-TimeSpan -Days $setParams.MinimumTimeBetweenProviderRefreshes + } + if ($setParams.ContainsKey("MinimumTimeBetweenSearchQueries")) + { + $setParams.MinimumTimeBetweenSearchQueries = New-TimeSpan -Days $setParams.MinimumTimeBetweenSearchQueries + } + $setParams.Add("Confirm", $false) + $appService = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { + $_.GetType().FullName -eq "Microsoft.Office.Server.WorkManagement.WorkManagementServiceApplication" + } + + $appService | Set-SPWorkManagementServiceApplication @setPArams | Out-Null + } } - if ($setParams.ContainsKey("MinimumTimeBetweenSearchQueries")) { - $setParams.MinimumTimeBetweenSearchQueries = New-TimeSpan -Days $setParams.MinimumTimeBetweenSearchQueries + } + + if ($Ensure -eq "Absent") + { + # The service app should not exit + Write-Verbose -Message "Removing Work Management Service Application $Name" + Invoke-SPDSCCommand -Credential $InstallAccount ` + -Arguments $PSBoundParameters ` + -ScriptBlock { + $params = $args[0] + + $serviceApp = Get-SPServiceApplication -Name $params.Name | Where-Object -FilterScript { + $_.GetType().FullName -eq "Microsoft.Office.Server.WorkManagement.WorkManagementServiceApplication" + } + + $proxies = Get-SPServiceApplicationProxy + foreach($proxyInstance in $proxies) + { + if($serviceApp.IsConnected($proxyInstance)) + { + $proxyInstance.Delete() + } + } + + Remove-SPServiceApplication $serviceApp -Confirm:$false } - $setParams.Add("Confirm", $false) - $appService = Get-SPServiceApplication -Name $params.Name ` - | Where-Object { $_.TypeName -eq "Work Management Service Application" } - - $appService | Set-SPWorkManagementServiceApplication @setPArams | Out-Null } } - function Test-TargetResource { [CmdletBinding()] [OutputType([System.Boolean])] param ( - [parameter(Mandatory = $true)] [System.String] $Name, - [parameter(Mandatory = $false)] [System.String] $ProxyName, - [parameter(Mandatory = $false)] [System.String] $ApplicationPool, - [parameter(Mandatory = $false)] [ValidateSet("Present","Absent")] [System.String] $Ensure = "Present", - [parameter(Mandatory = $false)] [System.Management.Automation.PSCredential] $InstallAccount, - [parameter(Mandatory = $false)] [System.UInt32] $MinimumTimeBetweenEwsSyncSubscriptionSearches, - [parameter(Mandatory = $false)] [System.UInt32] $MinimumTimeBetweenProviderRefreshes, - [parameter(Mandatory = $false)] [System.UInt32] $MinimumTimeBetweenSearchQueries, - [parameter(Mandatory = $false)] [System.UInt32] $NumberOfSubscriptionSyncsPerEwsSyncRun, - [parameter(Mandatory = $false)] [System.UInt32] $NumberOfUsersEwsSyncWillProcessAtOnce, - [parameter(Mandatory = $false)] [System.UInt32] $NumberOfUsersPerEwsSyncBatch + [parameter(Mandatory = $true)] + [System.String] + $Name, + + [parameter(Mandatory = $false)] + [System.String] + $ProxyName, + + [parameter(Mandatory = $false)] + [System.String] + $ApplicationPool, + + [parameter(Mandatory = $false)] + [System.UInt32] + $MinimumTimeBetweenEwsSyncSubscriptionSearches, + + [parameter(Mandatory = $false)] + [System.UInt32] + $MinimumTimeBetweenProviderRefreshes, + + [parameter(Mandatory = $false)] + [System.UInt32] + $MinimumTimeBetweenSearchQueries, + + [parameter(Mandatory = $false)] + [System.UInt32] + $NumberOfSubscriptionSyncsPerEwsSyncRun, + + [parameter(Mandatory = $false)] + [System.UInt32] + $NumberOfUsersEwsSyncWillProcessAtOnce, + + [parameter(Mandatory = $false)] + [System.UInt32] + $NumberOfUsersPerEwsSyncBatch, + + [parameter(Mandatory = $false)] + [ValidateSet("Present","Absent")] + [System.String] + $Ensure = "Present", + + [parameter(Mandatory = $false)] + [System.Management.Automation.PSCredential] + $InstallAccount ) - Write-Verbose -Message "Testing for App management Service Application '$Name'" - $CurrentValues = Get-TargetResource @PSBoundParameters + Write-Verbose -Message "Testing Work management service app '$Name'" + $PSBoundParameters.Ensure = $Ensure - if ($Ensure -eq "Present") { - return Test-SPDscParameterState -CurrentValues $CurrentValues -DesiredValues $PSBoundParameters -ValuesToCheck @("ApplicationPool", - "MinimumTimeBetweenEwsSyncSubscriptionSearches", - "MinimumTimeBetweenProviderRefreshes", - "MinimumTimeBetweenSearchQueries", - "Name", - "NumberOfSubscriptionSyncsPerEwsSyncRun", - "NumberOfUsersEwsSyncWillProcessAtOnce", - "NumberOfUsersPerEwsSyncBatch", - "Ensure" - ) - } else { - return Test-SPDscParameterState -CurrentValues $CurrentValues -DesiredValues $PSBoundParameters -ValuesToCheck @("Ensure") + + $CurrentValues = Get-TargetResource @PSBoundParameters + + if ($Ensure -eq "Present") + { + return Test-SPDscParameterState -CurrentValues $CurrentValues ` + -DesiredValues $PSBoundParameters ` + -ValuesToCheck @("ApplicationPool", + "MinimumTimeBetweenEwsSyncSubscriptionSearches", + "MinimumTimeBetweenProviderRefreshes", + "MinimumTimeBetweenSearchQueries", + "Name", + "NumberOfSubscriptionSyncsPerEwsSyncRun", + "NumberOfUsersEwsSyncWillProcessAtOnce", + "NumberOfUsersPerEwsSyncBatch", + "Ensure") + } + else + { + return Test-SPDscParameterState -CurrentValues $CurrentValues ` + -DesiredValues $PSBoundParameters ` + -ValuesToCheck @("Ensure") } - } Export-ModuleMember -Function *-TargetResource + diff --git a/Modules/SharePointDsc/Examples/Resources/SPAppCatalog/1-SetSiteAsAppCatalog.ps1 b/Modules/SharePointDsc/Examples/Resources/SPAppCatalog/1-SetSiteAsAppCatalog.ps1 index 50487fcfe..6248d94f3 100644 --- a/Modules/SharePointDsc/Examples/Resources/SPAppCatalog/1-SetSiteAsAppCatalog.ps1 +++ b/Modules/SharePointDsc/Examples/Resources/SPAppCatalog/1-SetSiteAsAppCatalog.ps1 @@ -1,6 +1,6 @@ <# .EXAMPLE - This example shows how to apply specific anti-virus configuration to the farm + This example shows how to configure the AppCatalog in the farm #> Configuration Example diff --git a/Modules/SharePointDsc/Examples/Resources/SPAppStoreSettings/1-EnableSharePointAppStore.ps1 b/Modules/SharePointDsc/Examples/Resources/SPAppStoreSettings/1-EnableSharePointAppStore.ps1 new file mode 100644 index 000000000..fb06f8c70 --- /dev/null +++ b/Modules/SharePointDsc/Examples/Resources/SPAppStoreSettings/1-EnableSharePointAppStore.ps1 @@ -0,0 +1,23 @@ +<# +.EXAMPLE + This example shows how to configure the AppCatalog in the farm +#> + + Configuration Example + { + param( + [Parameter(Mandatory = $true)] + [PSCredential] + $SetupAccount + ) + Import-DscResource -ModuleName SharePointDsc + + node localhost { + SPAppStoreSettings EnableSharePointAppStore + { + WebAppUrl = "https://sharepoint.contoso.com" + AllowAppPurchases = $true + PsDscRunAsCredential = $SetupAccount + } + } + } diff --git a/Modules/SharePointDsc/Examples/Resources/SPAppStoreSettings/2-EnableAppStores.ps1 b/Modules/SharePointDsc/Examples/Resources/SPAppStoreSettings/2-EnableAppStores.ps1 new file mode 100644 index 000000000..6f8ad479c --- /dev/null +++ b/Modules/SharePointDsc/Examples/Resources/SPAppStoreSettings/2-EnableAppStores.ps1 @@ -0,0 +1,24 @@ +<# +.EXAMPLE + This example shows how to configure the AppCatalog in the farm +#> + + Configuration Example + { + param( + [Parameter(Mandatory = $true)] + [PSCredential] + $SetupAccount + ) + Import-DscResource -ModuleName SharePointDsc + + node localhost { + SPAppStoreSettings EnableAppStores + { + WebAppUrl = "https://sharepoint.contoso.com" + AllowAppPurchases = $true + AllowAppsForOffice = $true + PsDscRunAsCredential = $SetupAccount + } + } + } diff --git a/Modules/SharePointDsc/Examples/Resources/SPAppStoreSettings/3-DisableAppStores.ps1 b/Modules/SharePointDsc/Examples/Resources/SPAppStoreSettings/3-DisableAppStores.ps1 new file mode 100644 index 000000000..861c5aa27 --- /dev/null +++ b/Modules/SharePointDsc/Examples/Resources/SPAppStoreSettings/3-DisableAppStores.ps1 @@ -0,0 +1,24 @@ +<# +.EXAMPLE + This example shows how to configure the AppCatalog in the farm +#> + + Configuration Example + { + param( + [Parameter(Mandatory = $true)] + [PSCredential] + $SetupAccount + ) + Import-DscResource -ModuleName SharePointDsc + + node localhost { + SPAppStoreSettings DisableAppStores + { + WebAppUrl = "https://sharepoint.contoso.com" + AllowAppPurchases = $false + AllowAppsForOffice = $false + PsDscRunAsCredential = $SetupAccount + } + } + } diff --git a/Modules/SharePointDsc/Modules/SharePointDsc.Util/SharePointDsc.Util.psm1 b/Modules/SharePointDsc/Modules/SharePointDsc.Util/SharePointDsc.Util.psm1 index 6ad5d0509..72791a48e 100644 --- a/Modules/SharePointDsc/Modules/SharePointDsc.Util/SharePointDsc.Util.psm1 +++ b/Modules/SharePointDsc/Modules/SharePointDsc.Util/SharePointDsc.Util.psm1 @@ -73,7 +73,6 @@ function Get-SPDscFarmVersionInfo # Loop through all products foreach ($product in $products) { - #Write-Verbose -Verbose "Product: $product" $singleProductInfo = $serverProductInfo.GetSingleProductInfo($product) $patchableUnits = $singleProductInfo.PatchableUnitDisplayNames @@ -89,7 +88,6 @@ function Get-SPDscFarmVersionInfo ($patchableUnit -notmatch "Project Server") -and ($patchableUnit -notmatch "Microsoft SharePoint Server 2013")) { - #Write-Verbose -Verbose " - $patchableUnit" $patchableUnitsInfo = $singleProductInfo.GetPatchableUnitInfoByDisplayName($patchableUnit) $currentVersion = "" foreach ($patchableUnitInfo in $patchableUnitsInfo) @@ -131,6 +129,18 @@ function Get-SPDscFarmProductsInfo return $serverProductInfo.Products } +function Get-SPDscRegProductsInfo +{ + $registryLocation = Get-ChildItem -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall" + $sharePointPrograms = $registryLocation | Where-Object -FilterScript { + $_.PsPath -like "*\Office*" + } | ForEach-Object -Process { + Get-ItemProperty -Path $_.PsPath + } + + return $sharePointPrograms.DisplayName +} + function Get-SPDSCRegistryKey { [CmdletBinding()] @@ -493,7 +503,7 @@ function Test-SPDscParameterState if (($DesiredValues.GetType().Name -eq "CimInstance") -and ($null -eq $ValuesToCheck)) { - throw ("If 'DesiredValues' is a Hashtable then property 'ValuesToCheck' must contain " + ` + throw ("If 'DesiredValues' is a CimInstance then property 'ValuesToCheck' must contain " + ` "a value") } @@ -511,12 +521,11 @@ function Test-SPDscParameterState { if (($CurrentValues.ContainsKey($_) -eq $false) ` -or ($CurrentValues.$_ -ne $DesiredValues.$_) ` - -or (($DesiredValues.ContainsKey($_) -eq $true) -and ($DesiredValues.$_.GetType().IsArray))) + -or (($DesiredValues.ContainsKey($_) -eq $true) -and ($null -ne $DesiredValues.$_ -and $DesiredValues.$_.GetType().IsArray))) { if ($DesiredValues.GetType().Name -eq "HashTable" -or ` $DesiredValues.GetType().Name -eq "PSBoundParametersDictionary") { - $CheckDesiredValue = $DesiredValues.ContainsKey($_) } else @@ -662,7 +671,7 @@ function Test-SPDSCIsADUser $IdentityName = $IdentityName.Substring($IdentityName.IndexOf('\') + 1) } - $searcher = New-Object System.DirectoryServices.DirectorySearcher + $searcher = New-Object -TypeName System.DirectoryServices.DirectorySearcher $searcher.filter = "((samAccountName=$IdentityName))" $searcher.SearchScope = "subtree" $searcher.PropertiesToLoad.Add("objectClass") | Out-Null diff --git a/Modules/SharePointDsc/Modules/SharePointDsc.WebApplication/SPWebApplication.BlockedFileTypes.psm1 b/Modules/SharePointDsc/Modules/SharePointDsc.WebApplication/SPWebApplication.BlockedFileTypes.psm1 index 3f26cc5de..d5711040e 100644 --- a/Modules/SharePointDsc/Modules/SharePointDsc.WebApplication/SPWebApplication.BlockedFileTypes.psm1 +++ b/Modules/SharePointDsc/Modules/SharePointDsc.WebApplication/SPWebApplication.BlockedFileTypes.psm1 @@ -45,14 +45,14 @@ function Set-SPDSCWebApplicationBlockedFileTypeConfig if($Settings.ContainsKey("Blocked") -eq $true) { $WebApplication.BlockedFileExtensions.Clear(); - $Settings.Blocked | ForEach-Object { + $Settings.Blocked | ForEach-Object -Process { $WebApplication.BlockedFileExtensions.Add($_.ToLower()); } } if($Settings.ContainsKey("EnsureBlocked") -eq $true) { - $Settings.EnsureBlocked | ForEach-Object { + $Settings.EnsureBlocked | ForEach-Object -Process { if(!$WebApplication.BlockedFileExtensions.Contains($_.ToLower())){ $WebApplication.BlockedFileExtensions.Add($_.ToLower()); } @@ -61,7 +61,7 @@ function Set-SPDSCWebApplicationBlockedFileTypeConfig if($Settings.ContainsKey("EnsureAllowed") -eq $true) { - $Settings.EnsureAllowed | ForEach-Object { + $Settings.EnsureAllowed | ForEach-Object -Process { if($WebApplication.BlockedFileExtensions.Contains($_.ToLower())){ $WebApplication.BlockedFileExtensions.Remove($_.ToLower()); } diff --git a/Modules/SharePointDsc/Modules/SharePointDsc.WebApplication/SPWebApplication.Throttling.psm1 b/Modules/SharePointDsc/Modules/SharePointDsc.WebApplication/SPWebApplication.Throttling.psm1 index 2fea5b55d..27786e51a 100644 --- a/Modules/SharePointDsc/Modules/SharePointDsc.WebApplication/SPWebApplication.Throttling.psm1 +++ b/Modules/SharePointDsc/Modules/SharePointDsc.WebApplication/SPWebApplication.Throttling.psm1 @@ -47,7 +47,7 @@ function Set-SPDSCWebApplicationThrottlingConfig EventHandlersEnabled = "EventHandlersEnabled" ChangeLogExpirationEnabled = "ChangeLogEnabled" } - $mapping.Keys | ForEach-Object { + $mapping.Keys | ForEach-Object -Process { Set-SPDscObjectPropertyIfValuePresent -ObjectToSet $WebApplication ` -PropertyToSet $_ ` -ParamsValue $settings ` diff --git a/Modules/SharePointDsc/SharePointDsc.psd1 b/Modules/SharePointDsc/SharePointDsc.psd1 index c231ca642..cb1ee3a73 100644 --- a/Modules/SharePointDsc/SharePointDsc.psd1 +++ b/Modules/SharePointDsc/SharePointDsc.psd1 @@ -12,7 +12,7 @@ # RootModule = '' # Version number of this module. -ModuleVersion = '1.3.0.0' +ModuleVersion = '1.4.0.0' # ID used to uniquely identify this module GUID = '6c1176a0-4fac-4134-8ca2-3fa8a21a7b90' @@ -27,7 +27,7 @@ CompanyName = 'Microsoft Corporation' Copyright = '(c) 2015-2016 Microsoft Corporation. All rights reserved.' # Description of the functionality provided by this module -Description = 'This DSC module is used to deploy and configure SharePoint Server 2013 and 2016, and convers a wide range of areas including web apps, service apps and farm configuration.' +Description = 'This DSC module is used to deploy and configure SharePoint Server 2013 and 2016, and covers a wide range of areas including web apps, service apps and farm configuration.' # Minimum version of the Windows PowerShell engine required by this module # PowerShellVersion = '' @@ -126,21 +126,40 @@ PrivateData = @{ # ReleaseNotes of this module ReleaseNotes = ' - * Fixed typo on return value in SPServiceAppProxyGroup - * Fixed SPJoinFarm to not write output during successful farm join - * Fixed issue with SPSearchTopology to keep array of strings in the hashtable returned by Get-Target - * Fixed issue with SPSearchTopology that prevented topology from updating where ServerName was not returned on each component - * Added ProxyName parameter to all service application resources - * Changed SPServiceInstance to look for object type names instead of the display name to ensure consistency with language packs - * Fixed typos in documentation for InstallAccount parameter on most resources - * Fixed a bug where SPQuotaTemplate would not allow warning and limit values to be equal - * New resources: SPConfigWizard, SPProductUpdate and SPPublishServiceApplication - * Updated style of all script in module to align with PowerShell team standards - * Changed parameter ClaimsMappings in SPTrustedIdentityTokenIssuer to consume an array of custom object MSFT_SPClaimTypeMapping - * Changed SPTrustedIdentityTokenIssuer to throw an exception if certificate specified has a private key, since SharePoint doesn''t accept it - * Fixed issue with SPTrustedIdentityTokenIssuer to stop if cmdlet New-SPTrustedIdentityTokenIssuer returns null - * Fixed issue with SPTrustedIdentityTokenIssuer to correctly get parameters ClaimProviderName and ProviderSignOutUri - * Fixed issue with SPTrustedIdentityTokenIssuer to effectively remove the SPTrustedAuthenticationProvider from all zones before deleting the SPTrustedIdentityTokenIssuer + * Set-TargetResource of Service Application now also removes all associated proxies + * Fixed issue with all SPServiceApplication for OS not in En-Us language, add GetType().FullName method in: + - SPAccessServiceApp + - SPAppManagementServiceApp + - SPBCSServiceApp + - SPExcelServiceApp + - SPManagedMetaDataServiceApp + - SPPerformancePointServiceApp + - SPSearchServiceApp + - SPSearchCrawlRule + - SPSecureStoreServiceApp + - SPSubscriptionSettingsServiceApp + - SPUsageApplication + - SPUserProfileServiceApp + - SPVisioServiceApp + - SPWordAutomationServiceApp + - SPWorkManagementServiceApp + * Fixed issue with SPServiceInstance for OS not in En-Us language, add GetType().Name method in: + - SPDistributedCacheService + - SPUserProfileSyncService + * Fixed issue with SPInstallLanguagePack to install before farm creation + * Fixed issue with mounting SPContentDatabase + * Fixed issue with SPShellAdmin and Content Database method + * Fixed issue with SPServiceInstance (Set-TargetResource) for OS not in En-Us language + * Added .Net 4.6 support check to SPInstall and SPInstallPrereqs + * Improved code styling + * SPVisioServiceapplication now creates proxy and lets you specify a name for it + * New resources: SPAppStoreSettings + * Fixed bug with SPInstallPrereqs to allow minor version changes to prereqs for SP2016 + * Refactored unit tests to consolidate and streamline test approaches + * Updated SPExcelServiceApp resource to add support for trusted file locations and most other properties of the service app + * Added support to SPMetadataServiceApp to allow changing content type hub URL on existing service apps + * Fixed a bug that would cause SPSearchResultSource to throw exceptions when the enterprise search centre URL has not been set + * Updated documentation of SPProductUpdate to reflect the required install order of product updates ' } # End of PSData hashtable diff --git a/Modules/SharePointDsc/en-us/about_SPAppCatalog.help.txt b/Modules/SharePointDsc/en-us/about_SPAppCatalog.help.txt index 576b5e336..112ef45cf 100644 --- a/Modules/SharePointDsc/en-us/about_SPAppCatalog.help.txt +++ b/Modules/SharePointDsc/en-us/about_SPAppCatalog.help.txt @@ -17,7 +17,7 @@ .EXAMPLE - This example shows how to apply specific anti-virus configuration to the farm + This example shows how to configure the AppCatalog in the farm Configuration Example diff --git a/Modules/SharePointDsc/en-us/about_SPAppStoreSettings.help.txt b/Modules/SharePointDsc/en-us/about_SPAppStoreSettings.help.txt new file mode 100644 index 000000000..5ab234e60 --- /dev/null +++ b/Modules/SharePointDsc/en-us/about_SPAppStoreSettings.help.txt @@ -0,0 +1,98 @@ +.NAME + SPAppStoreSettings + +.DESCRIPTION + + This resource will configure the ability to purchase apps for both SharePoint and Office apps. + +.PARAMETER WebAppUrl + Key - string + The URL of the web application + +.PARAMETER AllowAppPurchases + Write - Boolean + Specifies if App Purchases from the SharePoint Store are allowed + +.PARAMETER AllowAppsForOffice + Write - Boolean + Specifies if App Purchases for Office applications are allowed + +.PARAMETER InstallAccount + Write - String + POWERSHELL 4 ONLY: The account to run this resource as, use PsDscRunAsCredential if using PowerShell 5 + + +.EXAMPLE + This example shows how to configure the AppCatalog in the farm + + + Configuration Example + { + param( + [Parameter(Mandatory = $true)] + [PSCredential] + $SetupAccount + ) + Import-DscResource -ModuleName SharePointDsc + + node localhost { + SPAppStoreSettings EnableSharePointAppStore + { + WebAppUrl = "https://sharepoint.contoso.com" + AllowAppPurchases = $true + PsDscRunAsCredential = $SetupAccount + } + } + } + + +.EXAMPLE + This example shows how to configure the AppCatalog in the farm + + + Configuration Example + { + param( + [Parameter(Mandatory = $true)] + [PSCredential] + $SetupAccount + ) + Import-DscResource -ModuleName SharePointDsc + + node localhost { + SPAppStoreSettings EnableAppStores + { + WebAppUrl = "https://sharepoint.contoso.com" + AllowAppPurchases = $true + AllowAppsForOffice = $true + PsDscRunAsCredential = $SetupAccount + } + } + } + + +.EXAMPLE + This example shows how to configure the AppCatalog in the farm + + + Configuration Example + { + param( + [Parameter(Mandatory = $true)] + [PSCredential] + $SetupAccount + ) + Import-DscResource -ModuleName SharePointDsc + + node localhost { + SPAppStoreSettings DisableAppStores + { + WebAppUrl = "https://sharepoint.contoso.com" + AllowAppPurchases = $false + AllowAppsForOffice = $false + PsDscRunAsCredential = $SetupAccount + } + } + } + + diff --git a/Modules/SharePointDsc/en-us/about_SPExcelServiceApp.help.txt b/Modules/SharePointDsc/en-us/about_SPExcelServiceApp.help.txt index c68fb3d8f..0d8f16088 100644 --- a/Modules/SharePointDsc/en-us/about_SPExcelServiceApp.help.txt +++ b/Modules/SharePointDsc/en-us/about_SPExcelServiceApp.help.txt @@ -15,6 +15,77 @@ Required - string The name of the application pool to run the service app in +.PARAMETER TrustedFileLocations + Write - string + Trusted file locations for the service app + +.PARAMETER CachingOfUnusedFilesEnable + Write - Boolean + Specifies that files that are no longer used by Excel Services Application can remain in the cache for later use. + +.PARAMETER CrossDomainAccessAllowed + Write - Boolean + Specifies that trusted workbooks and data connection files can be requested and rendered by Web Parts or pages that reside in other HTTP domains. + +.PARAMETER EncryptedUserConnectionRequired + Write - String + Allowed values: None, Connection + Requires that encryption is used between the end-user and the server running Excel Services Application. + +.PARAMETER ExternalDataConnectionLifetime + Write - Uint32 + Specifies the maximum number of seconds that an external data connection can remain open in the connection pool. + +.PARAMETER FileAccessMethod + Write - String + Allowed values: UseImpersonation, UseFileAccessAccount + Specifies the authentication method that Excel Services Application uses to retrieve files. + +.PARAMETER LoadBalancingScheme + Write - String + Allowed values: RoundRobin, Local, WorkbookURL + Specifies the load-balancing schema that is used by the Excel Services Application Web service application to send requests to different back-end Excel Services Application computers. + +.PARAMETER MemoryCacheThreshold + Write - Uint32 + Specifies the percentage of the maximum private bytes that can be allocated to inactive objects. + +.PARAMETER PrivateBytesMax + Write - Uint32 + Specifies the maximum private bytes, in megabytes, that are used by Excel Services Application. + +.PARAMETER SessionsPerUserMax + Write - Uint32 + Specifies the maximum number of sessions allowed for a user. + +.PARAMETER SiteCollectionAnonymousSessionsMax + Write - Uint32 + Specifies the maximum number of anonymous sessions allowed per site collection. + +.PARAMETER TerminateProcessOnAccessViolation + Write - Boolean + Terminates Excel Services Application when an access violation occurs in the process. + +.PARAMETER ThrottleAccessViolationsPerSiteCollection + Write - Uint32 + Specifies that if a workbook causes an access violation error on Excel Services Application, all files originating from that workbook’s site collection are blocked from loading for the specified period (in seconds). + +.PARAMETER UnattendedAccountApplicationId + Write - String + Specifies that the application ID that is used to look up the unattended service account credentials from the secure storage service that is specified by the UnattendedAccountSecureServiceAppName parameter. + +.PARAMETER UnusedObjectAgeMax + Write - Uint32 + Specifies the maximum amount of time, in minutes, that objects not currently used in a session are kept in the memory cache. + +.PARAMETER WorkbookCache + Write - String + Specifies the local file system location of the cache that is used to store workbooks that are used by Excel Services Application. + +.PARAMETER WorkbookCacheSizeMax + Write - Uint32 + Specifies the maximum allowable size, in megabytes, of an individual session. + .PARAMETER Ensure Write - string Allowed values: Present, Absent diff --git a/Modules/SharePointDsc/en-us/about_SPProductUpdate.help.txt b/Modules/SharePointDsc/en-us/about_SPProductUpdate.help.txt index 57decedb8..3c4e2dc3f 100644 --- a/Modules/SharePointDsc/en-us/about_SPProductUpdate.help.txt +++ b/Modules/SharePointDsc/en-us/about_SPProductUpdate.help.txt @@ -9,6 +9,15 @@ The BinaryInstallDays and BinaryInstallTime parameters specify a window in which the update can be installed. This module requires the Configuration Wizard resource to fully complete the installation of the update, which can be done through the use of SPConfigWizard. + IMPORTANT: + This resource retrieves build information from the Configuration Database. Therefore it requires SharePoint to be installed and a farm created. + If you like to deploy a new farm and install updates automatically, you need to implement the following order: + 1. Install the SharePoint Binaries (SPInstall) + 2. (Optional) Install SharePoint Language Pack(s) Binaries (SPInstallLanguagePack) + 3. Create SPFarm (SPCreateFarm) + 4. Install Cumulative Updates (SPProductUpdate) + 5. Run the Configuration Wizard (SPConfigWizard) + .PARAMETER SetupFile Key - String The name of the update setup file diff --git a/Modules/SharePointDsc/en-us/about_SPVisioServiceApp.help.txt b/Modules/SharePointDsc/en-us/about_SPVisioServiceApp.help.txt index 91afb8247..ca3ba5b38 100644 --- a/Modules/SharePointDsc/en-us/about_SPVisioServiceApp.help.txt +++ b/Modules/SharePointDsc/en-us/about_SPVisioServiceApp.help.txt @@ -15,6 +15,10 @@ Required - string The name of the application pool to run the service app in +.PARAMETER ProxyName + Write - string + The name of the Visio Service Application Proxy + .PARAMETER Ensure Write - string Allowed values: Present, Absent diff --git a/Tests/Integration/PreflightChecks/Preflight.Tests.ps1 b/Tests/Integration/PreflightChecks/Preflight.Tests.ps1 index a8f0a914b..f3d2efc55 100644 --- a/Tests/Integration/PreflightChecks/Preflight.Tests.ps1 +++ b/Tests/Integration/PreflightChecks/Preflight.Tests.ps1 @@ -5,7 +5,7 @@ Set-StrictMode -Off Describe -Tags @("Preflight") "SharePointDsc Integration Tests - Preflight Check" { - it "Includes all required service accounts" { + It "Includes all required service accounts" { $Global:SPDscIntegrationCredPool.ContainsKey("Setup") | Should Be $true $Global:SPDscIntegrationCredPool.ContainsKey("Farm") | Should Be $true $Global:SPDscIntegrationCredPool.ContainsKey("WebApp") | Should Be $true @@ -21,11 +21,11 @@ Describe -Tags @("Preflight") "SharePointDsc Integration Tests - Preflight Check it "Has valid credentials for all service accounts" { $failedCredentials = $false - $Global:SPDscIntegrationCredPool.Keys | ForEach-Object { + $Global:SPDscIntegrationCredPool.Keys | ForEach-Object -Process { $cred = $Global:SPDscIntegrationCredPool.$_ $username = $cred.username $password = $cred.GetNetworkCredential().password - $domain = New-Object System.DirectoryServices.DirectoryEntry("",$UserName,$Password) + $domain = New-Object -TypeName System.DirectoryServices.DirectoryEntry("",$UserName,$Password) if ($domain.name -eq $null) { Write-Warning "Credential for $username is not valid" @@ -39,7 +39,7 @@ Describe -Tags @("Preflight") "SharePointDsc Integration Tests - Preflight Check { Invoke-Command -Credential $Global:SPDscIntegrationCredPool.Setup -ComputerName . { - $SqlConnection = New-Object System.Data.SqlClient.SqlConnection + $SqlConnection = New-Object -TypeName System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server=$($Global:SPDscIntegrationGlobals.SQL.DatabaseServer);Database=master;Trusted_Connection=True;" $SqlConnection.Open() $SqlConnection.Close() diff --git a/Tests/Integration/SharePointDsc.IntegrationTestHarness.psm1 b/Tests/Integration/SharePointDsc.IntegrationTestHarness.psm1 index 63b4b6425..a23b68a7a 100644 --- a/Tests/Integration/SharePointDsc.IntegrationTestHarness.psm1 +++ b/Tests/Integration/SharePointDsc.IntegrationTestHarness.psm1 @@ -47,7 +47,7 @@ function Invoke-SPDscIntegrationTest() { $testResults = @{} # Execute Pre, main and Post tests for each sequence object - $testSequence | ForEach-Object { + $testSequence | ForEach-Object -Process { Write-Verbose "Starting tests for 'Pre$_'" $testResults.Add("Pre$_", (Invoke-Pester "$repoDir\Tests\Integration" -Tag "Pre$_" -PassThru)) @@ -59,7 +59,7 @@ function Invoke-SPDscIntegrationTest() { } # Output the results - $testResults.Keys | ForEach-Object { + $testResults.Keys | ForEach-Object -Process { $result = $testResults.$_ Write-Output -InputObject "$_ - Passed: $($result.PassedCount) Failed: $($result.FailedCount)" $result.TestResult | Where-Object { $_.Passed -ne $true } diff --git a/Tests/Integration/SharePointDsc/SharePointDsc.SPAccessServiceApp.Tests.ps1 b/Tests/Integration/SharePointDsc/SharePointDsc.SPAccessServiceApp.Tests.ps1 index d11493e10..5a84a0929 100644 --- a/Tests/Integration/SharePointDsc/SharePointDsc.SPAccessServiceApp.Tests.ps1 +++ b/Tests/Integration/SharePointDsc/SharePointDsc.SPAccessServiceApp.Tests.ps1 @@ -11,7 +11,7 @@ $RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\SharePointDsc.psd1") Describe -Tags @("ServiceApp") "SPAccessServiceApp - Integration Tests" { - Context "Creates a new Access Services service application" { + Context -Name "Creates a new Access Services service application" { It "Is able to create a service app" { $configName = "SPAccessServiceApp_CreateNewApp" Configuration $configName { @@ -32,7 +32,7 @@ Describe -Tags @("ServiceApp") "SPAccessServiceApp - Integration Tests" { } } - Context "Removes an existing Access Services service application" { + Context -Name "Removes an existing Access Services service application" { It "Is able to remove a service app" { $configName = "SPAccessServiceApp_RemoveApp" Configuration $configName { diff --git a/Tests/Integration/SharePointDsc/SharePointDsc.SPAlternateUrl.Tests.ps1 b/Tests/Integration/SharePointDsc/SharePointDsc.SPAlternateUrl.Tests.ps1 index 1a29ca10e..48509a82b 100644 --- a/Tests/Integration/SharePointDsc/SharePointDsc.SPAlternateUrl.Tests.ps1 +++ b/Tests/Integration/SharePointDsc/SharePointDsc.SPAlternateUrl.Tests.ps1 @@ -11,7 +11,7 @@ $RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\SharePointDsc.psd1") Describe -Tags @("PostWebApp") "SPAlternateUrl - Integration Tests" { - Context "Creates a new alternate URL" { + Context -Name "Creates a new alternate URL" { It "Is able to create a service app" { $configName = "SPAlternateUrl_CreateNewUrl" Configuration $configName { @@ -32,7 +32,7 @@ Describe -Tags @("PostWebApp") "SPAlternateUrl - Integration Tests" { } } - Context "Updates existing alternate URLs" { + Context -Name "Updates existing alternate URLs" { It "Is able to update an existing alternate URL" { $configName = "SPAlternateUrl_UpdateUrl" Configuration $configName { @@ -53,7 +53,7 @@ Describe -Tags @("PostWebApp") "SPAlternateUrl - Integration Tests" { } } - Context "Delete existing alternate URLs" { + Context -Name "Delete existing alternate URLs" { It "Is able to delete an existing alternate URL" { $configName = "SPAlternateUrl_DeleteUrl" Configuration $configName { diff --git a/Tests/Integration/SharePointDsc/SharePointDsc.SPAntivirusSettings.Tests.ps1 b/Tests/Integration/SharePointDsc/SharePointDsc.SPAntivirusSettings.Tests.ps1 index e8854530f..fc83408d9 100644 --- a/Tests/Integration/SharePointDsc/SharePointDsc.SPAntivirusSettings.Tests.ps1 +++ b/Tests/Integration/SharePointDsc/SharePointDsc.SPAntivirusSettings.Tests.ps1 @@ -11,7 +11,7 @@ $RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\SharePointDsc.psd1") Describe -Tags @("PostFarm") "SPAntivirusSettings - Integration Tests" { - Context "Applies AV settings" { + Context -Name "Applies AV settings" { It "Apply settings to the local farm" { $configName = "SPAntivirusSettings_ApplySettings" Configuration $configName { diff --git a/Tests/Integration/SharePointDsc/SharePointDsc.SPAppCatalog.Tests.ps1 b/Tests/Integration/SharePointDsc/SharePointDsc.SPAppCatalog.Tests.ps1 index 89951b80f..1ea67c555 100644 --- a/Tests/Integration/SharePointDsc/SharePointDsc.SPAppCatalog.Tests.ps1 +++ b/Tests/Integration/SharePointDsc/SharePointDsc.SPAppCatalog.Tests.ps1 @@ -11,7 +11,7 @@ $RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\SharePointDsc.psd1") Describe -Tags @("PostSite") "SPAppCatalog - Integration Tests" { - Context "Sets the app catalog location" { + Context -Name "Sets the app catalog location" { It "Is able to create a app catalog site and set it as the app catalog for the web app" { $configName = "SPAppCatalog_CreateAndSetAppCatalog" Configuration $configName { diff --git a/Tests/Integration/SharePointDsc/SharePointDsc.SPAppManagementServiceApp.Tests.ps1 b/Tests/Integration/SharePointDsc/SharePointDsc.SPAppManagementServiceApp.Tests.ps1 index eb531ff8b..0bac3d7e3 100644 --- a/Tests/Integration/SharePointDsc/SharePointDsc.SPAppManagementServiceApp.Tests.ps1 +++ b/Tests/Integration/SharePointDsc/SharePointDsc.SPAppManagementServiceApp.Tests.ps1 @@ -11,7 +11,7 @@ $RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\SharePointDsc.psd1") Describe -Tags @("PreServiceApp") "SPAppManagementServiceApp - Integration Tests" { - Context "Creates a new app management service application" { + Context -Name "Creates a new app management service application" { It "Is able to create a service app" { $configName = "SPAppManagementServiceApp_CreateNewApp" Configuration $configName { @@ -32,7 +32,7 @@ Describe -Tags @("PreServiceApp") "SPAppManagementServiceApp - Integration Tests } } - Context "Removes an existing App management service application" { + Context -Name "Removes an existing App management service application" { It "Is able to remove a service app" { $configName = "SPAppManagementServiceApp_RemoveApp" Configuration $configName { @@ -53,7 +53,7 @@ Describe -Tags @("PreServiceApp") "SPAppManagementServiceApp - Integration Tests } } - Context "Creates a new app management service application" { + Context -Name "Creates a new app management service application" { It "Is able to create a service app to persist for other service apps" { $configName = "SPAppManagementServiceApp_CreateNewApp2" Configuration $configName { diff --git a/Tests/Integration/SharePointDsc/SharePointDsc.SPCreateFarm.Tests.ps1 b/Tests/Integration/SharePointDsc/SharePointDsc.SPCreateFarm.Tests.ps1 index 1cd6377db..7b2d2473f 100644 --- a/Tests/Integration/SharePointDsc/SharePointDsc.SPCreateFarm.Tests.ps1 +++ b/Tests/Integration/SharePointDsc/SharePointDsc.SPCreateFarm.Tests.ps1 @@ -11,7 +11,7 @@ $RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\SharePointDsc.psd1") Describe -Tags @("Farm") "SPCreateFarm - Integration Tests" { - Context "Creates new farms where no farm exists" { + Context -Name "Creates new farms where no farm exists" { It "Is able to create a new farm on the local server" { $configName = "SPCreateFarm_CreateNewFarm" Configuration $configName { diff --git a/Tests/Integration/SharePointDsc/SharePointDsc.SPManagedAccount.Tests.ps1 b/Tests/Integration/SharePointDsc/SharePointDsc.SPManagedAccount.Tests.ps1 index ab5848ad3..d19cb8abc 100644 --- a/Tests/Integration/SharePointDsc/SharePointDsc.SPManagedAccount.Tests.ps1 +++ b/Tests/Integration/SharePointDsc/SharePointDsc.SPManagedAccount.Tests.ps1 @@ -11,7 +11,7 @@ $RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\SharePointDsc.psd1") Describe -Tags @("PostFarm") "SPManagedAccount - Integration Tests" { - Context "Creates new new managed accounts" { + Context -Name "Creates new new managed accounts" { It "Is able to create a new managed account" { $configName = "SPManagedAccounts_CreateNewManagedAccounts" Configuration $configName { @@ -35,7 +35,7 @@ Describe -Tags @("PostFarm") "SPManagedAccount - Integration Tests" { } } - Context "Updates managed accounts" { + Context -Name "Updates managed accounts" { It "is able to set a schedule" { $configName = "SPManagedAccounts_SetSchedules" Configuration $configName { diff --git a/Tests/Integration/SharePointDsc/SharePointDsc.SPServiceAppPool.Tests.ps1 b/Tests/Integration/SharePointDsc/SharePointDsc.SPServiceAppPool.Tests.ps1 index 75eb4f898..7fcf22fa0 100644 --- a/Tests/Integration/SharePointDsc/SharePointDsc.SPServiceAppPool.Tests.ps1 +++ b/Tests/Integration/SharePointDsc/SharePointDsc.SPServiceAppPool.Tests.ps1 @@ -11,7 +11,7 @@ $RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\SharePointDsc.psd1") Describe -Tags @("PostFarm") "SPServiceAppPool - Integration Tests" { - Context "Creates new service app pools" { + Context -Name "Creates new service app pools" { It "Is able to create service app pools" { $configName = "SPServiceAppPool_CreateNewAppPool" Configuration $configName { @@ -38,8 +38,8 @@ Describe -Tags @("PostFarm") "SPServiceAppPool - Integration Tests" { } } - Context "Updates existing pools" { - It "Updates the service account of a service app pool" { + Context -Name "Updates existing pools" { + It "Should update the service account of a service app pool" { $configName = "SPServiceAppPool_UpdateAppPool" Configuration $configName { Import-DscResource -ModuleName SharePointDsc @@ -58,8 +58,8 @@ Describe -Tags @("PostFarm") "SPServiceAppPool - Integration Tests" { } } - Context "Removes existing pools" { - It "Removes the service app pool" { + Context -Name "Removes existing pools" { + It "Should remove the service app pool" { $configName = "SPServiceAppPool_RemoveAppPool" Configuration $configName { Import-DscResource -ModuleName SharePointDsc diff --git a/Tests/Integration/SharePointDsc/SharePointDsc.SPSite.Tests.ps1 b/Tests/Integration/SharePointDsc/SharePointDsc.SPSite.Tests.ps1 index 35e99d257..9c4231a0c 100644 --- a/Tests/Integration/SharePointDsc/SharePointDsc.SPSite.Tests.ps1 +++ b/Tests/Integration/SharePointDsc/SharePointDsc.SPSite.Tests.ps1 @@ -11,7 +11,7 @@ $RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\SharePointDsc.psd1") Describe -Tags @("Site") "SPSite - Integration Tests" { - Context "Creates new new site collections" { + Context -Name "Creates new new site collections" { It "Is able to create a new path based site collection" { $configName = "SPSite_CreateNewPathBasedSite" Configuration $configName { diff --git a/Tests/Integration/SharePointDsc/SharePointDsc.SPSubscriptionSettingsServiceApp.Tests.ps1 b/Tests/Integration/SharePointDsc/SharePointDsc.SPSubscriptionSettingsServiceApp.Tests.ps1 index ee452d6f4..dcca98899 100644 --- a/Tests/Integration/SharePointDsc/SharePointDsc.SPSubscriptionSettingsServiceApp.Tests.ps1 +++ b/Tests/Integration/SharePointDsc/SharePointDsc.SPSubscriptionSettingsServiceApp.Tests.ps1 @@ -11,7 +11,7 @@ $RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\SharePointDsc.psd1") Describe -Tags @("PreServiceApp") "SPSubscriptionSettingsServiceApp - Integration Tests" { - Context "Creates a new app management service application" { + Context -Name "Creates a new app management service application" { It "Is able to create a service app" { $configName = "SPSubscriptionSettingsServiceApp_CreateNewApp" Configuration $configName { @@ -32,7 +32,7 @@ Describe -Tags @("PreServiceApp") "SPSubscriptionSettingsServiceApp - Integratio } } - Context "Removes an existing App management service application" { + Context -Name "Removes an existing App management service application" { It "Is able to remove a service app" { $configName = "SPSubscriptionSettingsServiceApp_RemoveApp" Configuration $configName { @@ -53,7 +53,7 @@ Describe -Tags @("PreServiceApp") "SPSubscriptionSettingsServiceApp - Integratio } } - Context "Creates a new app management service application" { + Context -Name "Creates a new app management service application" { It "Is able to create a service app to persist for other service apps" { $configName = "SPSubscriptionSettingsServiceApp_CreateNewApp2" Configuration $configName { diff --git a/Tests/Integration/SharePointDsc/SharePointDsc.SPWebApplication.Tests.ps1 b/Tests/Integration/SharePointDsc/SharePointDsc.SPWebApplication.Tests.ps1 index 456d8aa92..aed76e2bc 100644 --- a/Tests/Integration/SharePointDsc/SharePointDsc.SPWebApplication.Tests.ps1 +++ b/Tests/Integration/SharePointDsc/SharePointDsc.SPWebApplication.Tests.ps1 @@ -11,7 +11,7 @@ $RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\SharePointDsc.psd1") Describe -Tags @("WebApp") "SPWebApplication - Integration Tests" { - Context "Creates new new web applications" { + Context -Name "Creates new new web applications" { It "Is able to create a new web application" { $configName = "SPWebApplication_CreateWebApp" Configuration $configName { diff --git a/Tests/Unit/SharePointDsc.TestHarness.psm1 b/Tests/Unit/SharePointDsc.TestHarness.psm1 index 7816ae255..69bac0dd8 100644 --- a/Tests/Unit/SharePointDsc.TestHarness.psm1 +++ b/Tests/Unit/SharePointDsc.TestHarness.psm1 @@ -1,76 +1,206 @@ -function Invoke-SPDscUnitTestSuite() { +function Invoke-SPDscUnitTestSuite +{ param ( - [parameter(Mandatory = $false)] [System.String] $testResultsFile, - [parameter(Mandatory = $false)] [System.String] $DscTestsPath, - [parameter(Mandatory = $false)] [System.Boolean] $CalculateTestCoverage = $true + [parameter(Mandatory = $false)] + [System.String] + $TestResultsFile, + + [parameter(Mandatory = $false)] + [System.String] + $DscTestsPath, + + [parameter(Mandatory = $false)] + [System.Boolean] + $CalculateTestCoverage = $true ) Write-Verbose "Commencing SharePointDsc unit tests" - $repoDir = Join-Path $PSScriptRoot "..\..\" -Resolve + $repoDir = Join-Path -Path $PSScriptRoot -ChildPath "..\..\" -Resolve $testCoverageFiles = @() - if ($CalculateTestCoverage -eq $true) { + if ($CalculateTestCoverage -eq $true) + { Write-Warning -Message ("Code coverage statistics are being calculated. This will slow the " + ` "start of the tests by several minutes while the code matrix is " + ` "built. Please be patient") - Get-ChildItem "$repoDir\modules\SharePointDsc\**\*.psm1" -Recurse | ForEach-Object { - if ($_.FullName -notlike "*\DSCResource.Tests\*") { + Get-ChildItem "$repoDir\modules\SharePointDsc\**\*.psm1" -Recurse | ForEach-Object -Process { + if ($_.FullName -notlike "*\DSCResource.Tests\*") + { $testCoverageFiles += $_.FullName } } } - $testResultSettings = @{ } - if ([string]::IsNullOrEmpty($testResultsFile) -eq $false) { + if ([string]::IsNullOrEmpty($TestResultsFile) -eq $false) + { $testResultSettings.Add("OutputFormat", "NUnitXml" ) - $testResultSettings.Add("OutputFile", $testResultsFile) + $testResultSettings.Add("OutputFile", $TestResultsFile) } - Import-Module "$repoDir\modules\SharePointDsc\SharePointDsc.psd1" + Import-Module -Name "$repoDir\modules\SharePointDsc\SharePointDsc.psd1" - - $versionsToTest = (Get-ChildItem (Join-Path $repoDir "\Tests\Unit\Stubs\SharePoint\")).Name + $versionsPath = Join-Path -Path $repoDir -ChildPath "\Tests\Unit\Stubs\SharePoint\" + $versionsToTest = (Get-ChildItem -Path $versionsPath).Name # Import the first stub found so that there is a base module loaded before the tests start - $firstVersion = $versionsToTest | Select -First 1 - Import-Module (Join-Path $repoDir "\Tests\Unit\Stubs\SharePoint\$firstVersion\Microsoft.SharePoint.PowerShell.psm1") -WarningAction SilentlyContinue + $firstVersion = $versionsToTest | Select-Object -First 1 + $firstStub = Join-Path -Path $repoDir ` + -ChildPath "\Tests\Unit\Stubs\SharePoint\$firstVersion\Microsoft.SharePoint.PowerShell.psm1" + Import-Module $firstStub -WarningAction SilentlyContinue $testsToRun = @() - $versionsToTest | ForEach-Object { + $versionsToTest | ForEach-Object -Process { + $stubPath = Join-Path -Path $repoDir ` + -ChildPath "\Tests\Unit\Stubs\SharePoint\$_\Microsoft.SharePoint.PowerShell.psm1" $testsToRun += @(@{ 'Path' = (Join-Path -Path $repoDir -ChildPath "\Tests\Unit") 'Parameters' = @{ - 'SharePointCmdletModule' = (Join-Path $repoDir "\Tests\Unit\Stubs\SharePoint\$_\Microsoft.SharePoint.PowerShell.psm1") + 'SharePointCmdletModule' = $stubPath } }) } - if ($PSBoundParameters.ContainsKey("DscTestsPath") -eq $true) { + if ($PSBoundParameters.ContainsKey("DscTestsPath") -eq $true) + { $testsToRun += @{ 'Path' = $DscTestsPath 'Parameters' = @{ } } } $Global:VerbosePreference = "SilentlyContinue" - $results = Invoke-Pester -Script $testsToRun -CodeCoverage $testCoverageFiles -PassThru @testResultSettings + $results = Invoke-Pester -Script $testsToRun ` + -CodeCoverage $testCoverageFiles ` + -PassThru ` + @testResultSettings return $results } +function New-SPDscUnitTestHelper +{ + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [String] + $SharePointStubModule, + + [Parameter(Mandatory = $true, ParameterSetName = 'DscResource')] + [String] + $DscResource, + + [Parameter(Mandatory = $true, ParameterSetName = 'SubModule')] + [String] + $SubModulePath, + + [Parameter(Mandatory = $false)] + [Switch] + $ExcludeInvokeHelper, + + [Parameter(Mandatory = $false)] + [Switch] + $IncludeDistributedCacheStubs + ) + + $repoRoot = Join-Path -Path $PSScriptRoot -ChildPath "..\..\" -Resolve + $moduleRoot = Join-Path -Path $repoRoot -ChildPath "Modules\SharePointDsc" + + if ($PSBoundParameters.ContainsKey("SubModulePath") -eq $true) + { + $describeHeader = "Sub-module '$SubModulePath'" + $moduleToLoad = Join-Path -Path $moduleRoot -ChildPath $SubModulePath + $moduleName = (Get-Item -Path $moduleToLoad).BaseName + } + + if ($PSBoundParameters.ContainsKey("DscResource") -eq $true) + { + $describeHeader = "DSC Resource '$DscResource'" + $moduleName = "MSFT_$DscResource" + $modulePath = "DSCResources\MSFT_$DscResource\MSFT_$DscResource.psm1" + $moduleToLoad = Join-Path -Path $moduleRoot -ChildPath $modulePath + } + + $spBuild = (Get-Item -Path $SharePointStubModule).Directory.BaseName + $firstDot = $spBuild.IndexOf(".") + $majorBuildNumber = $spBuild.Substring(0, $firstDot) + + $describeHeader += " [SP Build: $spBuild]" + + Import-Module -Name $moduleToLoad -Global + + + + $initScript = @" + Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue + Import-Module -Name "$SharePointStubModule" -WarningAction SilentlyContinue + Import-Module -Name "$moduleToLoad" + + Mock -CommandName Get-SPDSCInstalledProductVersion -MockWith { + return @{ + FileMajorPart = $majorBuildNumber + } + } + + Mock -CommandName Get-SPDSCAssemblyVersion -MockWith { + return $majorBuildNumber + } + +"@ + + if ($ExcludeInvokeHelper -eq $false) + { + $initScript += @" + Mock Invoke-SPDSCCommand { + return Invoke-Command -ScriptBlock `$ScriptBlock -ArgumentList `$Arguments -NoNewScope + } +"@ + } + + if ($IncludeDistributedCacheStubs -eq $true) + { + $dcachePath = Join-Path -Path $repoRoot ` + -ChildPath "Tests\Unit\Stubs\DistributedCache\DistributedCache.psm1" + $initScript += @" + + Import-Module -Name "$dcachePath" -WarningAction SilentlyContinue + +"@ + } + + return @{ + DescribeHeader = $describeHeader + ModuleName = $moduleName + CurrentStubModulePath = $SharePointStubModule + CurrentStubBuildNumber = [Version]::Parse($spBuild) + InitializeScript = [ScriptBlock]::Create($initScript) + RepoRoot = $repoRoot + CleanupScript = [ScriptBlock]::Create(@" + + Get-Variable -Scope Global -Name "SPDsc*" | Remove-Variable -Force -Scope "Global" + `$global:DSCMachineStatus = 0 + +"@) + } +} + function Write-SPDSCStubFile() { param ( - [parameter(Mandatory = $true)] [System.String] $SharePointStubPath + [parameter(Mandatory = $true)] + [System.String] + $SharePointStubPath ) Add-PSSnapin Microsoft.SharePoint.PowerShell - $SPStubContent = ((Get-Command | Where-Object { $_.Source -eq "Microsoft.SharePoint.PowerShell" } ) | ForEach-Object -Process { + $SPStubContent = ((Get-Command | Where-Object -FilterScript { + $_.Source -eq "Microsoft.SharePoint.PowerShell" + } ) | ForEach-Object -Process { $signature = $null $command = $_ - $metadata = New-Object -TypeName System.Management.Automation.CommandMetaData -ArgumentList $command + $metadata = New-Object -TypeName System.Management.Automation.CommandMetaData ` + -ArgumentList $command $definition = [System.Management.Automation.ProxyCommand]::Create($metadata) foreach ($line in $definition -split "`n") { @@ -83,12 +213,13 @@ function Write-SPDSCStubFile() { "function $($command.Name) { `n $signature `n } `n" }) | Out-String - foreach ($line in $SPStubContent.Split([Environment]::NewLine)) { + foreach ($line in $SPStubContent.Split([Environment]::NewLine)) + { $line = $line.Replace("[System.Nullable``1[[Microsoft.Office.Server.Search.Cmdlet.ContentSourceCrawlScheduleType, Microsoft.Office.Server.Search.PowerShell, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]", "[object]") $line = $line.Replace("[System.Collections.Generic.List``1[[Microsoft.SharePoint.PowerShell.SPUserLicenseMapping, Microsoft.SharePoint.PowerShell, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]", "[object]") $line = $line -replace "\[System.Nullable\[Microsoft.*]]", "[System.Nullable[object]]" $line = $line -replace "\[Microsoft.*.\]", "[object]" - $line | Out-File $SharePointStubPath -Encoding utf8 -Append + $line | Out-File -FilePath $SharePointStubPath -Encoding utf8 -Append } } \ No newline at end of file diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.Global.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.Global.Tests.ps1 index 5a0759460..2ba7c7b96 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.Global.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.Global.Tests.ps1 @@ -11,9 +11,19 @@ $RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path Describe 'SharePointDsc whole of module tests' { - Context "Validate example files" { + Context -Name "Validate example files" { - It "should compile MOFs for all examples correctly" { + It "Should compile MOFs for all examples correctly" { + + ## For Appveyor builds copy the module to the system modules directory so it falls + ## in to a PSModulePath folder and is picked up correctly. + if ($env:APPVEYOR -eq $true) + { + Copy-item -Path "$env:APPVEYOR_BUILD_FOLDER\Modules\SharePointDsc" ` + -Destination 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\SharePointDsc' ` + -Recurse + } + $examplesWithErrors = 0 $dummyPassword = ConvertTo-SecureString "-" -AsPlainText -Force $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList @("username", $dummyPassword) @@ -34,7 +44,7 @@ Describe 'SharePointDsc whole of module tests' { ) } - Get-ChildItem "$RepoRoot\Modules\SharePointDsc\Examples" -Filter "*.ps1" -Recurse | ForEach-Object -Process { + Get-ChildItem -Path "$RepoRoot\Modules\SharePointDsc\Examples" -Filter "*.ps1" -Recurse | ForEach-Object -Process { $path = $_.FullName try { @@ -54,7 +64,15 @@ Describe 'SharePointDsc whole of module tests' { Write-Warning $_.Exception.Message } } - $examplesWithErrors | Should Be 0 + $examplesWithErrors | Should Be 0 + + if ($env:APPVEYOR -eq $true) + { + Remove-item -Path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\SharePointDsc' ` + -Recurse -Force -Confirm:$false + # Restore the load of the module to ensure future tests have access to it + Import-Module -Name "$RepoRoot\modules\SharePointDsc\SharePointDsc.psd1" -Global -Force + } } } } diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPAccessServiceApp.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPAccessServiceApp.Tests.ps1 index 5f6e7b2b1..b6620f888 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPAccessServiceApp.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPAccessServiceApp.Tests.ps1 @@ -1,126 +1,176 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPAccessServiceApp" -$ModuleName = "MSFT_SPAccessServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPAccessServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Test Access Services App" - DatabaseServer = "SQL.contoso.local" - ApplicationPool = "Test App Pool" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") + # Initialize tests + $getTypeFullName = "Microsoft.Office.Access.Services.MossHost.AccessServicesWebServiceApplication" - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Mock New-SPAccessServicesApplication { } - Mock Set-SPAccessServicesApplication { } - Mock Remove-SPServiceApplication { } + # Mocks for all contexts + Mock -CommandName New-SPAccessServicesApplication -MockWith { } + Mock -CommandName Set-SPAccessServicesApplication -MockWith { } + Mock -CommandName Remove-SPServiceApplication -MockWith { } - Context "When no service applications exist in the current farm" { + # Test contexts + Context -Name "When no service applications exist in the current farm" -Fixture { + $testParams = @{ + Name = "Test Access Services App" + DatabaseServer = "SQL.contoso.local" + ApplicationPool = "Test App Pool" + } - Mock Get-SPServiceApplication { return $null } + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns null from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams - Assert-MockCalled New-SPAccessServicesApplication + Assert-MockCalled New-SPAccessServicesApplication } } - Context "When service applications exist in the current farm but the specific Access Services app does not" { + Context -Name "When service applications exist in the current farm but the specific Access Services app does not" -Fixture { + $testParams = @{ + Name = "Test Access Services App" + DatabaseServer = "SQL.contoso.local" + ApplicationPool = "Test App Pool" + } - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Some other service app type" - }) } + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = "Microsoft.Office.UnKnownWebServiceApplication" + } + } -PassThru -Force + return $spServiceApp + } - It "returns null from the Get method" { + It "Should return null from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - } - Context "When a service application exists and is configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When a service application exists and is configured correctly" -Fixture { + $testParams = @{ + Name = "Test Access Services App" + DatabaseServer = "SQL.contoso.local" + ApplicationPool = "Test App Pool" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Access Services Web Service Application" DisplayName = $testParams.Name - DatabaseServer = $testParams.DatebaseName + DatabaseServer = $testParams.DatabaseName ApplicationPool = @{ Name = $testParams.ApplicationPool } - }) + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = $getTypeFullName + } + } -PassThru -Force + return $spServiceApp } - It "returns values from the get method" { - (Get-TargetResource @testParams).Ensure | Should Be "Present" + It "Should return Present from the get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } - $testParams = @{ - Name = "Test App" - ApplicationPool = "-" - DatabaseServer = "-" - Ensure = "Absent" - } - Context "When the service application exists but it shouldn't" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When the service application exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + DatabaseServer = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Access Services Web Service Application" DisplayName = $testParams.Name - DatabaseServer = $testParams.DatabaseServer + DatabaseServer = $testParams.DatabaseName ApplicationPool = @{ Name = $testParams.ApplicationPool } - }) + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = $getTypeFullName + } + } -PassThru -Force + return $spServiceApp } - It "returns present from the Get method" { + It "Should return present from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "calls the remove service application cmdlet in the set method" { + It "Should call the remove service application cmdlet in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplication } } - Context "When the serivce application doesn't exist and it shouldn't" { - Mock Get-SPServiceApplication { return $null } + Context -Name "When the serivce application doesn't exist and it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + DatabaseServer = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPAlternateUrl.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPAlternateUrl.Tests.ps1 index c36509d6e..494af9b22 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPAlternateUrl.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPAlternateUrl.Tests.ps1 @@ -1,61 +1,64 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPAlternateUrl" -$ModuleName = "MSFT_SPAlternateUrl" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPAlternateUrl - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - WebAppUrl = "http://test.constoso.local" - Zone = "Default" - Ensure = "Present" - Url = "http://something.contoso.local" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } + # Mocks for all contexts + Mock -CommandName New-SPAlternateURL {} + Mock -CommandName Set-SPAlternateURL {} + Mock -CommandName Remove-SPAlternateURL {} - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue + # Test contexts + Context -Name "No alternate URL exists for the specified zone and web app, and there should be" -Fixture { + $testParams = @{ + WebAppUrl = "http://test.constoso.local" + Zone = "Default" + Ensure = "Present" + Url = "http://something.contoso.local" + } - Mock New-SPAlternateURL {} - Mock Set-SPAlternateURL {} - Mock Remove-SPAlternateURL {} - - Context "No alternate URL exists for the specified zone and web app, and there should be" { - - Mock Get-SPAlternateUrl { + Mock -CommandName Get-SPAlternateUrl -MockWith { return @() } - it "returns an empty URL in the get method" { + It "Should return an empty URL in the get method" { (Get-TargetResource @testParams).Url | Should BeNullOrEmpty } - it "return false from the test method" { + It "Should return false from the test method" { Test-targetResource @testParams | Should Be $false } - it "calls the new function in the set method" { + It "Should call the new function in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPAlternateURL } } - Context "A URL exists for the specified zone and web app, but the URL is wrong" { - - Mock Get-SPAlternateUrl { + Context -Name "A URL exists for the specified zone and web app, but the URL is wrong" -Fixture { + $testParams = @{ + WebAppUrl = "http://test.constoso.local" + Zone = "Default" + Ensure = "Present" + Url = "http://something.contoso.local" + } + + Mock -CommandName Get-SPAlternateUrl -MockWith { return @( @{ IncomingUrl = $testParams.WebAppUrl @@ -65,23 +68,29 @@ Describe "SPAlternateUrl - SharePoint Build $((Get-Item $SharePointCmdletModule) ) } - it "returns the wrong URL in the get method" { + It "Should return the wrong URL in the get method" { (Get-TargetResource @testParams).Url | Should Not Be $testParams.Url } - it "returns false from the test method" { + It "Should return false from the test method" { Test-targetResource @testParams | Should Be $false } - it "calls the set cmdlet from the set method" { + It "Should call the set cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Set-SPAlternateURL } } - Context "A URL exists for the specified zone and web app, and it is correct" { - - Mock Get-SPAlternateUrl { + Context -Name "A URL exists for the specified zone and web app, and it is correct" -Fixture { + $testParams = @{ + WebAppUrl = "http://test.constoso.local" + Zone = "Default" + Ensure = "Present" + Url = "http://something.contoso.local" + } + + Mock -CommandName Get-SPAlternateUrl -MockWith { return @( @{ IncomingUrl = $testParams.WebAppUrl @@ -91,18 +100,24 @@ Describe "SPAlternateUrl - SharePoint Build $((Get-Item $SharePointCmdletModule) ) } - it "returns the correct URL in the get method" { + It "Should return the correct URL in the get method" { (Get-TargetResource @testParams).Url | Should Be $testParams.Url } - it "returns true from the test method" { + It "Should return true from the test method" { Test-targetResource @testParams | Should Be $true } } - Context "A URL exists for the specified zone and web app, and it should not" { - - Mock Get-SPAlternateUrl { + Context -Name "A URL exists for the specified zone and web app, and it should not" -Fixture { + $testParams = @{ + WebAppUrl = "http://test.constoso.local" + Zone = "Default" + Ensure = "Absent" + Url = "http://something.contoso.local" + } + + Mock -CommandName Get-SPAlternateUrl -MockWith { return @( @{ IncomingUrl = $testParams.WebAppUrl @@ -111,44 +126,59 @@ Describe "SPAlternateUrl - SharePoint Build $((Get-Item $SharePointCmdletModule) } ) } - $testParams.Ensure = "Absent" - it "returns false from the test method" { + It "Should return false from the test method" { Test-targetResource @testParams | Should Be $false } - it "calls the remove cmdlet from the set method" { + It "Should call the remove cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPAlternateURL } } - Context "A URL does not exist for the current zone, and it should not" { + Context -Name "A URL does not exist for the current zone, and it should not" -Fixture { + $testParams = @{ + WebAppUrl = "http://test.constoso.local" + Zone = "Default" + Ensure = "Absent" + Url = "http://something.contoso.local" + } - Mock Get-SPAlternateUrl { + Mock -CommandName Get-SPAlternateUrl -MockWith { return @() } - it "returns the empty values in the get method" { + It "Should return the empty values in the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - it "returns true from the test method" { + It "Should return true from the test method" { Test-targetResource @testParams | Should Be $true } - $testParams.Remove("Url") - it "still returns true from the test method with the URL property not providing" { + + $testParams = @{ + WebAppUrl = "http://test.constoso.local" + Zone = "Default" + Ensure = "Absent" + } + It "Should still return true from the test method with the URL property not provided" { Test-targetResource @testParams | Should Be $true } - $testParams.Add("Url", "http://something.contoso.local") } - Context "The default zone URL for a web app was changed using this resource" { - - Mock Get-SPAlternateUrl { + Context -Name "The default zone URL for a web app was changed using this resource" -Fixture { + $testParams = @{ + WebAppUrl = "http://test.constoso.local" + Zone = "Default" + Ensure = "Present" + Url = "http://something.contoso.local" + } + + Mock -CommandName Get-SPAlternateUrl -MockWith { return @() } -ParameterFilter { $WebApplication -eq $testParams.WebAppUrl } - Mock Get-SPAlternateUrl { + Mock -CommandName Get-SPAlternateUrl -MockWith { return @( @{ IncomingUrl = $testParams.Url @@ -157,12 +187,12 @@ Describe "SPAlternateUrl - SharePoint Build $((Get-Item $SharePointCmdletModule) } ) } -ParameterFilter { $null -eq $WebApplication } - $testParams.Ensure = "Present" - it "should still return true in the test method despite the web app URL being different" { + It "Should still return true in the test method despite the web app URL being different" { Test-TargetResource @testParams | Should Be $true } } - } + } } +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPAntivirusSettings.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPAntivirusSettings.Tests.ps1 index 8996badda..391c4917d 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPAntivirusSettings.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPAntivirusSettings.Tests.ps1 @@ -1,40 +1,39 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPAntivirusSettings" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPAntivirusSettings - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - ScanOnDownload = $true - ScanOnUpload = $true - AllowDownloadInfected = $true - AttemptToClean = $true - TimeoutDuration = 60 - NumberOfThreads = 5 - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPAntivirusSettings" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Test contexts + Context -Name "The server is not part of SharePoint farm" -Fixture { + $testParams = @{ + ScanOnDownload = $true + ScanOnUpload = $true + AllowDownloadInfected = $true + AttemptToClean = $true + TimeoutDuration = 60 + NumberOfThreads = 5 + } - Context "The server is not part of SharePoint farm" { - Mock Get-SPFarm { throw "Unable to detect local farm" } + Mock -CommandName Get-SPFarm -MockWith { + throw "Unable to detect local farm" + } - It "return null from the get method" { + It "Should return null from the get method" { $result = Get-TargetResource @testParams $result.AllowDownloadInfected | Should Be $false $result.ScanOnDownload | Should Be $false @@ -44,17 +43,26 @@ Describe "SPAntivirusSettings - SharePoint Build $((Get-Item $SharePointCmdletMo $result.TimeoutDuration | Should Be 0 } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws an exception in the set method to say there is no local farm" { + It "Should throw an exception in the set method to say there is no local farm" { { Set-TargetResource @testParams } | Should throw "No local SharePoint farm was detected" } } - Context "The server is in a farm and the incorrect settings have been applied" { - Mock Get-SPDSCContentService { + Context -Name "The server is in a farm and the incorrect settings have been applied" -Fixture { + $testParams = @{ + ScanOnDownload = $true + ScanOnUpload = $true + AllowDownloadInfected = $true + AttemptToClean = $true + TimeoutDuration = 60 + NumberOfThreads = 5 + } + + Mock -CommandName Get-SPDSCContentService -MockWith { $returnVal = @{ AntivirusSettings = @{ AllowDownload = $false @@ -67,28 +75,39 @@ Describe "SPAntivirusSettings - SharePoint Build $((Get-Item $SharePointCmdletMo } } } - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCAntivirusUpdated = $true } -PassThru + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscAntivirusUpdated = $true + } -PassThru return $returnVal } - Mock Get-SPFarm { return @{} } + Mock -CommandName Get-SPFarm -MockWith { return @{} } - It "return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPDSCAntivirusUpdated = $false - It "updates the antivirus settings" { + $Global:SPDscAntivirusUpdated = $false + It "Should update the antivirus settings" { Set-TargetResource @testParams - $Global:SPDSCAntivirusUpdated | Should Be $true + $Global:SPDscAntivirusUpdated | Should Be $true } } - Context "The server is in a farm and the correct settings have been applied" { - Mock Get-SPDSCContentService { + Context -Name "The server is in a farm and the correct settings have been applied" -Fixture { + $testParams = @{ + ScanOnDownload = $true + ScanOnUpload = $true + AllowDownloadInfected = $true + AttemptToClean = $true + TimeoutDuration = 60 + NumberOfThreads = 5 + } + + Mock -CommandName Get-SPDSCContentService -MockWith { $returnVal = @{ AntivirusSettings = @{ AllowDownload = $true @@ -100,20 +119,20 @@ Describe "SPAntivirusSettings - SharePoint Build $((Get-Item $SharePointCmdletMo TotalSeconds = 60; } } - } - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCAntivirusUpdated = $true } -PassThru + } return $returnVal } - Mock Get-SPFarm { return @{} } + Mock -CommandName Get-SPFarm -MockWith { return @{} } - It "return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } - } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPAppCatalog.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPAppCatalog.Tests.ps1 index 51a67415c..118acafae 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPAppCatalog.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPAppCatalog.Tests.ps1 @@ -1,108 +1,127 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPAppCatalog" -$ModuleName = "MSFT_SPAppCatalog" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPAppCatalog - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - SiteUrl = "https://content.sharepoint.contoso.com/sites/AppCatalog" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - $mockSiteId = [Guid]::NewGuid() - Context "The specified site exists, but cannot be set as an app catalog as it is of the wrong template" { - Mock Update-SPAppCatalogConfiguration { throw 'Exception' } - Mock Get-SPSite { + # Test contexts + Context -Name "The specified site exists, but cannot be set as an app catalog as it is of the wrong template" -Fixture { + $testParams = @{ + SiteUrl = "https://content.sharepoint.contoso.com/sites/AppCatalog" + } + + Mock -CommandName Update-SPAppCatalogConfiguration -MockWith { throw 'Exception' } + Mock -CommandName Get-SPSite -MockWith { return @{ WebApplication = @{ - Features = @( @{} ) | Add-Member ScriptMethod Item { return $null } -PassThru -Force + Features = @( @{} ) | Add-Member -MemberType ScriptMethod ` + -Name "Item" ` + -Value { return $null } ` + -PassThru ` + -Force } ID = $mockSiteId } } - It "returns null from the get method" { + It "Should return null from the get method" { (Get-TargetResource @testParams).SiteUrl | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws exception when executed" { + It "Should throw exception when executed" { { Set-TargetResource @testParams } | Should throw } } - Context "The specified site exists but is not set as the app catalog for its web application" { - Mock Update-SPAppCatalogConfiguration { } - Mock Get-SPSite { + Context -Name "The specified site exists but is not set as the app catalog for its web application" -Fixture { + $testParams = @{ + SiteUrl = "https://content.sharepoint.contoso.com/sites/AppCatalog" + } + + Mock -CommandName Update-SPAppCatalogConfiguration -MockWith { } + Mock -CommandName Get-SPSite -MockWith { return @{ WebApplication = @{ - Features = @( @{} ) | Add-Member ScriptMethod Item { return $null } -PassThru -Force + Features = @( @{} ) | Add-Member -MemberType ScriptMethod ` + -Name "Item" ` + -Value { return $null } ` + -PassThru ` + -Force } ID = $mockSiteId } } - It "returns null from the get method" { + It "Should return null from the get method" { (Get-TargetResource @testParams).SiteUrl | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "Updates the settings" { + It "Should update the settings in the set method" { Set-TargetResource @testParams Assert-MockCalled Update-SPAppCatalogConfiguration } } - Context "The specified site exists and is the current app catalog already" { - Mock Get-SPSite { + Context -Name "The specified site exists and is the current app catalog already" -Fixture { + $testParams = @{ + SiteUrl = "https://content.sharepoint.contoso.com/sites/AppCatalog" + } + + Mock -CommandName Get-SPSite -MockWith { return @{ WebApplication = @{ - Features = @( @{} ) | Add-Member ScriptMethod Item { return @{ - ID = [guid]::NewGuid() - Properties = @{ - "__AppCatSiteId" = @{Value = $mockSiteId} - } - } } -PassThru -Force + Features = @( @{} ) | Add-Member -MemberType ScriptMethod ` + -Name "Item" ` + -Value { + return @{ + ID = [guid]::NewGuid() + Properties = @{ + "__AppCatSiteId" = @{Value = $mockSiteId} + } + } + } ` + -PassThru ` + -Force } ID = $mockSiteId Url = $testParams.SiteUrl } } - It "returns value from the get method" { + It "Should return value from the get method" { (Get-TargetResource @testParams).SiteUrl | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - } + } } - +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPAppDomain.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPAppDomain.Tests.ps1 index 380a9976a..958ac4178 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPAppDomain.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPAppDomain.Tests.ps1 @@ -1,87 +1,94 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPAppDomain" -$ModuleName = "MSFT_SPAppDomain" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPAppDomain - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - AppDomain = "apps.contoso.com" - Prefix = "apps" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - - Mock Set-SPAppDomain {} - Mock Set-SPAppSiteSubscriptionName {} - - Context "No app URLs have been configured locally" { - Mock Get-SPAppDomain { } - Mock Get-SPAppSiteSubscriptionName { } - - It "returns values from the get method" { + # Mocks for all contexts + Mock -CommandName Set-SPAppDomain -MockWith {} + Mock -CommandName Set-SPAppSiteSubscriptionName -MockWith {} + + # Test contexts + Context -Name "No app URLs have been configured locally" -Fixture { + $testParams = @{ + AppDomain = "apps.contoso.com" + Prefix = "apps" + } + + Mock -CommandName Get-SPAppDomain -MockWith { } + Mock -CommandName Get-SPAppSiteSubscriptionName -MockWith { } + + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "saves settings when executed" { + It "Should save settings when the set method is run" { Set-TargetResource @testParams Assert-MockCalled Set-SPAppDomain Assert-MockCalled Set-SPAppSiteSubscriptionName } } - Context "Incorrect app URLs have been configured locally" { - Mock Get-SPAppDomain { return "wrong.domain" } - Mock Get-SPAppSiteSubscriptionName { return "wrongprefix" } + Context -Name "Incorrect app URLs have been configured locally" -Fixture { + $testParams = @{ + AppDomain = "apps.contoso.com" + Prefix = "apps" + } + + Mock -CommandName Get-SPAppDomain -MockWith { return "wrong.domain" } + Mock -CommandName Get-SPAppSiteSubscriptionName -MockWith { return "wrongprefix" } - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "saves settings when executed" { + It "Should save settings when the set method is run" { Set-TargetResource @testParams Assert-MockCalled Set-SPAppDomain Assert-MockCalled Set-SPAppSiteSubscriptionName } } - Context "Correct app URLs have been configured locally" { - Mock Get-SPAppDomain { return $testParams.AppDomain } - Mock Get-SPAppSiteSubscriptionName { $testParams.Prefix } + Context -Name "Correct app URLs have been configured locally" -Fixture { + $testParams = @{ + AppDomain = "apps.contoso.com" + Prefix = "apps" + } + + Mock -CommandName Get-SPAppDomain -MockWith { return $testParams.AppDomain } + Mock -CommandName Get-SPAppSiteSubscriptionName -MockWith { $testParams.Prefix } - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - } + } } - +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPAppManagementServiceApp.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPAppManagementServiceApp.Tests.ps1 index 4e8012474..f2882de1e 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPAppManagementServiceApp.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPAppManagementServiceApp.Tests.ps1 @@ -1,74 +1,99 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPAppManagementServiceApp" -$ModuleName = "MSFT_SPAppManagementServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPAppManagementServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Test App" - ApplicationPool = "Test App Pool" - DatabaseName = "Test_DB" - Ensure = "Present" - DatabaseServer = "TestServer\Instance" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") + #initialise tests + $getTypeFullName = "Microsoft.SharePoint.AppManagement.AppManagementServiceApplication" - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Mock Remove-SPServiceApplication { } + # Mocks for all contexts + Mock -CommandName Remove-SPServiceApplication -MockWith { } - Context "When no service applications exist in the current farm but it should" { + # Test contexts + Context -Name "When no service applications exist in the current farm but it should" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "Test App Pool" + DatabaseName = "Test_DB" + Ensure = "Present" + DatabaseServer = "TestServer\Instance" + } - Mock Get-SPServiceApplication { return $null } - Mock New-SPAppManagementServiceApplication { return @(@{})} - Mock New-SPAppManagementServiceApplicationProxy{ return $null } + Mock -CommandName Get-SPServiceApplication -MockWith { return $null } + Mock -CommandName New-SPAppManagementServiceApplication -MockWith { return @(@{})} + Mock -CommandName New-SPAppManagementServiceApplicationProxy -MockWith { return $null } - It "returns absent from the Get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.Name } } - It "returns false when the Test method is called" { + It "Should return false when the test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPAppManagementServiceApplication } } - Context "When service applications exist in the current farm with the same name but is the wrong type" { - - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Some other service app type" - }) } - - It "returns absent from the Get method" { + Context -Name "When service applications exist in the current farm with the same name but is the wrong type" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "Test App Pool" + DatabaseName = "Test_DB" + Ensure = "Present" + DatabaseServer = "TestServer\Instance" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = "Microsoft.Office.UnKnownWebServiceApplication" + } + } -PassThru -Force + return $spServiceApp + } + + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.Name } } } - Context "When a service application exists and it should, and is also configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When a service application exists and it should, and is also configured correctly" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "Test App Pool" + DatabaseName = "Test_DB" + Ensure = "Present" + DatabaseServer = "TestServer\Instance" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "App Management Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool } @@ -76,76 +101,92 @@ Describe "SPAppManagementServiceApp - SharePoint Build $((Get-Item $SharePointCm Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.Name } } - It "returns true when the Test method is called" { + It "Should return true when the test method is called" { Test-TargetResource @testParams | Should Be $true } } - Context "When a service application exists and it should, but the app pool is not configured correctly" { - Mock Get-SPServiceApplication { - $service = @(@{ + Context -Name "When a service application exists and it should, but the app pool is not configured correctly" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "Test App Pool" + DatabaseName = "Test_DB" + Ensure = "Present" + DatabaseServer = "TestServer\Instance" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "App Management Service Application" DisplayName = $testParams.Name - ApplicationPool = @{ Name = "Wrong App Pool Name" } + ApplicationPool = @{ Name = "Wrong app pool" } Database = @{ Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force - $service = $service | Add-Member ScriptMethod Update { - $Global:SPAppServiceUpdateCalled = $true + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscAppServiceUpdateCalled = $true } -PassThru - return $service + return $spServiceApp } - Mock Get-SPServiceApplicationPool { + Mock -CommandName Get-SPServiceApplicationPool -MockWith { @{ Name = $testParams.ApplicationPool } } - It "returns false when the Test method is called" { + It "Should return false when the test method is called" { Test-TargetResource @testParams | Should Be $false } - $Global:SPAppServiceUpdateCalled = $false - It "calls the update service app cmdlet from the set method" { + $Global:SPDscAppServiceUpdateCalled = $false + It "Should call the update service app cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Get-SPServiceApplicationPool - $Global:SPAppServiceUpdateCalled | Should Be $true + $Global:SPDscAppServiceUpdateCalled | Should Be $true } } - Context "When a service app needs to be created and no database paramsters are provided" { + Context -Name "When a service app needs to be created and no database paramsters are provided" -Fixture { $testParams = @{ Name = "Test App" ApplicationPool = "Test App Pool" Ensure = "Present" } - Mock Get-SPServiceApplication { return $null } - Mock New-SPAppManagementServiceApplication { return @(@{})} - Mock New-SPAppManagementServiceApplicationProxy{ return $null } + Mock -CommandName Get-SPServiceApplication -MockWith { return $null } + Mock -CommandName New-SPAppManagementServiceApplication -MockWith { return @(@{})} + Mock -CommandName New-SPAppManagementServiceApplicationProxy -MockWith { return $null } - it "should not throw an exception in the set method" { + It "Should not throw an exception in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPAppManagementServiceApplication } } - $testParams = @{ - Name = "Test App" - ApplicationPool = "-" - Ensure = "Absent" - } - Context "When the service application exists but it shouldn't" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When the service application exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "App Management Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool } @@ -153,33 +194,45 @@ Describe "SPAppManagementServiceApp - SharePoint Build $((Get-Item $SharePointCm Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns present from the Get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false when the Test method is called" { + It "Should return false when the test method is called" { Test-TargetResource @testParams | Should Be $false } - It "calls the remove service application cmdlet in the set method" { + It "Should call the remove service application cmdlet in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplication } } - Context "When the serivce application doesn't exist and it shouldn't" { - Mock Get-SPServiceApplication { return $null } + Context -Name "When the serivce application doesn't exist and it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } - It "returns absent from the Get method" { + Mock -CommandName Get-SPServiceApplication -MockWith { return $null } + + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns true when the Test method is called" { + It "Should returns true when the test method is called" { Test-TargetResource @testParams | Should Be $true } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPAppStoreSettings.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPAppStoreSettings.Tests.ps1 new file mode 100644 index 000000000..5f2d3585f --- /dev/null +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPAppStoreSettings.Tests.ps1 @@ -0,0 +1,169 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) +) + +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPAppStoreSettings" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Initialize tests + + # Mocks for all contexts + Mock -CommandName Set-SPAppAcquisitionConfiguration -MockWith {} + Mock -CommandName Set-SPOfficeStoreAppsDefaultActivation -MockWith {} + + # Test contexts + Context -Name "The specified web application does not exist" -Fixture { + $testParams = @{ + WebAppUrl = "https://sharepoint.contoso.com" + AllowAppPurchases = $true + AllowAppsForOffice = $true + } + + Mock -CommandName Get-SPWebApplication -MockWith { + return $null + } + + It "Should return null from the get method" { + (Get-TargetResource @testParams).WebAppUrl | Should BeNullOrEmpty + } + + It "Should return false from the test method" { + Test-TargetResource @testParams | Should Be $false + } + + It "Should throw exception when executed" { + { Set-TargetResource @testParams } | Should Throw "Specified web application does not exist." + } + } + + Context -Name "The specified settings do not match" -Fixture { + $testParams = @{ + WebAppUrl = "https://sharepoint.contoso.com" + AllowAppPurchases = $true + AllowAppsForOffice = $true + } + + Mock -CommandName Get-SPAppAcquisitionConfiguration -MockWith { + return @{ + Enabled = $false + } + } + Mock -CommandName Get-SPOfficeStoreAppsDefaultActivation -MockWith { + return @{ + Enable = $false + } + } + + Mock -CommandName Get-SPWebApplication -MockWith { + return @{ + Url = "https://sharepoint.contoso.com" + } + } + + It "Should return values from the get method" { + $result = Get-TargetResource @testParams + $result.AllowAppPurchases | Should Be $false + $result.AllowAppsForOffice | Should Be $false + } + + It "Should return false from the test method" { + Test-TargetResource @testParams | Should Be $false + } + + It "Should update the settings" { + Set-TargetResource @testParams + Assert-MockCalled Set-SPAppAcquisitionConfiguration + Assert-MockCalled Set-SPOfficeStoreAppsDefaultActivation + } + } + + Context -Name "The specified settings match" -Fixture { + $testParams = @{ + WebAppUrl = "https://sharepoint.contoso.com" + AllowAppPurchases = $true + AllowAppsForOffice = $true + } + + Mock -CommandName Get-SPAppAcquisitionConfiguration -MockWith { + return @{ + Enabled = $true + } + } + Mock -CommandName Get-SPOfficeStoreAppsDefaultActivation -MockWith { + return @{ + Enable = $true + } + } + + Mock -CommandName Get-SPWebApplication -MockWith { + return @{ + Url = "https://sharepoint.contoso.com" + } + } + + It "Should return values from the get method" { + $result = Get-TargetResource @testParams + $result.AllowAppPurchases | Should Be $true + $result.AllowAppsForOffice | Should Be $true + } + + It "Should returns false from the test method" { + Test-TargetResource @testParams | Should Be $true + } + } + + Context -Name "The specified setting does not match" -Fixture { + $testParams = @{ + WebAppUrl = "https://sharepoint.contoso.com" + AllowAppPurchases = $true + } + + Mock -CommandName Get-SPAppAcquisitionConfiguration -MockWith { + return @{ + Enabled = $false + } + } + Mock -CommandName Get-SPOfficeStoreAppsDefaultActivation -MockWith { + return @{ + Enable = $true + } + } + + Mock -CommandName Get-SPWebApplication -MockWith { + return @{ + Url = "https://sharepoint.contoso.com" + } + } + + It "Should return values from the get method" { + $result = Get-TargetResource @testParams + $result.AllowAppPurchases | Should Be $false + $result.AllowAppsForOffice | Should Be $true + } + + It "Should return false from the test method" { + Test-TargetResource @testParams | Should Be $false + } + + It "Should update the settings" { + Set-TargetResource @testParams + Assert-MockCalled Set-SPAppAcquisitionConfiguration + } + } + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPBCSServiceApp.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPBCSServiceApp.Tests.ps1 index a0ef6fcbd..0357e0b0d 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPBCSServiceApp.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPBCSServiceApp.Tests.ps1 @@ -1,74 +1,97 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPBCSServiceApp" -$ModuleName = "MSFT_SPBCSServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPBCSServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Test App" - ApplicationPool = "Test App Pool" - DatabaseName = "Test_DB" - DatabaseServer = "TestServer\Instance" - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + #Initialise tests + $getTypeFullName = "Microsoft.SharePoint.BusinessData.SharedService.BdcServiceApplication" - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Remove-SPServiceApplication { } + # Mocks for all contexts + Mock -CommandName Remove-SPServiceApplication -MockWith { } - Context "When no service applications exist in the current farm and it should" { + # Test contexts + Context -Name "When no service applications exist in the current farm and it should" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "Test App Pool" + DatabaseName = "Test_DB" + DatabaseServer = "TestServer\Instance" + Ensure = "Present" + } - Mock Get-SPServiceApplication { return $null } - Mock New-SPBusinessDataCatalogServiceApplication { } + Mock -CommandName Get-SPServiceApplication -MockWith { return $null } + Mock -CommandName New-SPBusinessDataCatalogServiceApplication -MockWith { } - It "returns absent from the Get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.Name } } - It "returns false when the Test method is called" { + It "Should return false when the test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPBusinessDataCatalogServiceApplication } } - Context "When service applications exist in the current farm with the same name but is the wrong type" { - - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Some other service app type" - }) } - - It "returns absent from the Get method" { + Context -Name "When service applications exist in the current farm with the same name but is the wrong type" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "Test App Pool" + DatabaseName = "Test_DB" + DatabaseServer = "TestServer\Instance" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = "Microsoft.Office.UnKnownWebServiceApplication" + } + } -PassThru -Force + return $spServiceApp + } + + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.Name } } - } - Context "When a service application exists and it should, and is also configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When a service application exists and it should, and is also configured correctly" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "Test App Pool" + DatabaseName = "Test_DB" + DatabaseServer = "TestServer\Instance" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Business Data Connectivity Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool } @@ -76,22 +99,34 @@ Describe "SPBCSServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns values from the get method" { + It "Should return values from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.Name } } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } - Context "When a service application exists and it should, but the app pool is not configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When a service application exists and it should, but the app pool is not configured correctly" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "Test App Pool" + DatabaseName = "Test_DB" + DatabaseServer = "TestServer\Instance" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Business Data Connectivity Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = "Wrong App Pool Name" } @@ -99,16 +134,20 @@ Describe "SPBCSServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - Mock Get-SPServiceApplicationPool { return @{ Name = $testParams.ApplicationPool } } - Mock Set-SPBusinessDataCatalogServiceApplication { } + Mock -CommandName Get-SPServiceApplicationPool -MockWith { return @{ Name = $testParams.ApplicationPool } } + Mock -CommandName Set-SPBusinessDataCatalogServiceApplication -MockWith { } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "calls the update service app cmdlet from the set method" { + It "Should call the update service app cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Get-SPServiceApplicationPool @@ -116,14 +155,15 @@ Describe "SPBCSServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule } } - $testParams = @{ - Name = "Test App" - ApplicationPool = "-" - Ensure = "Absent" - } - Context "When the service application exists but it shouldn't" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When the service application exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Business Data Connectivity Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool } @@ -131,33 +171,45 @@ Describe "SPBCSServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns present from the Get method" { + It "Should return present from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "calls the remove service application cmdlet in the set method" { + It "Should call the remove service application cmdlet in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplication } } - Context "When the serivce application doesn't exist and it shouldn't" { - Mock Get-SPServiceApplication { return $null } + Context -Name "When the serivce application doesn't exist and it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } - It "returns absent from the Get method" { + Mock -CommandName Get-SPServiceApplication -MockWith { return $null } + + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPBlobCacheSettings.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPBlobCacheSettings.Tests.ps1 index 16a22a9cb..8b100ad27 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPBlobCacheSettings.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPBlobCacheSettings.Tests.ps1 @@ -1,204 +1,218 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPBlobCacheSettings" -$ModuleName = "MSFT_SPBlobCacheSettings" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDSC\DSCResources\$ModuleName\$ModuleName.psm1") +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPBlobCacheSettings" { - - $webConfigPath = "TestDrive:\inetpub\wwwroot\Virtual Directories\8080" - New-Item $webConfigPath -ItemType Directory - - InModuleScope $ModuleName { - $testParams = @{ - WebAppUrl = "http://sharepoint.contoso.com" - Zone = "Default" - EnableCache = $true - Location = "c:\BlobCache" - MaxSizeInGB = 30 - FileTypes = "\.(gif|jpg|jpeg|jpe|jfif|bmp|dib|tif|tiff|themedbmp|themedcss|themedgif|themedjpg|themedpng|ico|png|wdp|hdp|css|js|asf|avi|flv|m4v|mov|mp3|mp4|mpeg|mpg|rm|rmvb|wma|wmv|ogg|ogv|oga|webm|xap)$" - } - - $webConfigPath = "TestDrive:\inetpub\wwwroot\Virtual Directories\8080" + # Initialize the tests + $relativePath = "\inetpub\wwwroot\Virtual Directories\8080" + $Global:SPDscWebConfigPath = Join-Path -Path "TestDrive:\" -ChildPath $relativePath + $Global:SPDscWebConfigRealPath = Join-Path -Path $TestDrive.FullName -ChildPath $relativePath + $Global:SPDscWebConfigFile = Join-Path -Path $Global:SPDscWebConfigPath -ChildPath "web.config" + New-Item -Path $Global:SPDscWebConfigPath -ItemType Directory - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + try + { + [Microsoft.SharePoint.Administration.SPUrlZone] } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - try { [Microsoft.SharePoint.Administration.SPUrlZone] } - catch { - Add-Type @" + catch + { + Add-Type -TypeDefinition @" namespace Microsoft.SharePoint.Administration { public enum SPUrlZone { Default, Intranet, Internet, Custom, Extranet }; } "@ } - + # Mocks for all contexts + Mock -CommandName Get-SPWebApplication -MockWith { + return @{ + IISSettings = @(@{ + Path = $Global:SPDscWebConfigRealPath + }) + } + } + + function Update-SPDscTestConfigFile + { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [String] + $Content + ) + Set-Content -Path $Global:SPDscWebConfigFile -Value $Content + } + + # Test contexts + Context -Name "The web application doesn't exist" { + $testParams = @{ + WebAppUrl = "http://sharepoint.contoso.com" + Zone = "Default" + EnableCache = $true + Location = "c:\BlobCache" + MaxSizeInGB = 30 + FileTypes = "\.(gif|jpg|jpeg)$" + } - Context "The web application doesn't exist" { - Mock Get-SPWebApplication { return $null } - Mock Test-Path { return $false } + Mock -CommandName Get-SPWebApplication -MockWith { return $null } + Mock -CommandName Test-Path -MockWith { return $false } - It "throws exception from the get method" { + It "Should throw exception from the get method" { (Get-TargetResource @testParams).WebAppUrl | Should Be $null } - It "throws exception from the test method" { + It "Should throw exception from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws exception from the set method" { + It "Should throw exception from the set method" { { Set-TargetResource @testParams } | Should throw "Specified web application could not be found." } } - Context "BlobCache is enabled, but the MaxSize parameters cannot be converted to Uint16" { - Set-Content (Join-Path $webConfigPath "web.config") -value ' + Context -Name "BlobCache is enabled, but the MaxSize parameters cannot be converted to Uint16" { + $testParams = @{ + WebAppUrl = "http://sharepoint.contoso.com" + Zone = "Default" + EnableCache = $true + Location = "c:\BlobCache" + MaxSizeInGB = 30 + FileTypes = "\.(gif|jpg|jpeg)$" + } + + Update-SPDscTestConfigFile -Content ' - + ' - Mock Get-SPWebApplication { - $IISSettings = @(@{ - Path = (Join-Path (Join-Path (Get-PSDrive TestDrive).Root (Get-PSDrive TestDrive).CurrentLocation) "inetpub\wwwroot\Virtual Directories\8080") - }) - $iisSettingsCol = {$IISSettings}.Invoke() - - - $webapp = @{ - IISSettings = $iisSettingsCol - } - - return $webapp - } + Mock -CommandName Test-Path -MockWith { return $true } - Mock Test-Path { return $true } + Mock -CommandName Copy-Item -MockWith {} - Mock Copy-Item {} - - It "returns 0 from the get method" { + It "Should return 0 from the get method" { (Get-TargetResource @testParams).MaxSizeInGB | Should Be 0 } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "returns MaxSize 30 in web.config from the set method" { + It "Should return MaxSize 30 in web.config from the set method" { Set-TargetResource @testParams - [xml] $webcfg = Get-Content (Join-Path $webConfigPath "web.config") + [xml] $webcfg = Get-Content -Path $Global:SPDscWebConfigFile $webcfg.configuration.SharePoint.BlobCache.maxsize | Should Be "30" } } - Context "BlobCache correctly configured, but the folder does not exist" { - Set-Content (Join-Path $webConfigPath "web.config") -value ' + Context -Name "BlobCache correctly configured, but the folder does not exist" { + $testParams = @{ + WebAppUrl = "http://sharepoint.contoso.com" + Zone = "Default" + EnableCache = $true + Location = "c:\BlobCache" + MaxSizeInGB = 30 + FileTypes = "\.(gif|jpg|jpeg)$" + } + + Update-SPDscTestConfigFile -Content ' - + ' - - Mock Get-SPWebApplication { - $IISSettings = @(@{ - Path = (Join-Path (Join-Path (Get-PSDrive TestDrive).Root (Get-PSDrive TestDrive).CurrentLocation) "inetpub\wwwroot\Virtual Directories\8080") - }) - $iisSettingsCol = {$IISSettings}.Invoke() - - - $webapp = @{ - IISSettings = $iisSettingsCol - } - - return $webapp - } - Mock Test-Path { return $false } - Mock New-Item {} + Mock -CommandName Test-Path -MockWith { return $false } + Mock -CommandName New-Item -MockWith {} - Mock Copy-Item {} + Mock -CommandName Copy-Item -MockWith {} - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "check if function is called in the set method" { + It "Should check if function is called in the set method" { Set-TargetResource @testParams } } - Context "BlobCache is enabled, but the other parameters do not match" { - Set-Content (Join-Path $webConfigPath "web.config") -value ' + Context -Name "BlobCache is enabled, but the other parameters do not match" { + $testParams = @{ + WebAppUrl = "http://sharepoint.contoso.com" + Zone = "Default" + EnableCache = $true + Location = "c:\BlobCache" + MaxSizeInGB = 30 + FileTypes = "\.(gif|jpg|jpeg)$" + } + + + Update-SPDscTestConfigFile -Content ' - + ' - - Mock Get-SPWebApplication { - $IISSettings = @(@{ - Path = (Join-Path (Join-Path (Get-PSDrive TestDrive).Root (Get-PSDrive TestDrive).CurrentLocation) "inetpub\wwwroot\Virtual Directories\8080") - }) - $iisSettingsCol = {$IISSettings}.Invoke() - - - $webapp = @{ - IISSettings = $iisSettingsCol - } - - return $webapp - } - Mock Test-Path { return $true } + Mock -CommandName Test-Path -MockWith { return $true } - Mock Copy-Item {} + Mock -CommandName Copy-Item -MockWith {} - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "returns MaxSize 30 from the set method" { + It "Should return MaxSize 30 from the set method" { Set-TargetResource @testParams - [xml] $webcfg = Get-Content (Join-Path $webConfigPath "web.config") + [xml] $webcfg = Get-Content -Path $Global:SPDscWebConfigFile $webcfg.configuration.SharePoint.BlobCache.maxsize | Should Be "30" } } - Context "BlobCache is disabled, but the parameters specify it to be enabled" { - Set-Content (Join-Path $webConfigPath "web.config") -value ' + Context -Name "BlobCache is disabled, but the parameters specify it to be enabled" { + $testParams = @{ + WebAppUrl = "http://sharepoint.contoso.com" + Zone = "Default" + EnableCache = $true + Location = "c:\BlobCache" + MaxSizeInGB = 30 + FileTypes = "\.(gif|jpg|jpeg)$" + } + + Update-SPDscTestConfigFile -Content ' - + ' - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebApplication -MockWith { $IISSettings = @(@{ - Path = (Join-Path (Join-Path (Get-PSDrive TestDrive).Root (Get-PSDrive TestDrive).CurrentLocation) "inetpub\wwwroot\Virtual Directories\8080") + Path = $Global:SPDscWebConfigRealPath }) $iisSettingsCol = {$IISSettings}.Invoke() @@ -210,105 +224,86 @@ namespace Microsoft.SharePoint.Administration { return $webapp } - Mock Test-Path { return $true } + Mock -CommandName Test-Path -MockWith { return $true } - Mock Copy-Item {} + Mock -CommandName Copy-Item -MockWith {} - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "returns Enabled False from the set method" { + It "Should return Enabled False from the set method" { Set-TargetResource @testParams - [xml] $webcfg = Get-Content (Join-Path $webConfigPath "web.config") + [xml] $webcfg = Get-Content -Path $Global:SPDscWebConfigFile $webcfg.configuration.SharePoint.BlobCache.enabled | Should Be "True" } } - Context "The specified configuration is correctly configured" { - Set-Content (Join-Path $webConfigPath "web.config") -value ' + Context -Name "The specified configuration is correctly configured" { + $testParams = @{ + WebAppUrl = "http://sharepoint.contoso.com" + Zone = "Default" + EnableCache = $true + Location = "c:\BlobCache" + MaxSizeInGB = 30 + FileTypes = "\.(gif|jpg|jpeg)$" + } + + Update-SPDscTestConfigFile -Content ' - + ' - - Mock Get-SPWebApplication { - $IISSettings = @(@{ - Path = (Join-Path (Join-Path (Get-PSDrive TestDrive).Root (Get-PSDrive TestDrive).CurrentLocation) "inetpub\wwwroot\Virtual Directories\8080") - }) - $iisSettingsCol = {$IISSettings}.Invoke() - - - $webapp = @{ - IISSettings = $iisSettingsCol - } - - return $webapp - } - Mock Test-Path { return $true } + Mock -CommandName Test-Path -MockWith { return $true } - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "BlobCache is enabled, but the parameters specify it to be disabled" { + Context -Name "BlobCache is enabled, but the parameters specify it to be disabled" { $testParams = @{ WebAppUrl = "http:/sharepoint.contoso.com" Zone = "Default" EnableCache = $false } - Set-Content (Join-Path $webConfigPath "web.config") -value ' + Update-SPDscTestConfigFile -Content ' - + ' - - Mock Get-SPWebApplication { - $IISSettings = @(@{ - Path = (Join-Path (Join-Path (Get-PSDrive TestDrive).Root (Get-PSDrive TestDrive).CurrentLocation) "inetpub\wwwroot\Virtual Directories\8080") - }) - $iisSettingsCol = {$IISSettings}.Invoke() - - - $webapp = @{ - IISSettings = $iisSettingsCol - } - - return $webapp - } - Mock Test-Path { return $true } + Mock -CommandName Test-Path -MockWith { return $true } - Mock Copy-Item {} + Mock -CommandName Copy-Item -MockWith {} - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "returns true from the set method" { + It "Should return correct values in the config file after the set method" { Set-TargetResource @testParams - [xml] $webcfg = Get-Content (Join-Path $webConfigPath "web.config") + [xml] $webcfg = Get-Content -Path $Global:SPDscWebConfigFile $webcfg.configuration.SharePoint.BlobCache.enabled | Should Be "False" } } - - - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPCacheAccounts.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPCacheAccounts.Tests.ps1 index 7ff79f2a5..cea7f672a 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPCacheAccounts.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPCacheAccounts.Tests.ps1 @@ -1,214 +1,341 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPCacheAccounts" -$ModuleName = "MSFT_SPCacheAccounts" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPCacheAccounts - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - WebAppUrl = "http://test.sharepoint.com" - SuperUserAlias = "DEMO\SuperUser" - SuperReaderAlias = "DEMO\SuperReader" + # Initialize tests + try + { + [Microsoft.SharePoint.Administration.SPPolicyRoleType] } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - try { [Microsoft.SharePoint.Administration.SPPolicyRoleType] } - catch { - Add-Type @" + catch + { + Add-Type -TypeDefinition @" namespace Microsoft.SharePoint.Administration { public enum SPPolicyRoleType { FullRead, FullControl, DenyWrite, DenyAll }; } "@ } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock New-SPClaimsPrincipal { - $Global:SPDSCClaimsPrincipalUser = $Identity + + # Mocks for all contexts + Mock -CommandName New-SPClaimsPrincipal -MockWith { + $Global:SPDscClaimsPrincipalUser = $Identity return ( - New-Object Object | Add-Member ScriptMethod ToEncodedString { - return "i:0#.w|$($Global:SPDSCClaimsPrincipalUser)" - } -PassThru + New-Object -TypeName Object | Add-Member -MemberType ScriptMethod ` + -Name "ToEncodedString" ` + -Value { + return "i:0#.w|$($Global:SPDscClaimsPrincipalUser)" + } -PassThru ) } -ParameterFilter { $IdentityType -eq "WindowsSamAccountName" } - Mock New-SPClaimsPrincipal { + Mock -CommandName New-SPClaimsPrincipal -MockWith { return @{ Value = $Identity -replace "i:0#.w|" } } -ParameterFilter { $IdentityType -eq "EncodedClaim" } - Context "The web application specified does not exist" { - Mock Get-SPWebApplication { return $null } + # Test contexts + Context -Name "The web application specified does not exist" -Fixture { + $testParams = @{ + WebAppUrl = "http://test.sharepoint.com" + SuperUserAlias = "DEMO\SuperUser" + SuperReaderAlias = "DEMO\SuperReader" + } - It "returns empty values from the get method" { + Mock -CommandName Get-SPWebApplication -MockWith { return $null } + + It "Should return empty values from the get method" { $results = Get-TargetResource @testParams $results.SuperUserAlias | Should BeNullOrEmpty $results.SuperReaderAlias | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws and exception where set is called" { + It "Should throw and exception where set is called" { { Set-TargetResource @testParams } | Should Throw } } - Context "The specified cache accounts have not been configured" { - Mock Get-SPWebApplication { return New-Object Object | - Add-Member NoteProperty Properties @{} -PassThru | - Add-Member NoteProperty Policies ( - New-Object Object | - Add-Member ScriptMethod Add { return New-Object Object | - Add-Member NoteProperty PolicyRoleBindings ( - New-Object Object | - Add-Member ScriptMethod Add {} -PassThru - ) -PassThru - } -PassThru | - Add-Member ScriptMethod Remove {} -PassThru - ) -PassThru | - Add-Member NoteProperty PolicyRoles ( - New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru - ) -PassThru | - Add-Member ScriptMethod Update {} -PassThru | - Add-Member NoteProperty UseClaimsAuthentication ($true) -PassThru - } - - It "returns empty strings from the Get method" { + Context -Name "The specified cache accounts have not been configured" -Fixture { + $testParams = @{ + WebAppUrl = "http://test.sharepoint.com" + SuperUserAlias = "DEMO\SuperUser" + SuperReaderAlias = "DEMO\SuperReader" + } + + Mock -CommandName Get-SPWebApplication -MockWith { + $policiesObject = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name Add ` + -Value { + return New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name PolicyRoleBindings ` + -Value ( + New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name Add ` + -Value {} ` + -PassThru + ) -PassThru + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Remove ` + -Value {} ` + -PassThru + + return New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Properties ` + -Value @{} ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name Policies ` + -Value $policiesObject ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name PolicyRoles ` + -Value ( + New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name GetSpecialRole ` + -Value { return @{} } ` + -PassThru + ) -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value {} ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name UseClaimsAuthentication ` + -Value $true ` + -PassThru + } + + It "Should return empty strings from the Get method" { $results = Get-TargetResource @testParams $results.SuperUserAlias | Should BeNullOrEmpty $results.SuperReaderAlias | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "Updates the accounts when set is called" { + It "Should update the accounts when set is called" { Set-TargetResource @testParams } } - Context "The cache accounts have been configured correctly" { - Mock Get-SPWebApplication { return New-Object Object | - Add-Member NoteProperty Properties @{ - portalsuperuseraccount = $testParams.SuperUserAlias - portalsuperreaderaccount = $testParams.SuperReaderAlias - } -PassThru | - Add-Member NoteProperty Policies @( - @{ - UserName = $testParams.SuperUserAlias - }, - @{ - UserName = $testParams.SuperReaderAlias - }, - @{ - UserName = "i:0#.w|$($testParams.SuperUserAlias)" - }, - @{ - UserName = "i:0#.w|$($testParams.SuperReaderAlias)" - } - ) -PassThru | - Add-Member NoteProperty PolicyRoles ( - New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru - ) -PassThru | - Add-Member ScriptMethod Update {} -PassThru| - Add-Member NoteProperty UseClaimsAuthentication ($false) -PassThru + Context -Name "The cache accounts have been configured correctly" -Fixture { + $testParams = @{ + WebAppUrl = "http://test.sharepoint.com" + SuperUserAlias = "DEMO\SuperUser" + SuperReaderAlias = "DEMO\SuperReader" } - It "returns the values from the get method" { + Mock -CommandName Get-SPWebApplication -MockWith { + return New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Properties ` + -Value @{ + portalsuperuseraccount = $testParams.SuperUserAlias + portalsuperreaderaccount = $testParams.SuperReaderAlias + } -PassThru | + Add-Member -MemberType NoteProperty ` + -Name Policies ` + -Value @( + @{ + UserName = $testParams.SuperUserAlias + }, + @{ + UserName = $testParams.SuperReaderAlias + }, + @{ + UserName = "i:0#.w|$($testParams.SuperUserAlias)" + }, + @{ + UserName = "i:0#.w|$($testParams.SuperReaderAlias)" + } + ) -PassThru | + Add-Member -MemberType NoteProperty ` + -Name PolicyRoles ` + -Value ( + New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name GetSpecialRole ` + -Value { + return @{} + } -PassThru + ) -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value {} ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name UseClaimsAuthentication ` + -Value $false ` + -PassThru + } + + It "Should return the values from the get method" { $results = Get-TargetResource @testParams $results.SuperUserAlias | Should Not BeNullOrEmpty $results.SuperReaderAlias | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Cache accounts have been configured, but the reader account is wrong" { - Mock Get-SPWebApplication { return New-Object Object | - Add-Member NoteProperty Properties @{ - portalsuperuseraccount = $testParams.SuperUserAlias - portalsuperreaderaccount = "WRONG\AccountName" - } -PassThru | - Add-Member NoteProperty Policies ( - New-Object Object | - Add-Member ScriptMethod Add { return New-Object Object | - Add-Member NoteProperty PolicyRoleBindings ( - New-Object Object | - Add-Member ScriptMethod Add {} -PassThru - ) -PassThru - } -PassThru | - Add-Member ScriptMethod Remove {} -PassThru - ) -PassThru | - Add-Member NoteProperty PolicyRoles ( - New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru - ) -PassThru | - Add-Member ScriptMethod Update {} -PassThru| - Add-Member NoteProperty UseClaimsAuthentication ($true) -PassThru - } - - It "returns false from the test method" { + Context -Name "Cache accounts have been configured, but the reader account is wrong" -Fixture { + $testParams = @{ + WebAppUrl = "http://test.sharepoint.com" + SuperUserAlias = "DEMO\SuperUser" + SuperReaderAlias = "DEMO\SuperReader" + } + + Mock -CommandName Get-SPWebApplication -MockWith { + return New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty -Name Properties @{ + portalsuperuseraccount = $testParams.SuperUserAlias + portalsuperreaderaccount = "WRONG\AccountName" + } -PassThru | + Add-Member -MemberType NoteProperty ` + -Name Policies ` + -Value ( + New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name Add ` + -Value { + return New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name PolicyRoleBindings ` + -Value ( + New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name Add ` + -Value {} ` + -PassThru + ) -PassThru + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Remove ` + -Value {} ` + -PassThru + ) -PassThru | + Add-Member -MemberType NoteProperty ` + -Name PolicyRoles ` + -Value ( + New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name GetSpecialRole ` + -Value { + return @{} + } -PassThru + ) -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value {} ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name UseClaimsAuthentication ` + -Value $true ` + -PassThru + } + + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "sets the correct accounts to the web app again" { + It "Should set the correct accounts to the web app again" { Set-TargetResource @testParams } } - Context "Cache accounts have been configured, but the super account is wrong" { - Mock Get-SPWebApplication { return New-Object Object | - Add-Member NoteProperty Properties @{ - portalsuperuseraccount = "WRONG\AccountName" - portalsuperreaderaccount = $testParams.SuperReaderAlias - } -PassThru | - Add-Member NoteProperty Policies ( - New-Object Object | - Add-Member ScriptMethod Add { return New-Object Object | - Add-Member NoteProperty PolicyRoleBindings ( - New-Object Object | - Add-Member ScriptMethod Add {} -PassThru - ) -PassThru - } -PassThru | - Add-Member ScriptMethod Remove {} -PassThru - ) -PassThru | - Add-Member NoteProperty PolicyRoles ( - New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru - ) -PassThru | - Add-Member ScriptMethod Update {} -PassThru| - Add-Member NoteProperty UseClaimsAuthentication ($true) -PassThru - } - - It "returns false from the test method" { + Context -Name "Cache accounts have been configured, but the super account is wrong" -Fixture { + $testParams = @{ + WebAppUrl = "http://test.sharepoint.com" + SuperUserAlias = "DEMO\SuperUser" + SuperReaderAlias = "DEMO\SuperReader" + } + + Mock -CommandName Get-SPWebApplication -MockWith { + return New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty -Name Properties @{ + portalsuperuseraccount = "WRONG\AccountName" + portalsuperreaderaccount = $testParams.SuperReaderAlias + } -PassThru | + Add-Member -MemberType NoteProperty -Name Policies -Value ( + New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name Add ` + -Value { + return New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name PolicyRoleBindings ` + -Value ( + New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name Add ` + -Value {} ` + -PassThru + ) -PassThru + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Remove ` + -Value {} ` + -PassThru + ) -PassThru | + Add-Member -MemberType NoteProperty ` + -Name PolicyRoles ` + -Value ( + New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name GetSpecialRole ` + -Value { + return @{} + } -PassThru + ) -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value {} ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name UseClaimsAuthentication ` + -Value $true ` + -PassThru + } + + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "sets the correct accounts to the web app again" { + It "Should set the correct accounts to the web app again" { Set-TargetResource @testParams } } - } -} \ No newline at end of file + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPConfigWizard.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPConfigWizard.Tests.ps1 index 0fd7099ce..57920801b 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPConfigWizard.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPConfigWizard.Tests.ps1 @@ -1,90 +1,95 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPConfigWizard" -$ModuleName = "MSFT_SPConfigWizard" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPConfigWizard - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - $versionBeingTested = (Get-Item $Global:CurrentSharePointStubModule).Directory.BaseName - $majorBuildNumber = $versionBeingTested.Substring(0, $versionBeingTested.IndexOf(".")) - Mock Get-SPDSCInstalledProductVersion { return @{ FileMajorPart = $majorBuildNumber } } - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue + # Test contexts + Context -Name "Upgrade required for Language Pack" -Fixture { + $testParams = @{ + Ensure = "Present" + } - Context "Upgrade required for Language Pack" { - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "LanguagePackInstalled") { return 1 } } - Mock Start-Process { return @{ ExitCode = 0 }} + Mock -CommandName Start-Process -MockWith { + return @{ + ExitCode = 0 + } + } - It "should return Ensure=Absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should run Start-Process in the set method" { + It "Should run Start-Process in the set method" { Set-TargetResource @testParams Assert-MockCalled Start-Process } } - Context "Upgrade required for Cumulative Update" { - Mock Get-SPDSCRegistryKey { + Context -Name "Upgrade required for Cumulative Update" -Fixture { + $testParams = @{ + Ensure = "Present" + } + + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "B2B_UPGRADE" } } - Mock Start-Process { @{ ExitCode = 0 }} + Mock -CommandName Start-Process -MockWith { + return @{ + ExitCode = 0 + } + } - It "should return Ensure=Absent from the get method" { + It "Should return Ensure=Absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should run Start-Process in the set method" { + It "Should run Start-Process in the set method" { Set-TargetResource @testParams Assert-MockCalled Start-Process } } - Context "Current date outside Upgrade Days" { + Context -Name "Current date outside Upgrade Days" -Fixture { $testParams = @{ Ensure = "Present" DatabaseUpgradeDays = "mon" } - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "B2B_UPGRADE" @@ -92,32 +97,31 @@ Describe "SPConfigWizard - SharePoint Build $((Get-Item $SharePointCmdletModule) } $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - - Mock Get-Date { - return $testDate + Mock -CommandName Get-Date -MockWith { + return $testDate } - It "should return Ensure=Absent from the get method" { + It "Should return Ensure=Absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should run Start-Process in the set method" { + It "Should run Start-Process in the set method" { Set-TargetResource @testParams | Should BeNullOrEmpty } } - Context "Current date outside Upgrade Time" { + Context -Name "Current date outside Upgrade Time" -Fixture { $testParams = @{ Ensure = "Present" DatabaseUpgradeDays = "sun" DatabaseUpgradeTime = "3:00am to 5:00am" } - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "B2B_UPGRADE" @@ -125,24 +129,23 @@ Describe "SPConfigWizard - SharePoint Build $((Get-Item $SharePointCmdletModule) } $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should return null from the set method" { + It "Should return null from the set method" { Set-TargetResource @testParams | Should BeNullOrEmpty } } - Context "Upgrade Time incorrectly formatted" { + Context -Name "Upgrade Time incorrectly formatted" -Fixture { $testParams = @{ Ensure = "Present" DatabaseUpgradeDays = "sun" DatabaseUpgradeTime = "error 3:00am to 5:00am" } - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "B2B_UPGRADE" @@ -150,24 +153,23 @@ Describe "SPConfigWizard - SharePoint Build $((Get-Item $SharePointCmdletModule) } $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - - Mock Get-Date { - return $testDate + Mock -CommandName Get-Date -MockWith { + return $testDate } - It "should return exception from the set method" { + It "Should return exception from the set method" { { Set-TargetResource @testParams } | Should Throw "Time window incorrectly formatted." } } - Context "Start time Upgrade Time incorrectly formatted" { + Context -Name "Start time Upgrade Time incorrectly formatted" -Fixture { $testParams = @{ Ensure = "Present" DatabaseUpgradeDays = "sun" DatabaseUpgradeTime = "3:00xm to 5:00am" } - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "B2B_UPGRADE" @@ -175,24 +177,23 @@ Describe "SPConfigWizard - SharePoint Build $((Get-Item $SharePointCmdletModule) } $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - - Mock Get-Date { - return $testDate + Mock -CommandName Get-Date -MockWith { + return $testDate } - It "should return exception from the set method" { + It "Should return exception from the set method" { { Set-TargetResource @testParams } | Should Throw "Error converting start time" } } - Context "End time Upgrade Time incorrectly formatted" { + Context -Name "End time Upgrade Time incorrectly formatted" -Fixture { $testParams = @{ Ensure = "Present" DatabaseUpgradeDays = "sun" DatabaseUpgradeTime = "3:00am to 5:00xm" } - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "B2B_UPGRADE" @@ -200,24 +201,23 @@ Describe "SPConfigWizard - SharePoint Build $((Get-Item $SharePointCmdletModule) } $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should return exception from the set method" { + It "Should return exception from the set method" { { Set-TargetResource @testParams } | Should Throw "Error converting end time" } } - Context "Start time of Upgrade Time larger than end time" { + Context -Name "Start time of Upgrade Time larger than end time" -Fixture { $testParams = @{ Ensure = "Present" DatabaseUpgradeDays = "sun" DatabaseUpgradeTime = "3:00pm to 5:00am" } - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "B2B_UPGRADE" @@ -225,61 +225,74 @@ Describe "SPConfigWizard - SharePoint Build $((Get-Item $SharePointCmdletModule) } $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - - Mock Get-Date { - return $testDate + Mock -CommandName Get-Date -MockWith { + return $testDate } - It "should return exception from the set method" { + It "Should return exception from the set method" { { Set-TargetResource @testParams } | Should Throw "Error: Start time cannot be larger than end time" } } - Context "ExitCode of process is not 0" { - Mock Get-SPDSCRegistryKey { + Context -Name "ExitCode of process is not 0" -Fixture { + $testParams = @{ + Ensure = "Present" + } + + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "LanguagePackInstalled") { return 1 } } - Mock Start-Process { @{ ExitCode = -1 }} + Mock -CommandName Start-Process -MockWith { return + @{ + ExitCode = -1 + } + } - It "should return Ensure=Absent from the get method" { + It "Should return Ensure=Absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should Throw "SharePoint Post Setup Configuration Wizard failed, exit code was" } } - Context "Ensure is set to Absent, Config Wizard not required" { + Context -Name "Ensure is set to Absent, Config Wizard not required" -Fixture { $testParams = @{ Ensure = "Absent" } - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { return 0 } - Mock Start-Process { @{ ExitCode = 0 }} + Mock -CommandName Start-Process -MockWith { + return @{ + ExitCode = 0 + } + } - It "should return Ensure=Present from the get method" { + It "Should return Ensure=Present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } - It "should return null from the set method" { + It "Should return null from the set method" { Set-TargetResource @testParams | Should BeNullOrEmpty } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPContentDatabase.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPContentDatabase.Tests.ps1 index 8dba217e7..065c08627 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPContentDatabase.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPContentDatabase.Tests.ps1 @@ -1,108 +1,150 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPContentDatabase" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPContentDatabase - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "SharePoint_Content_01" - DatabaseServer = "SQLSrv" - WebAppUrl = "http://sharepoint.contoso.com" - Enabled = $true - WarningSiteCount = 2000 - MaximumSiteCount = 5000 - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPContentDatabase" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope - try { [Microsoft.SharePoint.Administration.SPObjectStatus] } - catch { - Add-Type @" + # Initialize tests + try + { + [Microsoft.SharePoint.Administration.SPObjectStatus] + } + catch + { + Add-Type -TypeDefinition @" namespace Microsoft.SharePoint.Administration { public enum SPObjectStatus { Online, Disabled }; } "@ - } + } - Context "DatabaseServer parameter does not match actual setting" { - Mock Get-SPDatabase { + # Mocks for all contexts + Mock -CommandName Dismount-SPContentDatabase -MockWith { } + Mock -CommandName Get-SPWebApplication -MockWith { + return @{ + Url="http://sharepoint.contoso.com/" + } + } + + # Test contexts + Context -Name "DatabaseServer parameter does not match actual setting" -Fixture { + $testParams = @{ + Name = "SharePoint_Content_01" + DatabaseServer = "SQLSrv" + WebAppUrl = "http://sharepoint.contoso.com" + Enabled = $true + WarningSiteCount = 2000 + MaximumSiteCount = 5000 + Ensure = "Present" + } + + Mock -CommandName Get-SPDatabase -MockWith { return @{ Name = "SharePoint_Content_01" Type = "Content Database" Server = "WrongSQLSrv" - WebApplication = @{ Url = "http://sharepoint.contoso.com/" } + WebApplication = @{ + Url = "http://sharepoint.contoso.com/" + } Status = "Online" WarningSiteCount = 2000 MaximumSiteCount = 5000 } } - Mock Get-SPWebApplication { return @{ Url="http://sharepoint.contoso.com/" } } + Mock -CommandName Get-SPWebApplication -MockWith { + return @{ + Url="http://sharepoint.contoso.com/" + } + } - It "return Ensure=Present from the get method" { + It "Should return Ensure=Present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false and display message to indicate the databaseserver parameter does not match" { + It "Should return false and display message to indicate the databaseserver parameter does not match" { Test-TargetResource @testParams | Should Be $false } - It "throws an exception in the test method to say the databaseserver parameter does not match" { + It "Should throw an exception in the test method to say the databaseserver parameter does not match" { { Set-TargetResource @testParams } | Should throw "Specified database server does not match the actual database server. This resource cannot move the database to a different SQL instance." } } - Context "Specified Web application does not exist" { - Mock Get-SPDatabase { + Context -Name "Specified Web application does not exist" -Fixture { + $testParams = @{ + Name = "SharePoint_Content_01" + DatabaseServer = "SQLSrv" + WebAppUrl = "http://sharepoint.contoso.com" + Enabled = $true + WarningSiteCount = 2000 + MaximumSiteCount = 5000 + Ensure = "Present" + } + + Mock -CommandName Get-SPDatabase -MockWith { return @{ Name = "SharePoint_Content_01" Type = "Content Database" Server = "SQLSrv" - WebApplication = @{ Url = "http://sharepoint2.contoso.com/" } + WebApplication = @{ + Url = "http://sharepoint2.contoso.com/" + } Status = "Online" WarningSiteCount = 2000 MaximumSiteCount = 5000 } } - Get-SPWebApplication { return $null } + Mock -CommandName Get-SPWebApplication -MockWith { + return @() + } - It "return Ensure=Present from the get method" { + It "Should return Ensure=Present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws an exception in the set method to say the web application does not exist" { + It "Should throw an exception in the set method to say the web application does not exist" { { Set-TargetResource @testParams } | Should throw "Specified web application does not exist." } } - Context "Mount database throws an error" { - Mock Get-SPDatabase { + Context -Name "Mount database throws an error" -Fixture { + $testParams = @{ + Name = "SharePoint_Content_01" + DatabaseServer = "SQLSrv" + WebAppUrl = "http://sharepoint.contoso.com" + Enabled = $true + WarningSiteCount = 2000 + MaximumSiteCount = 5000 + Ensure = "Present" + } + + Mock -CommandName Get-SPDatabase -MockWith { $returnVal = @{} - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCContentDatabaseUpdated = $true } -PassThru + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscContentDatabaseUpdated = $true + } -PassThru return $returnVal } - Mock Get-SPWebApplication { return @{ Url="http://sharepoint.contoso.com/" } } - Mock Mount-SPContentDatabase { + + Mock -CommandName Mount-SPContentDatabase -MockWith { throw "MOUNT ERROR" } @@ -111,14 +153,27 @@ namespace Microsoft.SharePoint.Administration { } } - Context "Content database does not exist, but has to be" { - Mock Get-SPDatabase { + Context -Name "Content database does not exist, but has to be" -Fixture { + $testParams = @{ + Name = "SharePoint_Content_01" + DatabaseServer = "SQLSrv" + WebAppUrl = "http://sharepoint.contoso.com" + Enabled = $true + WarningSiteCount = 2000 + MaximumSiteCount = 5000 + Ensure = "Present" + } + + Mock -CommandName Get-SPDatabase -MockWith { $returnVal = @{} - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCContentDatabaseUpdated = $true } -PassThru + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscContentDatabaseUpdated = $true + } -PassThru return $returnVal } - Mock Get-SPWebApplication { return @{ Url="http://sharepoint.contoso.com/" } } - Mock Mount-SPContentDatabase -ModuleName SPContentDatabase { + + Mock -CommandName Get-SPWebApplication { return @{ Url="http://sharepoint.contoso.com/" } } + Mock Mount-SPContentDatabase { $returnval = @{ Name = "SharePoint_Content_01" Server = "SQLSrv" @@ -127,27 +182,39 @@ namespace Microsoft.SharePoint.Administration { WarningSiteCount = 2000 MaximumSiteCount = 5000 } - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCContentDatabaseUpdated = $true } -PassThru + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscContentDatabaseUpdated = $true + } -PassThru return $returnVal } - It "return Ensure=Absent from the get method" { + It "Should return Ensure=Absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPDSCContentDatabaseUpdated = $false + $Global:SPDscContentDatabaseUpdated = $false It "mounts a (new) content database" { Set-TargetResource @testParams - $Global:SPDSCContentDatabaseUpdated | Should Be $true + $Global:SPDscContentDatabaseUpdated | Should Be $true } } - Context "Content database exists, but has incorrect settings" { - Mock Get-SPDatabase { + Context -Name "Content database exists, but has incorrect settings" -Fixture { + $testParams = @{ + Name = "SharePoint_Content_01" + DatabaseServer = "SQLSrv" + WebAppUrl = "http://sharepoint.contoso.com" + Enabled = $true + WarningSiteCount = 2000 + MaximumSiteCount = 5000 + Ensure = "Present" + } + + Mock -CommandName Get-SPDatabase -MockWith { $returnVal = @{ Name = "SharePoint_Content_01" Type = "Content Database" @@ -157,28 +224,39 @@ namespace Microsoft.SharePoint.Administration { WarningSiteCount = 1000 MaximumSiteCount = 2000 } - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCContentDatabaseUpdated = $true } -PassThru + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscContentDatabaseUpdated = $true + } -PassThru return $returnVal } - Mock Get-SPWebApplication { return @{ Url="http://sharepoint.contoso.com/" } } - It "return Ensure=Present from the get method" { + It "Should return Ensure=Present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPDSCContentDatabaseUpdated = $false - It "updates the content database settings" { + $Global:SPDscContentDatabaseUpdated = $false + It "Should update the content database settings" { Set-TargetResource @testParams - $Global:SPDSCContentDatabaseUpdated | Should Be $true + $Global:SPDscContentDatabaseUpdated | Should Be $true } } - Context "Content database exists, but Ensure is set to Absent" { - Mock Get-SPDatabase { + Context -Name "Content database exists, but Ensure is set to Absent" -Fixture { + $testParams = @{ + Name = "SharePoint_Content_01" + DatabaseServer = "SQLSrv" + WebAppUrl = "http://sharepoint.contoso.com" + Enabled = $true + WarningSiteCount = 2000 + MaximumSiteCount = 5000 + Ensure = "Absent" + } + + Mock -CommandName Get-SPDatabase -MockWith { $returnVal = @{ Name = "SharePoint_Content_01" Type = "Content Database" @@ -188,30 +266,38 @@ namespace Microsoft.SharePoint.Administration { WarningSiteCount = 1000 MaximumSiteCount = 2000 } - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCContentDatabaseUpdated = $true } -PassThru + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscContentDatabaseUpdated = $true + } -PassThru return $returnVal } - Mock Get-SPWebApplication { return @{ Url="http://sharepoint.contoso.com/" } } - Mock Dismount-SPContentDatabase { } - $testParams.Ensure = "Absent" - - It "return Ensure=Present from the get method" { + It "Should return Ensure=Present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "updates the content database settings" { + It "Should update the content database settings" { Set-TargetResource @testParams Assert-MockCalled Dismount-SPContentDatabase } } - Context "Content database is mounted to the incorrect web application" { - Mock Get-SPDatabase { + Context -Name "Content database is mounted to the incorrect web application" -Fixture { + $testParams = @{ + Name = "SharePoint_Content_01" + DatabaseServer = "SQLSrv" + WebAppUrl = "http://sharepoint.contoso.com" + Enabled = $true + WarningSiteCount = 2000 + MaximumSiteCount = 5000 + Ensure = "Present" + } + + Mock -CommandName Get-SPDatabase -MockWith { $returnVal = @{ Name = "SharePoint_Content_01" Type = "Content Database" @@ -223,9 +309,10 @@ namespace Microsoft.SharePoint.Administration { } return $returnVal } - Mock Get-SPWebApplication { return @{ Url="http://sharepoint.contoso.com/" } } + + Mock -CommandName Get-SPWebApplication { return @{ Url="http://sharepoint.contoso.com/" } } Mock Dismount-SPContentDatabase { } - Mock Mount-SPContentDatabase -ModuleName SPContentDatabase { + Mock Mount-SPContentDatabase { $returnVal = @{ Name = "SharePoint_Content_01" Server = "SQLSrv" @@ -234,29 +321,39 @@ namespace Microsoft.SharePoint.Administration { WarningSiteCount = 2000 MaximumSiteCount = 5000 } - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCContentDatabaseUpdated = $true } -PassThru + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscContentDatabaseUpdated = $true + } -PassThru return $returnVal } - - $testParams.Ensure = "Present" - It "return Ensure=Present from the get method" { + It "Should return Ensure=Present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPDSCContentDatabaseUpdated = $false + $Global:SPDscContentDatabaseUpdated = $false It "move the content database to the specified web application via set method" { Set-TargetResource @testParams - $Global:SPDSCContentDatabaseUpdated | Should Be $true + $Global:SPDscContentDatabaseUpdated | Should Be $true } } - Context "Content database is present with correct settings and Ensure is Present" { - Mock Get-SPDatabase { + Context -Name "Content database is present with correct settings and Ensure is Present" -Fixture { + $testParams = @{ + Name = "SharePoint_Content_01" + DatabaseServer = "SQLSrv" + WebAppUrl = "http://sharepoint.contoso.com" + Enabled = $true + WarningSiteCount = 2000 + MaximumSiteCount = 5000 + Ensure = "Present" + } + + Mock -CommandName Get-SPDatabase -MockWith { $returnVal = @{ Name = "SharePoint_Content_01" Type = "Content Database" @@ -268,33 +365,41 @@ namespace Microsoft.SharePoint.Administration { } return $returnVal } - Mock Get-SPWebApplication { return @{ Url="http://sharepoint.contoso.com/" } } - It "return Ensure=Present from the get method" { + It "Should return Ensure=Present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Content database is absent and Ensure is Absent" { - Mock Get-SPDatabase { + Context -Name "Content database is absent and Ensure is Absent" -Fixture { + $testParams = @{ + Name = "SharePoint_Content_01" + DatabaseServer = "SQLSrv" + WebAppUrl = "http://sharepoint.contoso.com" + Enabled = $true + WarningSiteCount = 2000 + MaximumSiteCount = 5000 + Ensure = "Absent" + } + + Mock -CommandName Get-SPDatabase -MockWith { $returnVal = @{ } return $returnVal } - Mock Get-SPWebApplication { return @{ Url="http://sharepoint.contoso.com/" } } - - $testParams.Ensure = "Absent" - It "return Ensure=Absent from the get method" { + It "Should return Ensure=Absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPCreateFarm.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPCreateFarm.Tests.ps1 index e010dd40d..3d3789d0f 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPCreateFarm.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPCreateFarm.Tests.ps1 @@ -1,62 +1,65 @@ [CmdletBinding()] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPCreateFarm" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPCreateFarm - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - FarmConfigDatabaseName = "SP_Config" - DatabaseServer = "DatabaseServer\Instance" - FarmAccount = New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)) - Passphrase = New-Object System.Management.Automation.PSCredential ("PASSPHRASEUSER", (ConvertTo-SecureString "MyFarmPassphrase" -AsPlainText -Force)) - AdminContentDatabaseName = "Admin_Content" - CentralAdministrationAuth = "Kerberos" - CentralAdministrationPort = 1234 - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPCreateFarm" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Initialize tests + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $mockFarmAccount = New-Object -TypeName "System.Management.Automation.PSCredential" ` + -ArgumentList @("username", $mockPassword) + $mockPassphrase = New-Object -TypeName "System.Management.Automation.PSCredential" ` + -ArgumentList @("PASSPHRASEUSER", $mockPassword) + + # Mocks for all contexts + Mock -CommandName New-SPConfigurationDatabase -MockWith {} + Mock -CommandName Install-SPHelpCollection -MockWith {} + Mock Initialize-SPResourceSecurity -MockWith {} + Mock -CommandName Install-SPService -MockWith {} + Mock -CommandName Install-SPFeature -MockWith {} + Mock -CommandName New-SPCentralAdministration -MockWith {} + Mock -CommandName Install-SPApplicationContent -MockWith {} - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Mock New-SPConfigurationDatabase {} - Mock Install-SPHelpCollection {} - Mock Initialize-SPResourceSecurity {} - Mock Install-SPService {} - Mock Install-SPFeature {} - Mock New-SPCentralAdministration {} - Mock Install-SPApplicationContent {} - - $versionBeingTested = (Get-Item $Global:CurrentSharePointStubModule).Directory.BaseName - $majorBuildNumber = $versionBeingTested.Substring(0, $versionBeingTested.IndexOf(".")) - Mock Get-SPDSCInstalledProductVersion { return @{ FileMajorPart = $majorBuildNumber } } - - Context "no farm is configured locally and a supported version of SharePoint is installed" { - Mock Get-SPFarm { throw "Unable to detect local farm" } + # Test contexts + Context -Name "no farm is configured locally and a supported version of SharePoint is installed" -Fixture { + $testParams = @{ + FarmConfigDatabaseName = "SP_Config" + DatabaseServer = "DatabaseServer\Instance" + FarmAccount = $mockFarmAccount + Passphrase = $mockPassphrase + AdminContentDatabaseName = "Admin_Content" + CentralAdministrationAuth = "Kerberos" + CentralAdministrationPort = 1234 + } + + Mock -CommandName Get-SPFarm -MockWith { throw "Unable to detect local farm" } It "the get method returns null when the farm is not configured" { Get-TargetResource @testParams | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "calls the new configuration database cmdlet in the set method" { + It "Should call the new configuration database cmdlet in the set method" { Set-TargetResource @testParams - switch ($majorBuildNumber) + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) { 15 { Assert-MockCalled New-SPConfigurationDatabase @@ -68,12 +71,12 @@ Describe "SPCreateFarm - SharePoint Build $((Get-Item $SharePointCmdletModule).D throw [Exception] "A supported version of SharePoint was not used in testing" } } - } - if ($majorBuildNumber -eq 16) { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 16) + { $testParams.Add("ServerRole", "WebFrontEnd") - It "creates a farm with a specific server role" { + It "Should create a farm with a specific server role" { Set-TargetResource @testParams Assert-MockCalled New-SPConfigurationDatabase -ParameterFilter { $LocalServerRole -eq "WebFrontEnd" } } @@ -81,108 +84,198 @@ Describe "SPCreateFarm - SharePoint Build $((Get-Item $SharePointCmdletModule).D } } - if ($majorBuildNumber -eq 15) { - $testParams.Add("ServerRole", "WebFrontEnd") + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) + { + Context -Name "only valid parameters for SharePoint 2013 are used" -Fixture { + $testParams = @{ + FarmConfigDatabaseName = "SP_Config" + DatabaseServer = "DatabaseServer\Instance" + FarmAccount = $mockFarmAccount + Passphrase = $mockPassphrase + AdminContentDatabaseName = "Admin_Content" + CentralAdministrationAuth = "Kerberos" + CentralAdministrationPort = 1234 + ServerRole = "WebFrontEnd" + } - Context "only valid parameters for SharePoint 2013 are used" { - It "throws if server role is used in the get method" { + It "Should throw if server role is used in the get method" { { Get-TargetResource @testParams } | Should Throw } - It "throws if server role is used in the test method" { + It "Should throw if server role is used in the test method" { { Test-TargetResource @testParams } | Should Throw } - It "throws if server role is used in the set method" { + It "Should throw if server role is used in the set method" { { Set-TargetResource @testParams } | Should Throw } } - - $testParams.Remove("ServerRole") } - Context "no farm is configured locally and an unsupported version of SharePoint is installed on the server" { - Mock Get-SPDSCInstalledProductVersion { return @{ FileMajorPart = 14 } } + Context -Name "no farm is configured locally and an unsupported version of SharePoint is installed on the server" -Fixture { + $testParams = @{ + FarmConfigDatabaseName = "SP_Config" + DatabaseServer = "DatabaseServer\Instance" + FarmAccount = $mockFarmAccount + Passphrase = $mockPassphrase + AdminContentDatabaseName = "Admin_Content" + CentralAdministrationAuth = "Kerberos" + CentralAdministrationPort = 1234 + } + + Mock -CommandName Get-SPDSCInstalledProductVersion -MockWith { return @{ FileMajorPart = 14 } } - It "throws when an unsupported version is installed and set is called" { + It "Should throw when an unsupported version is installed and set is called" { { Set-TargetResource @testParams } | Should throw } } - Context "a farm exists locally and is the correct farm" { - Mock Get-SPFarm { return @{ - DefaultServiceAccount = @{ Name = $testParams.FarmAccount.UserName } - Name = $testParams.FarmConfigDatabaseName - }} - Mock Get-SPDatabase { return @(@{ - Name = $testParams.FarmConfigDatabaseName - Type = "Configuration Database" - Server = @{ Name = $testParams.DatabaseServer } - })} - Mock Get-SPWebApplication { return @(@{ - IsAdministrationWebApplication = $true - ContentDatabases = @(@{ Name = $testParams.AdminContentDatabaseName }) - Url = "http://$($env:ComputerName):$($testParams.CentralAdministrationPort)" - })} + Context -Name "a farm exists locally and is the correct farm" -Fixture { + $testParams = @{ + FarmConfigDatabaseName = "SP_Config" + DatabaseServer = "DatabaseServer\Instance" + FarmAccount = $mockFarmAccount + Passphrase = $mockPassphrase + AdminContentDatabaseName = "Admin_Content" + CentralAdministrationAuth = "Kerberos" + CentralAdministrationPort = 1234 + } + + Mock -CommandName Get-SPFarm -MockWith { + return @{ + DefaultServiceAccount = @{ + Name = $testParams.FarmAccount.UserName + } + Name = $testParams.FarmConfigDatabaseName + } + } + + Mock -CommandName Get-SPDatabase -MockWith { + return @(@{ + Name = $testParams.FarmConfigDatabaseName + Type = "Configuration Database" + Server = @{ + Name = $testParams.DatabaseServer + } + }) + } + + Mock -CommandName Get-SPWebApplication -MockWith { + return @(@{ + IsAdministrationWebApplication = $true + ContentDatabases = @(@{ + Name = $testParams.AdminContentDatabaseName + }) + Url = "http://$($env:ComputerName):$($testParams.CentralAdministrationPort)" + }) + } It "the get method returns values when the farm is configured" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "a farm exists locally and is not the correct farm" { - Mock Get-SPFarm { return @{ - DefaultServiceAccount = @{ Name = $testParams.FarmAccount.UserName } - Name = "WrongDBName" - }} - Mock Get-SPDatabase { return @(@{ - Name = "WrongDBName" - Type = "Configuration Database" - Server = @{ Name = $testParams.DatabaseServer } - })} - Mock Get-SPWebApplication { return @(@{ - IsAdministrationWebApplication = $true - ContentDatabases = @(@{ Name = $testParams.AdminContentDatabaseName }) - Url = "http://$($env:ComputerName):$($testParams.CentralAdministrationPort)" - })} - - It "throws an error in the set method" { + Context -Name "a farm exists locally and is not the correct farm" -Fixture { + $testParams = @{ + FarmConfigDatabaseName = "SP_Config" + DatabaseServer = "DatabaseServer\Instance" + FarmAccount = $mockFarmAccount + Passphrase = $mockPassphrase + AdminContentDatabaseName = "Admin_Content" + CentralAdministrationAuth = "Kerberos" + CentralAdministrationPort = 1234 + } + + Mock -CommandName Get-SPFarm -MockWith { + return @{ + DefaultServiceAccount = @{ Name = $testParams.FarmAccount.UserName } + Name = "WrongDBName" + } + } + + Mock -CommandName Get-SPDatabase -MockWith { + return @(@{ + Name = "WrongDBName" + Type = "Configuration Database" + Server = @{ + Name = $testParams.DatabaseServer + } + }) + } + + Mock -CommandName Get-SPWebApplication -MockWith { + return @(@{ + IsAdministrationWebApplication = $true + ContentDatabases = @(@{ + Name = $testParams.AdminContentDatabaseName + }) + Url = "http://$($env:ComputerName):$($testParams.CentralAdministrationPort)" + }) + } + + It "Should throw an error in the set method" { { Set-TargetResource @testParams } | Should throw } } - Context "a farm exists locally with the wrong farm account" { - Mock Get-SPFarm { return @{ - DefaultServiceAccount = @{ Name = "WRONG\account" } - Name = $testParams.FarmConfigDatabaseName - }} - Mock Get-SPDatabase { return @(@{ - Name = $testParams.FarmConfigDatabaseName - Type = "Configuration Database" - Server = @{ Name = $testParams.DatabaseServer } - })} - Mock Get-SPWebApplication { return @(@{ - IsAdministrationWebApplication = $true - ContentDatabases = @(@{ Name = $testParams.AdminContentDatabaseName }) - Url = "http://$($env:ComputerName):$($testParams.CentralAdministrationPort)" - })} + Context -Name "a farm exists locally with the wrong farm account" -Fixture { + $testParams = @{ + FarmConfigDatabaseName = "SP_Config" + DatabaseServer = "DatabaseServer\Instance" + FarmAccount = $mockFarmAccount + Passphrase = $mockPassphrase + AdminContentDatabaseName = "Admin_Content" + CentralAdministrationAuth = "Kerberos" + CentralAdministrationPort = 1234 + } + + Mock -CommandName Get-SPFarm -MockWith { + return @{ + DefaultServiceAccount = @{ Name = "WRONG\account" } + Name = $testParams.FarmConfigDatabaseName + } + } + + Mock -CommandName Get-SPDatabase -MockWith { + return @(@{ + Name = $testParams.FarmConfigDatabaseName + Type = "Configuration Database" + Server = @{ Name = $testParams.DatabaseServer } + }) + } + + Mock -CommandName Get-SPWebApplication -MockWith { + return @(@{ + IsAdministrationWebApplication = $true + ContentDatabases = @(@{ + Name = $testParams.AdminContentDatabaseName + }) + Url = "http://$($env:ComputerName):$($testParams.CentralAdministrationPort)" + }) + } It "the get method returns current values" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method as changing the farm account isn't supported so set shouldn't be called" { + It "Should return true from the test method as changing the farm account isn't supported so set shouldn't be called" { Test-TargetResource @testParams | Should Be $true } - } - Context "no farm is configured locally, a supported version is installed and no central admin port is specified" { - $testParams.Remove("CentralAdministrationPort") + Context -Name "no farm is configured locally, a supported version is installed and no central admin port is specified" -Fixture { + $testParams = @{ + FarmConfigDatabaseName = "SP_Config" + DatabaseServer = "DatabaseServer\Instance" + FarmAccount = $mockFarmAccount + Passphrase = $mockPassphrase + AdminContentDatabaseName = "Admin_Content" + CentralAdministrationAuth = "Kerberos" + } It "uses a default value for the central admin port" { Set-TargetResource @testParams @@ -190,13 +283,22 @@ Describe "SPCreateFarm - SharePoint Build $((Get-Item $SharePointCmdletModule).D } } - Context "no farm is configured locally, a supported version is installed and no central admin auth is specified" { - $testParams.Remove("CentralAdministrationAuth") + Context -Name "no farm is configured locally, a supported version is installed and no central admin auth is specified" -Fixture { + $testParams = @{ + FarmConfigDatabaseName = "SP_Config" + DatabaseServer = "DatabaseServer\Instance" + FarmAccount = $mockFarmAccount + Passphrase = $mockPassphrase + AdminContentDatabaseName = "Admin_Content" + } It "uses NTLM for the Central Admin web application authentication" { Set-TargetResource @testParams Assert-MockCalled New-SPCentralAdministration -ParameterFilter { $WindowsAuthProvider -eq "NTLM" } } } - } -} \ No newline at end of file + + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPDatabaseAAG.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPDatabaseAAG.Tests.ps1 index a9ed598e7..59cb8f2b0 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPDatabaseAAG.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPDatabaseAAG.Tests.ps1 @@ -1,38 +1,36 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPDatabaseAAG" -$ModuleName = "MSFT_SPDatabaseAAG" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPDatabaseAAG - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - DatabaseName = "SampleDatabase" - AGName = "AGName" - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Add-DatabaseToAvailabilityGroup { } - Mock Remove-DatabaseFromAvailabilityGroup { } - - Context "The database is not in an availability group, but should be" { - Mock Get-SPDatabase { + # Mocks for all contexts + Mock -CommandName Add-DatabaseToAvailabilityGroup -MockWith { } + Mock -CommandName Remove-DatabaseFromAvailabilityGroup -MockWith { } + + # Test contexts + Context -Name "The database is not in an availability group, but should be" -Fixture { + $testParams = @{ + DatabaseName = "SampleDatabase" + AGName = "AGName" + Ensure = "Present" + } + + Mock -CommandName Get-SPDatabase -MockWith { return @( @{ Name = $testParams.DatabaseName @@ -41,23 +39,28 @@ Describe "SPDatabaseAAG - SharePoint Build $((Get-Item $SharePointCmdletModule). ) } - it "returns the current values from the get method" { + It "Should return the current values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - it "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - it "calls the add cmdlet in the set method" { + It "Should call the add cmdlet in the set method" { Set-TargetResource @testParams Assert-MockCalled Add-DatabaseToAvailabilityGroup } } - Context "The database is not in the availability group and should not be" { - $testParams.Ensure = "Absent" - Mock Get-SPDatabase { + Context -Name "The database is not in the availability group and should not be" -Fixture { + $testParams = @{ + DatabaseName = "SampleDatabase" + AGName = "AGName" + Ensure = "Absent" + } + + Mock -CommandName Get-SPDatabase -MockWith { return @( @{ Name = $testParams.DatabaseName @@ -66,18 +69,23 @@ Describe "SPDatabaseAAG - SharePoint Build $((Get-Item $SharePointCmdletModule). ) } - it "returns the current values from the get method" { + It "Should return the current values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - it "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The database is in the correct availability group and should be" { - $testParams.Ensure = "Present" - Mock Get-SPDatabase { + Context -Name "The database is in the correct availability group and should be" -Fixture { + $testParams = @{ + DatabaseName = "SampleDatabase" + AGName = "AGName" + Ensure = "Present" + } + + Mock -CommandName Get-SPDatabase -MockWith { return @( @{ Name = $testParams.DatabaseName @@ -88,18 +96,23 @@ Describe "SPDatabaseAAG - SharePoint Build $((Get-Item $SharePointCmdletModule). ) } - it "returns the current values from the get method" { + It "Should return the current values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - it "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The database is in an availability group and should not be" { - $testParams.Ensure = "Absent" - Mock Get-SPDatabase { + Context -Name "The database is in an availability group and should not be" -Fixture { + $testParams = @{ + DatabaseName = "SampleDatabase" + AGName = "AGName" + Ensure = "Absent" + } + + Mock -CommandName Get-SPDatabase -MockWith { return @( @{ Name = $testParams.DatabaseName @@ -110,23 +123,28 @@ Describe "SPDatabaseAAG - SharePoint Build $((Get-Item $SharePointCmdletModule). ) } - it "returns the current values from the get method" { + It "Should return the current values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - it "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - it "calls the remove cmdlet in the set method" { + It "Should call the remove cmdlet in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-DatabaseFromAvailabilityGroup } } - Context "The database is in the wrong availability group" { - $testParams.Ensure = "Present" - Mock Get-SPDatabase { + Context -Name "The database is in the wrong availability group" -Fixture { + $testParams = @{ + DatabaseName = "SampleDatabase" + AGName = "AGName" + Ensure = "Present" + } + + Mock -CommandName Get-SPDatabase -MockWith { return @( @{ Name = $testParams.DatabaseName @@ -137,15 +155,15 @@ Describe "SPDatabaseAAG - SharePoint Build $((Get-Item $SharePointCmdletModule). ) } - it "returns the current values from the get method" { + It "Should return the current values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - it "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - it "calls the remove and add cmdlets in the set method" { + It "Should call the remove and add cmdlets in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-DatabaseFromAvailabilityGroup Assert-MockCalled Add-DatabaseToAvailabilityGroup @@ -154,3 +172,4 @@ Describe "SPDatabaseAAG - SharePoint Build $((Get-Item $SharePointCmdletModule). } } +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPDesignerSettings.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPDesignerSettings.Tests.ps1 index 382db5174..529efbd32 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPDesignerSettings.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPDesignerSettings.Tests.ps1 @@ -1,57 +1,73 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPDesignerSettings" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPDesignerSettings - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Url = "https://intranet.sharepoint.contoso.com" - SettingsScope = "WebApplication" - AllowSharePointDesigner = $false - AllowDetachPagesFromDefinition = $false - AllowCustomiseMasterPage = $false - AllowManageSiteURLStructure = $false - AllowCreateDeclarativeWorkflow = $false - AllowSavePublishDeclarativeWorkflow = $false - AllowSaveDeclarativeWorkflowAsTemplate = $false - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPDesignerSettings" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Mocks for all contexts + Mock -CommandName Get-SPFarm -MockWith { + return @{} } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Context "The server is not part of SharePoint farm" { - Mock Get-SPFarm { throw "Unable to detect local farm" } + # Test contexts + Context -Name "The server is not part of SharePoint farm" -Fixture { + $testParams = @{ + Url = "https://intranet.sharepoint.contoso.com" + SettingsScope = "WebApplication" + AllowSharePointDesigner = $false + AllowDetachPagesFromDefinition = $false + AllowCustomiseMasterPage = $false + AllowManageSiteURLStructure = $false + AllowCreateDeclarativeWorkflow = $false + AllowSavePublishDeclarativeWorkflow = $false + AllowSaveDeclarativeWorkflowAsTemplate = $false + } + + Mock -CommandName Get-SPFarm -MockWith { + throw "Unable to detect local farm" + } - It "return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Be $null } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws an exception in the set method to say there is no local farm" { + It "Should throw an exception in the set method to say there is no local farm" { { Set-TargetResource @testParams } | Should throw "No local SharePoint farm was detected" } } - Context "The server is in a farm, target web application and the incorrect settings have been applied" { - Mock Get-SPDesignerSettings { return @{ + Context -Name "The server is in a farm, target web application and the incorrect settings have been applied" -Fixture { + $testParams = @{ + Url = "https://intranet.sharepoint.contoso.com" + SettingsScope = "WebApplication" + AllowSharePointDesigner = $false + AllowDetachPagesFromDefinition = $false + AllowCustomiseMasterPage = $false + AllowManageSiteURLStructure = $false + AllowCreateDeclarativeWorkflow = $false + AllowSavePublishDeclarativeWorkflow = $false + AllowSaveDeclarativeWorkflowAsTemplate = $false + } + + Mock -CommandName Get-SPDesignerSettings -MockWith { return @{ AllowDesigner = $true AllowRevertFromTemplate = $true AllowMasterPageEditing = $true @@ -62,34 +78,34 @@ Describe "SPDesignerSettings - SharePoint Build $((Get-Item $SharePointCmdletMod } } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $result = @{} $result.DisplayName = "Test" $result.Url = "https://intranet.sharepoint.contoso.com" - $result = $result | Add-Member ScriptMethod Update { $Global:SPDSCDesignerUpdated = $true } -PassThru + $result = $result | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscDesignerUpdated = $true + } -PassThru return $result } - Mock Get-SPFarm { return @{} } - - It "return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPDSCDesignerUpdated = $false - It "updates the SharePoint Designer settings" { + $Global:SPDscDesignerUpdated = $false + It "Should update the SharePoint Designer settings" { Set-TargetResource @testParams - $Global:SPDSCDesignerUpdated | Should Be $true + $Global:SPDscDesignerUpdated | Should Be $true } } - Context "The server is in a farm, target site collection and the incorrect settings have been applied" { + Context -Name "The server is in a farm, target site collection and the incorrect settings have been applied" -Fixture { $testParams = @{ Url = "https://intranet.sharepoint.contoso.com" SettingsScope = "SiteCollection" @@ -101,7 +117,8 @@ Describe "SPDesignerSettings - SharePoint Build $((Get-Item $SharePointCmdletMod AllowSavePublishDeclarativeWorkflow = $false AllowSaveDeclarativeWorkflowAsTemplate = $false } - Mock Get-SPSite { + + Mock -CommandName Get-SPSite -MockWith { return @{ Url = "https://intranet.sharepoint.contoso.com" AllowDesigner = $true @@ -114,24 +131,22 @@ Describe "SPDesignerSettings - SharePoint Build $((Get-Item $SharePointCmdletMod } } - Mock Test-SPDSCRunAsCredential { return $true } - - Mock Get-SPFarm { return @{} } + Mock -CommandName Test-SPDSCRunAsCredential { return $true } - It "return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "updates the SharePoint Designer settings" { + It "Should update the SharePoint Designer settings" { Set-TargetResource @testParams } } - Context "The server is in a farm, target site collection and InstallAccount is used" { + Context -Name "The server is in a farm, target site collection and InstallAccount is used" -Fixture { $testParams = @{ Url = "https://intranet.sharepoint.contoso.com" SettingsScope = "SiteCollection" @@ -143,7 +158,7 @@ Describe "SPDesignerSettings - SharePoint Build $((Get-Item $SharePointCmdletMod AllowSavePublishDeclarativeWorkflow = $false AllowSaveDeclarativeWorkflowAsTemplate = $false } - Mock Get-SPSite { + Mock -CommandName Get-SPSite -MockWith { return @{ Url = "https://intranet.sharepoint.contoso.com" AllowDesigner = $true @@ -155,26 +170,37 @@ Describe "SPDesignerSettings - SharePoint Build $((Get-Item $SharePointCmdletMod AllowSaveDeclarativeWorkflowAsTemplate = $true } } - Mock Test-SPDSCRunAsCredential { return $false } + Mock -CommandName Test-SPDSCRunAsCredential { return $false } - Mock Get-SPFarm { return @{} } - - It "throws an exception in the get method to say that this is not supported" { + It "Should throw an exception in the get method to say that this is not supported" { { Get-TargetResource @testParams } | Should throw "http://aka.ms/xSharePointRemoteIssues" } - It "throws an exception in the test method to say that this is not supported" { + It "Should throw an exception in the test method to say that this is not supported" { { Test-TargetResource @testParams } | Should throw "http://aka.ms/xSharePointRemoteIssues" } - It "throws an exception in the set method to say that this is not supported" { + It "Should throw an exception in the set method to say that this is not supported" { { Set-TargetResource @testParams } | Should throw "http://aka.ms/xSharePointRemoteIssues" } } - Context "The server is in a farm, target is web application and the correct settings have been applied" { - Mock Get-SPDesignerSettings { + Context -Name "The server is in a farm, target is web application and the correct settings have been applied" -Fixture { + $testParams = @{ + Url = "https://intranet.sharepoint.contoso.com" + SettingsScope = "SiteCollection" + AllowSharePointDesigner = $false + AllowDetachPagesFromDefinition = $false + AllowCustomiseMasterPage = $false + AllowManageSiteURLStructure = $false + AllowCreateDeclarativeWorkflow = $false + AllowSavePublishDeclarativeWorkflow = $false + AllowSaveDeclarativeWorkflowAsTemplate = $false + } + + Mock -CommandName Get-SPSite -MockWith { $returnVal = @{ + Url = "https://intranet.sharepoint.contoso.com" AllowDesigner = $false AllowRevertFromTemplate = $false AllowMasterPageEditing = $false @@ -183,11 +209,15 @@ Describe "SPDesignerSettings - SharePoint Build $((Get-Item $SharePointCmdletMod AllowSavePublishDeclarativeWorkflow = $false AllowSaveDeclarativeWorkflowAsTemplate = $false } - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCDesignerUpdated = $true } -PassThru + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscDesignerUpdated = $true + } -PassThru return $returnVal } + + Mock -CommandName Test-SPDSCRunAsCredential { return $true } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebApplication -MockWith { $result = @{} $result.DisplayName = "Test" $result.Url = "https://intranet.sharepoint.contoso.com" @@ -195,19 +225,16 @@ Describe "SPDesignerSettings - SharePoint Build $((Get-Item $SharePointCmdletMod return $result } - Mock Get-SPFarm { return @{} } - - It "return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } - } - Context "The server is in a farm, target is site collection and the correct settings have been applied" { + Context -Name "The server is in a farm, target is site collection and the correct settings have been applied" -Fixture { $testParams = @{ Url = "https://intranet.sharepoint.contoso.com" SettingsScope = "SiteCollection" @@ -220,7 +247,7 @@ Describe "SPDesignerSettings - SharePoint Build $((Get-Item $SharePointCmdletMod AllowSaveDeclarativeWorkflowAsTemplate = $false } - Mock Get-SPSite { + Mock -CommandName Get-SPSite -MockWith { $returnVal = @{ Url = "https://intranet.sharepoint.contoso.com" AllowDesigner = $false @@ -231,21 +258,23 @@ Describe "SPDesignerSettings - SharePoint Build $((Get-Item $SharePointCmdletMod AllowSavePublishDeclarativeWorkflow = $false AllowSaveDeclarativeWorkflowAsTemplate = $false } - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCDesignerUpdated = $true } -PassThru + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscDesignerUpdated = $true + } -PassThru return $returnVal } - Mock Test-SPDSCRunAsCredential { return $true } - - Mock Get-SPFarm { return @{} } + Mock -CommandName Test-SPDSCRunAsCredential -MockWith { return $true } - It "return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPDiagnosticLoggingSettings.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPDiagnosticLoggingSettings.Tests.ps1 index c359ef71d..99a5ddefd 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPDiagnosticLoggingSettings.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPDiagnosticLoggingSettings.Tests.ps1 @@ -1,185 +1,281 @@ [CmdletBinding()] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPDiagnosticLoggingSettings" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPDiagnosticLoggingSettings - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - LogPath = "L:\ULSLogs" - LogSpaceInGB = 10 - AppAnalyticsAutomaticUploadEnabled = $true - CustomerExperienceImprovementProgramEnabled = $true - ErrorReportingEnabled = $true - ErrorReportingAutomaticUploadEnabled = $true - DownloadErrorReportingUpdatesEnabled = $true - DaysToKeepLogs = 7 - LogMaxDiskSpaceUsageEnabled = $true - LogCutInterval = 30 - ScriptErrorReportingEnabled = $true - ScriptErrorReportingRequireAuth = $true - ScriptErrorReportingDelay = 5 - EventLogFloodProtectionEnabled = $true - EventLogFloodProtectionThreshold = 10 - EventLogFloodProtectionTriggerPeriod = 5 - EventLogFloodProtectionQuietPeriod = 5 - EventLogFloodProtectionNotifyInterval = 5 - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPDiagnosticLoggingSettings" - Context "Diagnostic configuration can not be loaded" { - Mock Get-SPDiagnosticConfig { return $null } +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Mocks for all contexts + Mock -CommandName Set-SPDiagnosticConfig -MockWith {} + + # Test contexts + Context -Name "Diagnostic configuration can not be loaded" { + $testParams = @{ + LogPath = "L:\ULSLogs" + LogSpaceInGB = 10 + AppAnalyticsAutomaticUploadEnabled = $true + CustomerExperienceImprovementProgramEnabled = $true + ErrorReportingEnabled = $true + ErrorReportingAutomaticUploadEnabled = $true + DownloadErrorReportingUpdatesEnabled = $true + DaysToKeepLogs = 7 + LogMaxDiskSpaceUsageEnabled = $true + LogCutInterval = 30 + ScriptErrorReportingEnabled = $true + ScriptErrorReportingRequireAuth = $true + ScriptErrorReportingDelay = 5 + EventLogFloodProtectionEnabled = $true + EventLogFloodProtectionThreshold = 10 + EventLogFloodProtectionTriggerPeriod = 5 + EventLogFloodProtectionQuietPeriod = 5 + EventLogFloodProtectionNotifyInterval = 5 + } - It "returns null from the get method" { + Mock -CommandName Get-SPDiagnosticConfig -MockWith { + return $null + } + + It "Should return null from the get method" { Get-TargetResource @testParams | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "Diagnostic configuration can be loaded and it is configured correctly" { - Mock Get-SPDiagnosticConfig { return @{ - AppAnalyticsAutomaticUploadEnabled = $testParams.AppAnalyticsAutomaticUploadEnabled - CustomerExperienceImprovementProgramEnabled = $testParams.CustomerExperienceImprovementProgramEnabled - ErrorReportingEnabled = $testParams.ErrorReportingEnabled - ErrorReportingAutomaticUploadEnabled = $testParams.ErrorReportingAutomaticUploadEnabled - DownloadErrorReportingUpdatesEnabled = $testParams.DownloadErrorReportingUpdatesEnabled - DaysToKeepLogs = $testParams.DaysToKeepLogs - LogMaxDiskSpaceUsageEnabled = $testParams.LogMaxDiskSpaceUsageEnabled - LogDiskSpaceUsageGB = $testParams.LogSpaceInGB - LogLocation = $testParams.LogPath - LogCutInterval = $testParams.LogCutInterval - EventLogFloodProtectionEnabled = $testParams.EventLogFloodProtectionEnabled - EventLogFloodProtectionThreshold = $testParams.EventLogFloodProtectionThreshold - EventLogFloodProtectionTriggerPeriod = $testParams.EventLogFloodProtectionTriggerPeriod - EventLogFloodProtectionQuietPeriod = $testParams.EventLogFloodProtectionQuietPeriod - EventLogFloodProtectionNotifyInterval = $testParams.EventLogFloodProtectionNotifyInterval - ScriptErrorReportingEnabled = $testParams.ScriptErrorReportingEnabled - ScriptErrorReportingRequireAuth = $testParams.ScriptErrorReportingRequireAuth - ScriptErrorReportingDelay = $testParams.ScriptErrorReportingDelay - } } - - It "return values from the get method" { + Context -Name "Diagnostic configuration can be loaded and it is configured correctly" { + $testParams = @{ + LogPath = "L:\ULSLogs" + LogSpaceInGB = 10 + AppAnalyticsAutomaticUploadEnabled = $true + CustomerExperienceImprovementProgramEnabled = $true + ErrorReportingEnabled = $true + ErrorReportingAutomaticUploadEnabled = $true + DownloadErrorReportingUpdatesEnabled = $true + DaysToKeepLogs = 7 + LogMaxDiskSpaceUsageEnabled = $true + LogCutInterval = 30 + ScriptErrorReportingEnabled = $true + ScriptErrorReportingRequireAuth = $true + ScriptErrorReportingDelay = 5 + EventLogFloodProtectionEnabled = $true + EventLogFloodProtectionThreshold = 10 + EventLogFloodProtectionTriggerPeriod = 5 + EventLogFloodProtectionQuietPeriod = 5 + EventLogFloodProtectionNotifyInterval = 5 + } + + Mock -CommandName Get-SPDiagnosticConfig -MockWith { + return @{ + AppAnalyticsAutomaticUploadEnabled = $testParams.AppAnalyticsAutomaticUploadEnabled + CustomerExperienceImprovementProgramEnabled = $testParams.CustomerExperienceImprovementProgramEnabled + ErrorReportingEnabled = $testParams.ErrorReportingEnabled + ErrorReportingAutomaticUploadEnabled = $testParams.ErrorReportingAutomaticUploadEnabled + DownloadErrorReportingUpdatesEnabled = $testParams.DownloadErrorReportingUpdatesEnabled + DaysToKeepLogs = $testParams.DaysToKeepLogs + LogMaxDiskSpaceUsageEnabled = $testParams.LogMaxDiskSpaceUsageEnabled + LogDiskSpaceUsageGB = $testParams.LogSpaceInGB + LogLocation = $testParams.LogPath + LogCutInterval = $testParams.LogCutInterval + EventLogFloodProtectionEnabled = $testParams.EventLogFloodProtectionEnabled + EventLogFloodProtectionThreshold = $testParams.EventLogFloodProtectionThreshold + EventLogFloodProtectionTriggerPeriod = $testParams.EventLogFloodProtectionTriggerPeriod + EventLogFloodProtectionQuietPeriod = $testParams.EventLogFloodProtectionQuietPeriod + EventLogFloodProtectionNotifyInterval = $testParams.EventLogFloodProtectionNotifyInterval + ScriptErrorReportingEnabled = $testParams.ScriptErrorReportingEnabled + ScriptErrorReportingRequireAuth = $testParams.ScriptErrorReportingRequireAuth + ScriptErrorReportingDelay = $testParams.ScriptErrorReportingDelay + } + } + + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Diagnostic configuration can be loaded and the log path is not set correctly" { - Mock Get-SPDiagnosticConfig { return @{ - AppAnalyticsAutomaticUploadEnabled = $testParams.AppAnalyticsAutomaticUploadEnabled - CustomerExperienceImprovementProgramEnabled = $testParams.CustomerExperienceImprovementProgramEnabled - ErrorReportingEnabled = $testParams.ErrorReportingEnabled - ErrorReportingAutomaticUploadEnabled = $testParams.ErrorReportingAutomaticUploadEnabled - DownloadErrorReportingUpdatesEnabled = $testParams.DownloadErrorReportingUpdatesEnabled - DaysToKeepLogs = $testParams.DaysToKeepLogs - LogMaxDiskSpaceUsageEnabled = $testParams.LogMaxDiskSpaceUsageEnabled - LogDiskSpaceUsageGB = $testParams.LogSpaceInGB - LogLocation = "C:\incorrect\value" - LogCutInterval = $testParams.LogCutInterval - EventLogFloodProtectionEnabled = $testParams.EventLogFloodProtectionEnabled - EventLogFloodProtectionThreshold = $testParams.EventLogFloodProtectionThreshold - EventLogFloodProtectionTriggerPeriod = $testParams.EventLogFloodProtectionTriggerPeriod - EventLogFloodProtectionQuietPeriod = $testParams.EventLogFloodProtectionQuietPeriod - EventLogFloodProtectionNotifyInterval = $testParams.EventLogFloodProtectionNotifyInterval - ScriptErrorReportingEnabled = $testParams.ScriptErrorReportingEnabled - ScriptErrorReportingRequireAuth = $testParams.ScriptErrorReportingRequireAuth - ScriptErrorReportingDelay = $testParams.ScriptErrorReportingDelay - } } - - - It "returns false from the test method" { + Context -Name "Diagnostic configuration can be loaded and the log path is not set correctly" { + $testParams = @{ + LogPath = "L:\ULSLogs" + LogSpaceInGB = 10 + AppAnalyticsAutomaticUploadEnabled = $true + CustomerExperienceImprovementProgramEnabled = $true + ErrorReportingEnabled = $true + ErrorReportingAutomaticUploadEnabled = $true + DownloadErrorReportingUpdatesEnabled = $true + DaysToKeepLogs = 7 + LogMaxDiskSpaceUsageEnabled = $true + LogCutInterval = 30 + ScriptErrorReportingEnabled = $true + ScriptErrorReportingRequireAuth = $true + ScriptErrorReportingDelay = 5 + EventLogFloodProtectionEnabled = $true + EventLogFloodProtectionThreshold = 10 + EventLogFloodProtectionTriggerPeriod = 5 + EventLogFloodProtectionQuietPeriod = 5 + EventLogFloodProtectionNotifyInterval = 5 + } + + Mock -CommandName Get-SPDiagnosticConfig -MockWith { + return @{ + AppAnalyticsAutomaticUploadEnabled = $testParams.AppAnalyticsAutomaticUploadEnabled + CustomerExperienceImprovementProgramEnabled = $testParams.CustomerExperienceImprovementProgramEnabled + ErrorReportingEnabled = $testParams.ErrorReportingEnabled + ErrorReportingAutomaticUploadEnabled = $testParams.ErrorReportingAutomaticUploadEnabled + DownloadErrorReportingUpdatesEnabled = $testParams.DownloadErrorReportingUpdatesEnabled + DaysToKeepLogs = $testParams.DaysToKeepLogs + LogMaxDiskSpaceUsageEnabled = $testParams.LogMaxDiskSpaceUsageEnabled + LogDiskSpaceUsageGB = $testParams.LogSpaceInGB + LogLocation = "C:\incorrect\value" + LogCutInterval = $testParams.LogCutInterval + EventLogFloodProtectionEnabled = $testParams.EventLogFloodProtectionEnabled + EventLogFloodProtectionThreshold = $testParams.EventLogFloodProtectionThreshold + EventLogFloodProtectionTriggerPeriod = $testParams.EventLogFloodProtectionTriggerPeriod + EventLogFloodProtectionQuietPeriod = $testParams.EventLogFloodProtectionQuietPeriod + EventLogFloodProtectionNotifyInterval = $testParams.EventLogFloodProtectionNotifyInterval + ScriptErrorReportingEnabled = $testParams.ScriptErrorReportingEnabled + ScriptErrorReportingRequireAuth = $testParams.ScriptErrorReportingRequireAuth + ScriptErrorReportingDelay = $testParams.ScriptErrorReportingDelay + } + } + + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "Diagnostic configuration can be loaded and the log size is not set correctly" { - Mock Get-SPDiagnosticConfig { return @{ - AppAnalyticsAutomaticUploadEnabled = $testParams.AppAnalyticsAutomaticUploadEnabled - CustomerExperienceImprovementProgramEnabled = $testParams.CustomerExperienceImprovementProgramEnabled - ErrorReportingEnabled = $testParams.ErrorReportingEnabled - ErrorReportingAutomaticUploadEnabled = $testParams.ErrorReportingAutomaticUploadEnabled - DownloadErrorReportingUpdatesEnabled = $testParams.DownloadErrorReportingUpdatesEnabled - DaysToKeepLogs = $testParams.DaysToKeepLogs - LogMaxDiskSpaceUsageEnabled = $testParams.LogMaxDiskSpaceUsageEnabled - LogDiskSpaceUsageGB = 1 - LogLocation = $testParams.LogPath - LogCutInterval = $testParams.LogCutInterval - EventLogFloodProtectionEnabled = $testParams.EventLogFloodProtectionEnabled - EventLogFloodProtectionThreshold = $testParams.EventLogFloodProtectionThreshold - EventLogFloodProtectionTriggerPeriod = $testParams.EventLogFloodProtectionTriggerPeriod - EventLogFloodProtectionQuietPeriod = $testParams.EventLogFloodProtectionQuietPeriod - EventLogFloodProtectionNotifyInterval = $testParams.EventLogFloodProtectionNotifyInterval - ScriptErrorReportingEnabled = $testParams.ScriptErrorReportingEnabled - ScriptErrorReportingRequireAuth = $testParams.ScriptErrorReportingRequireAuth - ScriptErrorReportingDelay = $testParams.ScriptErrorReportingDelay - } } - - It "returns false from the test method" { + Context -Name "Diagnostic configuration can be loaded and the log size is not set correctly" { + $testParams = @{ + LogPath = "L:\ULSLogs" + LogSpaceInGB = 10 + AppAnalyticsAutomaticUploadEnabled = $true + CustomerExperienceImprovementProgramEnabled = $true + ErrorReportingEnabled = $true + ErrorReportingAutomaticUploadEnabled = $true + DownloadErrorReportingUpdatesEnabled = $true + DaysToKeepLogs = 7 + LogMaxDiskSpaceUsageEnabled = $true + LogCutInterval = 30 + ScriptErrorReportingEnabled = $true + ScriptErrorReportingRequireAuth = $true + ScriptErrorReportingDelay = 5 + EventLogFloodProtectionEnabled = $true + EventLogFloodProtectionThreshold = 10 + EventLogFloodProtectionTriggerPeriod = 5 + EventLogFloodProtectionQuietPeriod = 5 + EventLogFloodProtectionNotifyInterval = 5 + } + + Mock -CommandName Get-SPDiagnosticConfig -MockWith { + return @{ + AppAnalyticsAutomaticUploadEnabled = $testParams.AppAnalyticsAutomaticUploadEnabled + CustomerExperienceImprovementProgramEnabled = $testParams.CustomerExperienceImprovementProgramEnabled + ErrorReportingEnabled = $testParams.ErrorReportingEnabled + ErrorReportingAutomaticUploadEnabled = $testParams.ErrorReportingAutomaticUploadEnabled + DownloadErrorReportingUpdatesEnabled = $testParams.DownloadErrorReportingUpdatesEnabled + DaysToKeepLogs = $testParams.DaysToKeepLogs + LogMaxDiskSpaceUsageEnabled = $testParams.LogMaxDiskSpaceUsageEnabled + LogDiskSpaceUsageGB = 1 + LogLocation = $testParams.LogPath + LogCutInterval = $testParams.LogCutInterval + EventLogFloodProtectionEnabled = $testParams.EventLogFloodProtectionEnabled + EventLogFloodProtectionThreshold = $testParams.EventLogFloodProtectionThreshold + EventLogFloodProtectionTriggerPeriod = $testParams.EventLogFloodProtectionTriggerPeriod + EventLogFloodProtectionQuietPeriod = $testParams.EventLogFloodProtectionQuietPeriod + EventLogFloodProtectionNotifyInterval = $testParams.EventLogFloodProtectionNotifyInterval + ScriptErrorReportingEnabled = $testParams.ScriptErrorReportingEnabled + ScriptErrorReportingRequireAuth = $testParams.ScriptErrorReportingRequireAuth + ScriptErrorReportingDelay = $testParams.ScriptErrorReportingDelay + } + } + + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "repairs the diagnostic configuration" { - Mock Set-SPDiagnosticConfig {} + It "Should repair the diagnostic configuration" { Set-TargetResource @testParams Assert-MockCalled Set-SPDiagnosticConfig } } - Context "Diagnostic configuration needs updating and the InstallAccount option is used" { - $testParams.Add("InstallAccount", (New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force))) ) - - Mock Get-SPDiagnosticConfig { return @{ - AppAnalyticsAutomaticUploadEnabled = $testParams.AppAnalyticsAutomaticUploadEnabled - CustomerExperienceImprovementProgramEnabled = $testParams.CustomerExperienceImprovementProgramEnabled - ErrorReportingEnabled = $testParams.ErrorReportingEnabled - ErrorReportingAutomaticUploadEnabled = $testParams.ErrorReportingAutomaticUploadEnabled - DownloadErrorReportingUpdatesEnabled = $testParams.DownloadErrorReportingUpdatesEnabled - DaysToKeepLogs = $testParams.DaysToKeepLogs - LogMaxDiskSpaceUsageEnabled = $testParams.LogMaxDiskSpaceUsageEnabled - LogDiskSpaceUsageGB = 1 - LogLocation = $testParams.LogPath - LogCutInterval = $testParams.LogCutInterval - EventLogFloodProtectionEnabled = $testParams.EventLogFloodProtectionEnabled - EventLogFloodProtectionThreshold = $testParams.EventLogFloodProtectionThreshold - EventLogFloodProtectionTriggerPeriod = $testParams.EventLogFloodProtectionTriggerPeriod - EventLogFloodProtectionQuietPeriod = $testParams.EventLogFloodProtectionQuietPeriod - EventLogFloodProtectionNotifyInterval = $testParams.EventLogFloodProtectionNotifyInterval - ScriptErrorReportingEnabled = $testParams.ScriptErrorReportingEnabled - ScriptErrorReportingRequireAuth = $testParams.ScriptErrorReportingRequireAuth - ScriptErrorReportingDelay = $testParams.ScriptErrorReportingDelay - } } - - It "returns false from the test method" { + Context -Name "Diagnostic configuration needs updating and the InstallAccount option is used" { + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $mockAccount = New-Object -TypeName "System.Management.Automation.PSCredential" ` + -ArgumentList @("username", $mockPassword) + $testParams = @{ + LogPath = "L:\ULSLogs" + LogSpaceInGB = 10 + AppAnalyticsAutomaticUploadEnabled = $true + CustomerExperienceImprovementProgramEnabled = $true + ErrorReportingEnabled = $true + ErrorReportingAutomaticUploadEnabled = $true + DownloadErrorReportingUpdatesEnabled = $true + DaysToKeepLogs = 7 + LogMaxDiskSpaceUsageEnabled = $true + LogCutInterval = 30 + ScriptErrorReportingEnabled = $true + ScriptErrorReportingRequireAuth = $true + ScriptErrorReportingDelay = 5 + EventLogFloodProtectionEnabled = $true + EventLogFloodProtectionThreshold = 10 + EventLogFloodProtectionTriggerPeriod = 5 + EventLogFloodProtectionQuietPeriod = 5 + EventLogFloodProtectionNotifyInterval = 5 + InstallAccount = $mockAccount + } + + Mock -CommandName Get-SPDiagnosticConfig -MockWith { + return @{ + AppAnalyticsAutomaticUploadEnabled = $testParams.AppAnalyticsAutomaticUploadEnabled + CustomerExperienceImprovementProgramEnabled = $testParams.CustomerExperienceImprovementProgramEnabled + ErrorReportingEnabled = $testParams.ErrorReportingEnabled + ErrorReportingAutomaticUploadEnabled = $testParams.ErrorReportingAutomaticUploadEnabled + DownloadErrorReportingUpdatesEnabled = $testParams.DownloadErrorReportingUpdatesEnabled + DaysToKeepLogs = $testParams.DaysToKeepLogs + LogMaxDiskSpaceUsageEnabled = $testParams.LogMaxDiskSpaceUsageEnabled + LogDiskSpaceUsageGB = 1 + LogLocation = $testParams.LogPath + LogCutInterval = $testParams.LogCutInterval + EventLogFloodProtectionEnabled = $testParams.EventLogFloodProtectionEnabled + EventLogFloodProtectionThreshold = $testParams.EventLogFloodProtectionThreshold + EventLogFloodProtectionTriggerPeriod = $testParams.EventLogFloodProtectionTriggerPeriod + EventLogFloodProtectionQuietPeriod = $testParams.EventLogFloodProtectionQuietPeriod + EventLogFloodProtectionNotifyInterval = $testParams.EventLogFloodProtectionNotifyInterval + ScriptErrorReportingEnabled = $testParams.ScriptErrorReportingEnabled + ScriptErrorReportingRequireAuth = $testParams.ScriptErrorReportingRequireAuth + ScriptErrorReportingDelay = $testParams.ScriptErrorReportingDelay + } + } + + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "repairs the diagnostic configuration" { - Mock Set-SPDiagnosticConfig {} + It "Should repair the diagnostic configuration" { Set-TargetResource @testParams Assert-MockCalled Set-SPDiagnosticConfig } } - } -} \ No newline at end of file + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPDistributedCacheService.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPDistributedCacheService.Tests.ps1 index 63ee27132..8b529e785 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPDistributedCacheService.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPDistributedCacheService.Tests.ps1 @@ -1,118 +1,216 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPDistributedCacheService" ` + -IncludeDistributedCacheStubs -$ModuleName = "MSFT_SPDistributedCacheService" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPDistributedCacheService - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "AppFabricCache" - Ensure = "Present" - CacheSizeInMB = 1024 - ServiceAccount = "DOMAIN\user" - CreateFirewallRules = $true + # Mocks for all contexts + Mock Use-CacheCluster -MockWith { } + Mock -CommandName Get-WmiObject -MockWith { + return @{ + StartName = $testParams.ServiceAccount + } } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + Mock -CommandName Get-NetFirewallRule -MockWith { + return @{} } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - $RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path - Import-Module "$RepoRoot\Tests\Unit\Stubs\DistributedCache\DistributedCache.psm1" -WarningAction SilentlyContinue - Mock Use-CacheCluster { } - Mock Get-WmiObject { return @{ StartName = $testParams.ServiceAccount } } - Mock Get-NetFirewallRule { return @{} } - Mock Get-NetFirewallRule { return @{} } - Mock Enable-NetFirewallRule { } - Mock New-NetFirewallRule { } - Mock Disable-NetFirewallRule { } - Mock Add-SPDistributedCacheServiceInstance { } - Mock Update-SPDistributedCacheSize { } - Mock Get-SPManagedAccount { return @{} } - Mock Add-SPDSCUserToLocalAdmin { } - Mock Test-SPDSCUserIsLocalAdmin { return $false } - Mock Remove-SPDSCUserToLocalAdmin { } - Mock Restart-Service { } - Mock Get-SPFarm { return @{ - Services = @(@{ - Name = "AppFabricCachingService" - ProcessIdentity = New-Object Object | - Add-Member NoteProperty ManagedAccount $null -PassThru | - Add-Member NoteProperty CurrentIdentityType $null -PassThru | - Add-Member ScriptMethod Update {} -PassThru | - Add-Member ScriptMethod Deploy {} -PassThru - }) + Mock -CommandName Get-NetFirewallRule -MockWith { + return @{} + } + Mock -CommandName Enable-NetFirewallRule -MockWith { } + Mock -CommandName New-NetFirewallRule -MockWith { } + Mock -CommandName Disable-NetFirewallRule -MockWith { } + Mock -CommandName Add-SPDistributedCacheServiceInstance -MockWith { } + Mock Update-SPDistributedCacheSize -MockWith { } + Mock -CommandName Get-SPManagedAccount -MockWith { + return @{} + } + Mock -CommandName Add-SPDSCUserToLocalAdmin -MockWith { } + Mock -CommandName Test-SPDSCUserIsLocalAdmin -MockWith { + return $false + } + Mock -CommandName Remove-SPDSCUserToLocalAdmin -MockWith { } + Mock Restart-Service -MockWith { } + Mock -CommandName Get-SPFarm -MockWith { + return @{ + Services = @(@{ + Name = "AppFabricCachingService" + ProcessIdentity = New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name ManagedAccount ` + -Value $null ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name CurrentIdentityType ` + -Value $null ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value {} ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Deploy ` + -Value {} ` + -PassThru + }) } } - Mock Stop-SPServiceInstance { $Global:SPDSCDCacheOnline = $false } - Mock Start-SPServiceInstance { $Global:SPDSCDCacheOnline = $true } - - Mock Get-SPServiceInstance { - if ($Global:SPDSCDCacheOnline -eq $false) { - return @(New-Object Object | - Add-Member NoteProperty TypeName "Distributed Cache" -PassThru | - Add-Member NoteProperty Status "Disabled" -PassThru | - Add-Member NoteProperty Service "SPDistributedCacheService Name=AppFabricCachingService" -PassThru | - Add-Member NoteProperty Server @{ Name = $env:COMPUTERNAME } -PassThru | - Add-Member ScriptMethod Delete {} -PassThru) - } else { - return @(New-Object Object | - Add-Member NoteProperty TypeName "Distributed Cache" -PassThru | - Add-Member NoteProperty Status "Online" -PassThru | - Add-Member NoteProperty Service "SPDistributedCacheService Name=AppFabricCachingService" -PassThru | - Add-Member NoteProperty Server @{ Name = $env:COMPUTERNAME } -PassThru | - Add-Member ScriptMethod Delete {} -PassThru) - } - + Mock -CommandName Stop-SPServiceInstance -MockWith { + $Global:SPDscDCacheOnline = $false + } + Mock -CommandName Start-SPServiceInstance -MockWith { + $Global:SPDscDCacheOnline = $true + } + + Mock -CommandName Get-SPServiceInstance -MockWith { + if ($Global:SPDscDCacheOnline -eq $false) + { + return @(New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Status ` + -Value "Disabled" ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name Service ` + -Value "SPDistributedCacheService Name=AppFabricCachingService" ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name Server ` + -Value @{ + Name = $env:COMPUTERNAME + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Delete ` + -Value {} ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "SPDistributedCacheServiceInstance" ` + -PassThru + } -PassThru -Force) + } + else + { + return @(New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Status ` + -Value "Online" ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name Service ` + -Value "SPDistributedCacheService Name=AppFabricCachingService" ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name Server ` + -Value @{ + Name = $env:COMPUTERNAME + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Delete ` + -Value {} ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "SPDistributedCacheServiceInstance" ` + -PassThru + } -PassThru -Force) + } + } + + # Test contexts + Context -Name "Distributed cache is not configured" -Fixture { + $testParams = @{ + Name = "AppFabricCache" + Ensure = "Present" + CacheSizeInMB = 1024 + ServiceAccount = "DOMAIN\user" + CreateFirewallRules = $true } - Context "Distributed cache is not configured" { - Mock Use-CacheCluster { throw [Exception] "ERRPS001 Error in reading provider and connection string values." } - $Global:SPDSCDCacheOnline = $false + Mock Use-CacheCluster -MockWith { + throw [Exception] "ERRPS001 Error in reading provider and connection string values." + } + $Global:SPDscDCacheOnline = $false - It "returns null from the get method" { + It "Should return null from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "Sets up the cache correctly" { + It "Should set up the cache correctly" { Set-TargetResource @testParams Assert-MockCalled Add-SPDistributedCacheServiceInstance } } - Context "Distributed cache is configured correctly and running as required" { - $Global:SPDSCDCacheOnline = $true + Context -Name "Distributed cache is configured correctly and running as required" -Fixture { + $testParams = @{ + Name = "AppFabricCache" + Ensure = "Present" + CacheSizeInMB = 1024 + ServiceAccount = "DOMAIN\user" + CreateFirewallRules = $true + } + + $Global:SPDscDCacheOnline = $true - Mock Get-AFCacheHostConfiguration { return @{ - Size = $testParams.CacheSizeInMB - }} - Mock Get-CacheHost { return @{ PortNo = 22233 } } + Mock -CommandName Get-AFCacheHostConfiguration -MockWith { + return @{ + Size = $testParams.CacheSizeInMB + } + } + Mock -CommandName Get-CacheHost -MockWith { + return @{ + PortNo = 22233 + } + } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Distributed cache is configured but the required firewall rules are not deployed" { - $Global:SPDSCDCacheOnline = $true - Mock Get-NetFirewallRule { return $null } + Context -Name "Distributed cache is configured but the required firewall rules are not deployed" -Fixture { + $testParams = @{ + Name = "AppFabricCache" + Ensure = "Present" + CacheSizeInMB = 1024 + ServiceAccount = "DOMAIN\user" + CreateFirewallRules = $true + } + + $Global:SPDscDCacheOnline = $true + + Mock -CommandName Get-NetFirewallRule -MockWith { + return $null + } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } @@ -122,17 +220,33 @@ Describe "SPDistributedCacheService - SharePoint Build $((Get-Item $SharePointCm } } - Context "Distributed cache is confgured but should not be running on this machine" { - $Global:SPDSCDCacheOnline = $true - $testParams.Ensure = "Absent" - Mock Get-AFCacheHostConfiguration { return @{ - Size = $testParams.CacheSizeInMB - }} - Mock Get-CacheHost { return @{ PortNo = 22233 } } - Mock Get-NetFirewallRule { return @{} } - Mock Remove-SPDistributedCacheServiceInstance { } - - It "returns false from the test method" { + Context -Name "Distributed cache is confgured but should not be running on this machine" -Fixture { + $testParams = @{ + Name = "AppFabricCache" + Ensure = "Absent" + CacheSizeInMB = 1024 + ServiceAccount = "DOMAIN\user" + CreateFirewallRules = $true + } + + $Global:SPDscDCacheOnline = $true + + Mock -CommandName Get-AFCacheHostConfiguration -MockWith { + return @{ + Size = $testParams.CacheSizeInMB + } + } + Mock -CommandName Get-CacheHost -MockWith { + return @{ + PortNo = 22233 + } + } + Mock -CommandName Get-NetFirewallRule -MockWith { + return @{} + } + Mock -CommandName Remove-SPDistributedCacheServiceInstance -MockWith { } + + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } @@ -142,5 +256,7 @@ Describe "SPDistributedCacheService - SharePoint Build $((Get-Item $SharePointCm Assert-MockCalled Disable-NetFirewallRule } } - } -} \ No newline at end of file + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPExcelServiceApp.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPExcelServiceApp.Tests.ps1 index b0ad7136e..1eeb4ecb2 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPExcelServiceApp.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPExcelServiceApp.Tests.ps1 @@ -1,147 +1,375 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPExcelServiceApp" -$ModuleName = "MSFT_SPExcelServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPExcelServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Test Excel Services App" - ApplicationPool = "Test App Pool" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - $versionBeingTested = (Get-Item $Global:CurrentSharePointStubModule).Directory.BaseName - $majorBuildNumber = $versionBeingTested.Substring(0, $versionBeingTested.IndexOf(".")) - Mock Get-SPDSCInstalledProductVersion { return @{ FileMajorPart = $majorBuildNumber } } - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue + # Initialize tests + $getTypeFullName = "Microsoft.Office.Excel.Server.MossHost.ExcelServerWebServiceApplication" + + # Mocks for all contexts + Mock -CommandName Remove-SPServiceApplication -MockWith { } + Mock -CommandName New-SPExcelServiceApplication -MockWith { } + Mock -CommandName Get-SPExcelFileLocation -MockWith { } + Mock -CommandName Set-SPExcelServiceApplication -MockWith { } + Mock -CommandName New-SPExcelFileLocation -MockWith { } + Mock -CommandName Set-SPExcelFileLocation -MockWith { } + Mock -CommandName Remove-SPExcelFileLocation -MockWith { } - Mock Remove-SPServiceApplication { } - - switch ($majorBuildNumber) { + # Test contexts + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) + { 15 { - Context "When no service applications exist in the current farm" { + Context -Name "When no service applications exist in the current farm" -Fixture { + $testParams = @{ + Name = "Test Excel Services App" + ApplicationPool = "Test App Pool" + } - Mock Get-SPServiceApplication { return $null } - Mock New-SPExcelServiceApplication { } + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPExcelServiceApplication } } - Context "When service applications exist in the current farm but the specific Excel Services app does not" { + Context -Name "When service applications exist in the current farm but the specific Excel Services app does not" -Fixture { + $testParams = @{ + Name = "Test Excel Services App" + ApplicationPool = "Test App Pool" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = "Microsoft.Office.UnKnownWebServiceApplication" + } + } -PassThru -Force + return $spServiceApp + } - Mock Get-SPServiceApplication { return @(@{ + Mock -CommandName Get-SPServiceApplication -MockWith { return @(@{ TypeName = "Some other service app type" }) } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } } - Context "When a service application exists and is configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When a service application exists and is configured correctly" -Fixture { + $testParams = @{ + Name = "Test Excel Services App" + ApplicationPool = "Test App Pool" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Excel Services Application Web Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns values from the get method" { + It "Should return values from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } - $testParams = @{ - Name = "Test App" - ApplicationPool = "-" - Ensure = "Absent" - } - Context "When the service application exists but it shouldn't" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When the service application exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Excel Services Application Web Service Application" DisplayName = $testParams.Name - DatabaseServer = $testParams.DatabaseServer ApplicationPool = @{ Name = $testParams.ApplicationPool } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns present from the Get method" { + It "Should return present from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "calls the remove service application cmdlet in the set method" { + It "Should call the remove service application cmdlet in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplication } } - Context "When the serivce application doesn't exist and it shouldn't" { - Mock Get-SPServiceApplication { return $null } + Context -Name "When the serivce application doesn't exist and it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { return $null } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { + Test-TargetResource @testParams | Should Be $true + } + } + + Context -Name "When the service app should have trusted locations, but doesn't" -Fixture { + $testParams = @{ + Name = "Test Excel Services App" + ApplicationPool = "Test App Pool" + TrustedFileLocations = @( + (New-CimInstance -ClassName MSFT_SPExcelFileLocation -ClientOnly -Property @{ + Address = "http://" + LocationType = "SharePoint" + WorkbookSizeMax = 10 + }) + ) + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + TypeName = "Excel Services Application Web Service Application" + DisplayName = $testParams.Name + ApplicationPool = @{ Name = $testParams.ApplicationPool } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + + Mock -CommandName Get-SPExcelFileLocation -MockWith { + return @() + } + + It "Should return no trusted location results from the get method" { + (Get-TargetResource @testParams).TrustedFileLocations | Should BeNullOrEmpty + } + + It "Should return false from the test method" { + Test-TargetResource @testParams | Should Be $false + } + + It "Should create the trusted location in the set method" { + Set-TargetResource @testParams + Assert-MockCalled -CommandName New-SPExcelFileLocation + } + } + + Context -Name "When the service app should have trusted locations, but the settings don't match" -Fixture { + $testParams = @{ + Name = "Test Excel Services App" + ApplicationPool = "Test App Pool" + TrustedFileLocations = @( + (New-CimInstance -ClassName MSFT_SPExcelFileLocation -ClientOnly -Property @{ + Address = "http://" + LocationType = "SharePoint" + WorkbookSizeMax = 10 + }) + ) + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + TypeName = "Excel Services Application Web Service Application" + DisplayName = $testParams.Name + ApplicationPool = @{ Name = $testParams.ApplicationPool } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + + Mock -CommandName Get-SPExcelFileLocation -MockWith { + return @(@{ + Address = "http://" + LocationType = "SharePoint" + WorkbookSizeMax = 2 + }) + } + + It "Should return trusted location results from the get method" { + (Get-TargetResource @testParams).TrustedFileLocations | Should Not BeNullOrEmpty + } + + It "Should return false from the test method" { + Test-TargetResource @testParams | Should Be $false + } + + It "Should update the trusted location in the set method" { + Set-TargetResource @testParams + Assert-MockCalled -CommandName Set-SPExcelFileLocation + } + } + + Context -Name "When the service app should have trusted locations, and does" -Fixture { + $testParams = @{ + Name = "Test Excel Services App" + ApplicationPool = "Test App Pool" + TrustedFileLocations = @( + (New-CimInstance -ClassName MSFT_SPExcelFileLocation -ClientOnly -Property @{ + Address = "http://" + LocationType = "SharePoint" + WorkbookSizeMax = 10 + }) + ) + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + TypeName = "Excel Services Application Web Service Application" + DisplayName = $testParams.Name + ApplicationPool = @{ Name = $testParams.ApplicationPool } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + + Mock -CommandName Get-SPExcelFileLocation -MockWith { + return @(@{ + Address = "http://" + LocationType = "SharePoint" + WorkbookSizeMax = 10 + }) + } + + It "Should return trusted location results from the get method" { + (Get-TargetResource @testParams).TrustedFileLocations | Should Not BeNullOrEmpty + } + + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } + + Context -Name "When the service app should have trusted locations, and does but also has an extra one that should be removed" -Fixture { + $testParams = @{ + Name = "Test Excel Services App" + ApplicationPool = "Test App Pool" + TrustedFileLocations = @( + (New-CimInstance -ClassName MSFT_SPExcelFileLocation -ClientOnly -Property @{ + Address = "http://" + LocationType = "SharePoint" + WorkbookSizeMax = 10 + }) + ) + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + TypeName = "Excel Services Application Web Service Application" + DisplayName = $testParams.Name + ApplicationPool = @{ Name = $testParams.ApplicationPool } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + + Mock -CommandName Get-SPExcelFileLocation -MockWith { + return @(@{ + Address = "http://" + LocationType = "SharePoint" + WorkbookSizeMax = 10 + }, + @{ + Address = "https://" + LocationType = "SharePoint" + WorkbookSizeMax = 10 + }) + } + + It "Should return trusted location results from the get method" { + (Get-TargetResource @testParams).TrustedFileLocations | Should Not BeNullOrEmpty + } + + It "Should return false from the test method" { + Test-TargetResource @testParams | Should Be $false + } + + It "Should remove the trusted location in the set method" { + Set-TargetResource @testParams + Assert-MockCalled -CommandName Remove-SPExcelFileLocation + } + } } 16 { - Context "All methods throw exceptions as Excel Services doesn't exist in 2016" { - It "throws on the get method" { + Context -Name "All methods throw exceptions as Excel Services doesn't exist in 2016" -Fixture { + It "Should throw on the get method" { { Get-TargetResource @testParams } | Should Throw } - It "throws on the test method" { + It "Should throw on the test method" { { Test-TargetResource @testParams } | Should Throw } - It "throws on the set method" { + It "Should throw on the set method" { { Set-TargetResource @testParams } | Should Throw } } } + Default { + throw [Exception] "A supported version of SharePoint was not used in testing" + } } - - } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPFarmAdministrators.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPFarmAdministrators.Tests.ps1 index 8de7eb254..5b68900f3 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPFarmAdministrators.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPFarmAdministrators.Tests.ps1 @@ -1,320 +1,468 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPFarmAdministrators" -$ModuleName = "MSFT_SPFarmAdministrators" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPFarmAdministrators - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Farm Administrators" - Members = @("Demo\User1", "Demo\User2") - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + # Test contexts + Context -Name "No central admin site exists" { + $testParams = @{ + Name = "Farm Administrators" + Members = @("Demo\User1", "Demo\User2") + } - Context "No central admin site exists" { - Mock Get-SPwebapplication { return $null } + Mock -CommandName Get-SPwebapplication -MockWith { return $null } - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "Unable to locate central administration website" } } - Context "Central admin exists and a fixed members list is used which matches" { - Mock Get-SPwebapplication { return @{ + Context -Name "Central admin exists and a fixed members list is used which matches" -Fixture { + $testParams = @{ + Name = "Farm Administrators" + Members = @("Demo\User1", "Demo\User2") + } + + Mock -CommandName Get-SPwebapplication -MockWith { + return @{ IsAdministrationWebApplication = $true Url = "http://admin.shareopoint.contoso.local" - }} - Mock Get-SPWeb { - $web = @{ + } + } + Mock -CommandName Get-SPWeb -MockWith { + return @{ AssociatedOwnerGroup = "Farm Administrators" - SiteGroups = New-Object Object | Add-Member ScriptMethod GetByName { - return @{ - Users = @( - @{ UserLogin = "Demo\User1" }, - @{ UserLogin = "Demo\User2" } - ) - } - } -PassThru + SiteGroups = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name GetByName ` + -Value { + return @{ + Users = @( + @{ UserLogin = "Demo\User1" }, + @{ UserLogin = "Demo\User2" } + ) + } + } -PassThru } - return $web } - It "should return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Central admin exists and a fixed members list is used which does not match" { - Mock Get-SPwebapplication { return @{ + Context -Name "Central admin exists and a fixed members list is used which does not match" -Fixture { + $testParams = @{ + Name = "Farm Administrators" + Members = @("Demo\User1", "Demo\User2") + } + + Mock -CommandName Get-SPwebapplication -MockWith { + return @{ IsAdministrationWebApplication = $true Url = "http://admin.shareopoint.contoso.local" - }} - Mock Get-SPWeb { - return @{ + } + } + + Mock -CommandName Get-SPWeb -MockWith { + $web = @{ AssociatedOwnerGroup = "Farm Administrators" - SiteGroups = New-Object Object | Add-Member ScriptMethod GetByName { - return New-Object Object | Add-Member ScriptProperty Users { - return @( - @{ UserLogin = "Demo\User1" } - ) - } -PassThru | Add-Member ScriptMethod AddUser { } -PassThru ` - | Add-Member ScriptMethod RemoveUser { } -PassThru - } -PassThru + SiteGroups = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name GetByName ` + -Value { + return New-Object -TypeName "Object" | + Add-Member -MemberType ScriptProperty ` + -Name Users ` + -Value { + return @( + @{ + UserLogin = "Demo\User1" + } + ) + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name AddUser ` + -Value { } ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name RemoveUser ` + -Value { } ` + -PassThru + } -PassThru } + return $web + } + + Mock -CommandName Get-SPUser -MockWith { + return @{} } - Mock Get-SPUser { return @{} } - It "should return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should update the members list" { + It "Should update the members list" { Set-TargetResource @testParams } } - Context "Central admin exists and a members to include is set where the members are in the group" { + Context -Name "Central admin exists and a members to include is set where the members are in the group" -Fixture { $testParams = @{ Name = "Farm Administrators" MembersToInclude = @("Demo\User2") } - Mock Get-SPwebapplication { return @{ + + Mock -CommandName Get-SPwebapplication -MockWith { + return @{ IsAdministrationWebApplication = $true Url = "http://admin.shareopoint.contoso.local" - }} - Mock Get-SPWeb { + } + } + + Mock -CommandName Get-SPWeb -MockWith { return @{ AssociatedOwnerGroup = "Farm Administrators" - SiteGroups = New-Object Object | Add-Member ScriptMethod GetByName { - return New-Object Object | Add-Member ScriptProperty Users { - return @( - @{ UserLogin = "Demo\User1" }, - @{ UserLogin = "Demo\User2" } - ) - } -PassThru | Add-Member ScriptMethod AddUser { } -PassThru ` - | Add-Member ScriptMethod RemoveUser { } -PassThru - } -PassThru + SiteGroups = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name GetByName ` + -Value { + return New-Object "Object" | + Add-Member -MemberType ScriptProperty ` + -Name Users ` + -Value { + return @( + @{ + UserLogin = "Demo\User1" + }, + @{ + UserLogin = "Demo\User2" + } + ) + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name AddUser ` + -Value { } ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name RemoveUser ` + -Value { } ` + -PassThru + } -PassThru } } - It "should return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Central admin exists and a members to include is set where the members are not in the group" { + Context -Name "Central admin exists and a members to include is set where the members are not in the group" -Fixture { $testParams = @{ Name = "Farm Administrators" MembersToInclude = @("Demo\User2") } - Mock Get-SPwebapplication { return @{ + + Mock -CommandName Get-SPwebapplication -MockWith { + return @{ IsAdministrationWebApplication = $true Url = "http://admin.shareopoint.contoso.local" - }} - Mock Get-SPWeb { + } + } + + Mock -CommandName Get-SPWeb -MockWith { return @{ AssociatedOwnerGroup = "Farm Administrators" - SiteGroups = New-Object Object | Add-Member ScriptMethod GetByName { - return New-Object Object | Add-Member ScriptProperty Users { - return @( - @{ UserLogin = "Demo\User1" } - ) - } -PassThru | Add-Member ScriptMethod AddUser { } -PassThru ` - | Add-Member ScriptMethod RemoveUser { } -PassThru - } -PassThru + SiteGroups = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name GetByName ` + -Value { + return New-Object "Object" | + Add-Member -MemberType ScriptProperty ` + -Name Users ` + -Value { + return @( + @{ + UserLogin = "Demo\User1" + } + ) + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name AddUser ` + -Value { } ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name RemoveUser ` + -Value { } ` + -PassThru + } -PassThru } } - It "should return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should update the members list" { + It "Should update the members list" { Set-TargetResource @testParams } } - Context "Central admin exists and a members to exclude is set where the members are in the group" { + Context -Name "Central admin exists and a members to exclude is set where the members are in the group" -Fixture { $testParams = @{ Name = "Farm Administrators" MembersToExclude = @("Demo\User1") } - Mock Get-SPwebapplication { return @{ + + Mock -CommandName Get-SPwebapplication -MockWith { + return @{ IsAdministrationWebApplication = $true Url = "http://admin.shareopoint.contoso.local" - }} - Mock Get-SPWeb { + } + } + + Mock -CommandName Get-SPWeb -MockWith { return @{ AssociatedOwnerGroup = "Farm Administrators" - SiteGroups = New-Object Object | Add-Member ScriptMethod GetByName { - return New-Object Object | Add-Member ScriptProperty Users { - return @( - @{ UserLogin = "Demo\User1" }, - @{ UserLogin = "Demo\User2" } - ) - } -PassThru | Add-Member ScriptMethod AddUser { } -PassThru ` - | Add-Member ScriptMethod RemoveUser { } -PassThru - } -PassThru + SiteGroups = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name GetByName ` + -Value { + return New-Object "Object" | + Add-Member -MemberType ScriptProperty ` + -Name Users ` + -Value { + return @( + @{ + UserLogin = "Demo\User1" + }, + @{ + UserLogin = "Demo\User2" + } + ) + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name AddUser ` + -Value { } ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name RemoveUser ` + -Value { } ` + -PassThru + } -PassThru } } - It "should return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should update the members list" { + It "Should update the members list" { Set-TargetResource @testParams } } - Context "Central admin exists and a members to exclude is set where the members are not in the group" { + Context -Name "Central admin exists and a members to exclude is set where the members are not in the group" -Fixture { $testParams = @{ Name = "Farm Administrators" MembersToExclude = @("Demo\User1") } - Mock Get-SPwebapplication { return @{ + + Mock -CommandName Get-SPwebapplication -MockWith { return @{ IsAdministrationWebApplication = $true Url = "http://admin.shareopoint.contoso.local" }} - Mock Get-SPWeb { + Mock -CommandName Get-SPWeb -MockWith { return @{ AssociatedOwnerGroup = "Farm Administrators" - SiteGroups = New-Object Object | Add-Member ScriptMethod GetByName { - return New-Object Object | Add-Member ScriptProperty Users { - return @( - @{ UserLogin = "Demo\User2" } - ) - } -PassThru | Add-Member ScriptMethod AddUser { } -PassThru ` - | Add-Member ScriptMethod RemoveUser { } -PassThru - } -PassThru + SiteGroups = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name GetByName ` + -Value { + return New-Object "Object" | + Add-Member -MemberType ScriptProperty ` + -Name Users ` + -Value { + return @( + @{ + UserLogin = "Demo\User2" + } + ) + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name AddUser ` + -Value { } ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name RemoveUser ` + -Value { } ` + -PassThru + } -PassThru } } - It "should return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The resource is called with both an explicit members list as well as members to include/exclude" { + Context -Name "The resource is called with both an explicit members list as well as members to include/exclude" -Fixture { $testParams = @{ Name = "Farm Administrators" Members = @("Demo\User1") MembersToExclude = @("Demo\User1") } - Mock Get-SPwebapplication { return @{ + + Mock -CommandName Get-SPwebapplication -MockWith { + return @{ IsAdministrationWebApplication = $true Url = "http://admin.shareopoint.contoso.local" - }} - Mock Get-SPWeb { + } + } + + Mock -CommandName Get-SPWeb -MockWith { return @{ AssociatedOwnerGroup = "Farm Administrators" - SiteGroups = New-Object Object | Add-Member ScriptMethod GetByName { - return New-Object Object | Add-Member ScriptProperty Users { - return @( - @{ UserLogin = "Demo\User2" } - ) - } -PassThru | Add-Member ScriptMethod AddUser { } -PassThru ` - | Add-Member ScriptMethod RemoveUser { } -PassThru - } -PassThru + SiteGroups = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name GetByName ` + -Value { + return New-Object "Object" | + Add-Member -MemberType ScriptProperty ` + -Name Users ` + -Value { + return @( + @{ + UserLogin = "Demo\User2" + } + ) + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name AddUser ` + -Value { } ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name RemoveUser ` + -Value { } ` + -PassThru + } -PassThru } } - It "should throw in the get method" { + It "Should throw in the get method" { { Get-TargetResource @testParams } | Should throw } - It "should throw in the test method" { + It "Should throw in the test method" { { Test-TargetResource @testParams } | Should throw } - It "should throw in the set method" { + It "Should throw in the set method" { { Set-TargetResource @testParams } | Should throw } } - Context "The resource is called without either the specific members list or the include/exclude lists" { + Context -Name "The resource is called without either the specific members list or the include/exclude lists" -Fixture { $testParams = @{ Name = "Farm Administrators" } - Mock Get-SPwebapplication { return @{ + + Mock -CommandName Get-SPwebapplication -MockWith { + return @{ IsAdministrationWebApplication = $true Url = "http://admin.shareopoint.contoso.local" - }} - Mock Get-SPWeb { + } + } + + Mock -CommandName Get-SPWeb -MockWith { return @{ AssociatedOwnerGroup = "Farm Administrators" - SiteGroups = New-Object Object | Add-Member ScriptMethod GetByName { - return New-Object Object | Add-Member ScriptProperty Users { - return @( - @{ UserLogin = "Demo\User2" } - ) - } -PassThru | Add-Member ScriptMethod AddUser { } -PassThru ` - | Add-Member ScriptMethod RemoveUser { } -PassThru - } -PassThru + SiteGroups = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name GetByName ` + -Value { + return New-Object "Object" | + Add-Member -MemberType ScriptProperty ` + -Name Users ` + -Value { + return @( + @{ + UserLogin = "Demo\User2" + } + ) + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name AddUser ` + -Value { } ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name RemoveUser ` + -Value { } ` + -PassThru + } -PassThru } } - It "should throw in the get method" { + It "Should throw in the get method" { { Get-TargetResource @testParams } | Should throw } - It "should throw in the test method" { + It "Should throw in the test method" { { Test-TargetResource @testParams } | Should throw } - It "should throw in the set method" { + It "Should throw in the set method" { { Set-TargetResource @testParams } | Should throw } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPFarmSolution.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPFarmSolution.Tests.ps1 index 0bbe84c5a..912cd054a 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPFarmSolution.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPFarmSolution.Tests.ps1 @@ -1,68 +1,73 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPFarmSolution" -$ModuleName = "MSFT_SPFarmSolution" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPFarmSolution - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - - InModuleScope $ModuleName { - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") + # Initialize tests - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } + # Mocks for all contexts + Mock -CommandName Update-SPSolution -MockWith { } + Mock -CommandName Wait-SPDSCSolutionJob -MockWith { } + Mock -CommandName Install-SPFeature -MockWith { } + Mock -CommandName Install-SPSolution -MockWith { } + Mock -CommandName Uninstall-SPSolution -MockWith { } + Mock -CommandName Remove-SPSolution -MockWith { } - $testParams = @{ - Name = "SomeSolution" - LiteralPath = "\\server\share\file.wsp" - Deployed = $true - Ensure = "Present" - Version = "1.0.0.0" - WebApplications = @("http://app1", "http://app2") - Verbose = $true - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue + # Test contexts + Context -Name "The solution isn't installed, but should be" -Fixture { + $testParams = @{ + Name = "SomeSolution" + LiteralPath = "\\server\share\file.wsp" + Deployed = $true + Ensure = "Present" + Version = "1.0.0.0" + WebApplications = @("http://app1", "http://app2") + } - Context "The solution isn't installed, but should be" { + $global:SPDscSolutionAdded = $false - $global:SolutionAdded = $false - Mock Get-SPSolution { - if ($global:SolutionAdded) { + Mock -CommandName Get-SPSolution -MockWith { + if ($global:SPDscSolutionAdded) + { return [pscustomobject] @{ } - }else{ + } + else + { return $null } - } -Verifiable - Mock Add-SPSolution { + } + + Mock -CommandName Add-SPSolution -MockWith { $solution = [pscustomobject] @{ Properties = @{ Version = "" }} - $solution | Add-Member -Name Update -MemberType ScriptMethod -Value { } - $global:SolutionAdded = $true + $solution | Add-Member -Name Update -MemberType ScriptMethod -Value { } + $global:SPDscSolutionAdded = $true return $solution - } -Verifiable - Mock Install-SPSolution { } -Verifiable - Mock Wait-SPDSCSolutionJob { } -Verifiable + } $getResults = Get-TargetResource @testParams - It "returns the expected empty values from the get method" { + It "Should return the expected empty values from the get method" { $getResults.Ensure | Should Be "Absent" $getResults.Version | Should Be "0.0.0.0" $getResults.Deployed | Should Be $false } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } @@ -75,33 +80,34 @@ Describe "SPFarmSolution - SharePoint Build $((Get-Item $SharePointCmdletModule) } } - Context "The solution is installed, but should not be"{ - - $testParams.Ensure = "Absent" + Context -Name "The solution is installed, but should not be" -Fixture { + $testParams = @{ + Name = "SomeSolution" + LiteralPath = "\\server\share\file.wsp" + Deployed = $true + Ensure = "Absent" + Version = "1.0.0.0" + WebApplications = @("http://app1", "http://app2") + } - Mock Get-SPSolution { + Mock -CommandName Get-SPSolution -MockWith { return [pscustomobject]@{ Deployed = $true Properties = @{ Version = "1.0.0.0" } DeployedWebApplications = @( [pscustomobject]@{Url="http://app1"}, [pscustomobject]@{Url="http://app2"}) ContainsGlobalAssembly = $true } - } -Verifiable - - Mock Uninstall-SPSolution { } -Verifiable - Mock Wait-SPDSCSolutionJob { } -Verifiable - Mock Remove-SPSolution { } -Verifiable - + } $getResults = Get-TargetResource @testParams - It "returns the expected values from the get method" { + It "Should return the expected values from the get method" { $getResults.Ensure | Should Be "Present" $getResults.Version | Should Be "1.0.0.0" $getResults.Deployed | Should Be $true } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } @@ -114,8 +120,7 @@ Describe "SPFarmSolution - SharePoint Build $((Get-Item $SharePointCmdletModule) } } - Context "The solution isn't installed, and should not be"{ - + Context -Name "The solution isn't installed, and should not be" -Fixture { $testParams = @{ Name = "SomeSolution" LiteralPath = "\\server\share\file.wsp" @@ -125,56 +130,55 @@ Describe "SPFarmSolution - SharePoint Build $((Get-Item $SharePointCmdletModule) WebApplications = @() } - Mock Get-SPSolution { $null } -Verifiable + Mock -CommandName Get-SPSolution -MockWith { $null } $getResults = Get-TargetResource @testParams - It "returns the expected empty values from the get method" { + It "Should return the expected empty values from the get method" { $getResults.Ensure | Should Be "Absent" $getResults.Version | Should Be "0.0.0.0" $getResults.Deployed | Should Be $false } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The solution is installed, but needs update"{ - - $testParams.Version = "1.1.0.0" - $testParams.Ensure = "Present" + Context -Name "The solution is installed, but needs update" -Fixture { + $testParams = @{ + Name = "SomeSolution" + LiteralPath = "\\server\share\file.wsp" + Deployed = $true + Ensure = "Present" + Version = "1.1.0.0" + WebApplications = @("http://app1", "http://app2") + } - Mock Get-SPSolution { + Mock -CommandName Get-SPSolution -MockWith { $s = [pscustomobject]@{ Deployed = $true Properties = @{ Version = "1.0.0.0" } DeployedWebApplications = @( [pscustomobject]@{Url="http://app1"}, [pscustomobject]@{Url="http://app2"}) ContainsGlobalAssembly = $true } - $s | Add-Member -Name Update -MemberType ScriptMethod -Value { } + $s | Add-Member -Name Update -MemberType ScriptMethod -Value { } return $s } $getResults = Get-TargetResource @testParams - Mock Update-SPSolution { } -Verifiable - Mock Wait-SPDSCSolutionJob { } -Verifiable - Mock Install-SPFeature { } -Verifiable - - $getResults = Get-TargetResource @testParams - - It "returns the expected values from the get method" { + It "Should return the expected values from the get method" { $getResults.Ensure | Should Be "Present" $getResults.Version | Should Be "1.0.0.0" $getResults.Deployed | Should Be $true } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "updates the solution in the set method" { + It "Should update the solution in the set method" { Set-TargetResource @testParams Assert-MockCalled Update-SPSolution @@ -183,12 +187,17 @@ Describe "SPFarmSolution - SharePoint Build $((Get-Item $SharePointCmdletModule) } } - Context "The solution is installed, and should be"{ - - $testParams.Version = "1.0.0.0" - $testParams.Ensure = "Present" - - Mock Get-SPSolution { + Context -Name "The solution is installed, and should be" -Fixture { + $testParams = @{ + Name = "SomeSolution" + LiteralPath = "\\server\share\file.wsp" + Deployed = $true + Ensure = "Present" + Version = "1.0.0.0" + WebApplications = @("http://app1", "http://app2") + } + + Mock -CommandName Get-SPSolution -MockWith { return [pscustomobject]@{ Deployed = $true Properties = @{ Version = "1.0.0.0" } @@ -199,21 +208,26 @@ Describe "SPFarmSolution - SharePoint Build $((Get-Item $SharePointCmdletModule) $getResults = Get-TargetResource @testParams - It "returns the expected values from the get method" { + It "Should return the expected values from the get method" { $getResults.Ensure | Should Be "Present" $getResults.Version | Should Be "1.0.0.0" $getResults.Deployed | Should Be $true } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The solution exists but is not deloyed, and needs update"{ - - $testParams.Version = "1.1.0.0" - $testParams.Ensure = "Present" + Context -Name "The solution exists but is not deloyed, and needs update" -Fixture { + $testParams = @{ + Name = "SomeSolution" + LiteralPath = "\\server\share\file.wsp" + Deployed = $true + Ensure = "Present" + Version = "1.1.0.0" + WebApplications = @() + } $solution = [pscustomobject]@{ Deployed = $false @@ -223,29 +237,22 @@ Describe "SPFarmSolution - SharePoint Build $((Get-Item $SharePointCmdletModule) } $solution | Add-Member -Name Update -MemberType ScriptMethod -Value { } - Mock Get-SPSolution { $solution } - - $getResults = Get-TargetResource @testParams - - Mock Remove-SPSolution { } -Verifiable - Mock Add-SPSolution { $solution } -Verifiable - - Mock Install-SPSolution { } -Verifiable - Mock Wait-SPDSCSolutionJob { } -Verifiable + Mock -CommandName Get-SPSolution -MockWith { $solution } + Mock -CommandName Add-SPSolution -MockWith { $solution } $getResults = Get-TargetResource @testParams - It "returns the expected values from the get method" { + It "Should return the expected values from the get method" { $getResults.Ensure | Should Be "Present" $getResults.Version | Should Be "1.0.0.0" $getResults.Deployed | Should Be $false } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "updates the solution in the set method" { + It "Should update the solution in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPSolution @@ -255,10 +262,16 @@ Describe "SPFarmSolution - SharePoint Build $((Get-Item $SharePointCmdletModule) } } - Context "A solution deployment can target a specific compatability level" { - $testParams.Version = "1.0.0.0" - $testParams.Ensure = "Present" - $testParams.Add("SolutionLevel", "All") + Context -Name "A solution deployment can target a specific compatability level" -Fixture { + $testParams = @{ + Name = "SomeSolution" + LiteralPath = "\\server\share\file.wsp" + Deployed = $true + Ensure = "Present" + Version = "1.1.0.0" + WebApplications = @() + SolutionLevel = "All" + } $solution = [pscustomobject]@{ Deployed = $false @@ -268,13 +281,8 @@ Describe "SPFarmSolution - SharePoint Build $((Get-Item $SharePointCmdletModule) } $solution | Add-Member -Name Update -MemberType ScriptMethod -Value { } - Mock Get-SPSolution { $solution } - - Mock Remove-SPSolution { } - Mock Add-SPSolution { $solution } - - Mock Install-SPSolution { } - Mock Wait-SPDSCSolutionJob { } + Mock -CommandName Get-SPSolution -MockWith { $solution } + Mock -CommandName Add-SPSolution -MockWith { $solution } It "deploys the solution using the correct compatability level" { Set-TargetResource @testParams @@ -282,5 +290,7 @@ Describe "SPFarmSolution - SharePoint Build $((Get-Item $SharePointCmdletModule) Assert-MockCalled Install-SPSolution -ParameterFilter { $CompatibilityLevel -eq $testParams.SolutionLevel } } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPFeature.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPFeature.Tests.ps1 index 7f2f01a06..90d451512 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPFeature.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPFeature.Tests.ps1 @@ -1,171 +1,209 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPFeature" -$ModuleName = "MSFT_SPFeature" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPFeature - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "DemoFeature" - FeatureScope = "Farm" - Url = "http://site.sharepoint.com" - Ensure = "Present" - } - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Mock Enable-SPFeature {} - Mock Disable-SPFeature {} + # Mocks for all contexts + Mock -CommandName Enable-SPFeature -MockWith {} + Mock -CommandName Disable-SPFeature -MockWith {} + + # Test contexts + Context -Name "A feature that is not installed in the farm should be turned on" -Fixture { + $testParams = @{ + Name = "DemoFeature" + FeatureScope = "Farm" + Url = "http://site.sharepoint.com" + Ensure = "Present" + } - Context "A feature that is not installed in the farm should be turned on" { - Mock Get-SPFeature { return $null } + Mock -CommandName Get-SPFeature -MockWith { return $null } - It "returns null from the get method" { + It "Should return null from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "A farm scoped feature is not enabled and should be" { - Mock Get-SPFeature { return $null } - $testParams.FeatureScope = "Farm" + Context -Name "A farm scoped feature is not enabled and should be" -Fixture { + $testParams = @{ + Name = "DemoFeature" + FeatureScope = "Farm" + Url = "http://site.sharepoint.com" + Ensure = "Present" + } + + Mock -CommandName Get-SPFeature -MockWith { + return $null + } - It "returns null from the get method" { + It "Should return null from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "enables the feature in the set method" { + It "Should enable the feature in the set method" { Set-TargetResource @testParams Assert-MockCalled Enable-SPFeature } } - Context "A site collection scoped feature is not enabled and should be" { - Mock Get-SPFeature { return $null } - $testParams.FeatureScope = "Site" + Context -Name "A site collection scoped feature is not enabled and should be" -Fixture { + $testParams = @{ + Name = "DemoFeature" + FeatureScope = "Site" + Url = "http://site.sharepoint.com" + Ensure = "Present" + } + + Mock -CommandName Get-SPFeature -MockWith { + return $null + } - It "returns null from the get method" { + It "Should return null from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "enables the feature in the set method" { + It "Should enable the feature in the set method" { Set-TargetResource @testParams Assert-MockCalled Enable-SPFeature } } - Context "A farm scoped feature is enabled and should not be" { - Mock Get-SPFeature { return @{} } - - $testParams.FeatureScope = "Farm" - $testParams.Ensure = "Absent" + Context -Name "A farm scoped feature is enabled and should not be" -Fixture { + $testParams = @{ + Name = "DemoFeature" + FeatureScope = "Farm" + Url = "http://site.sharepoint.com" + Ensure = "Absent" + } + + Mock -CommandName Get-SPFeature -MockWith { + return @{} + } - It "returns null from the get method" { + It "Should return null from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "enables the feature in the set method" { + It "Should enable the feature in the set method" { Set-TargetResource @testParams - Assert-MockCalled Disable-SPFeature } } - Context "A site collection scoped feature is enabled and should not be" { - Mock Get-SPFeature { return @{} } - - $testParams.FeatureScope = "Site" + Context -Name "A site collection scoped feature is enabled and should not be" -Fixture { + $testParams = @{ + Name = "DemoFeature" + FeatureScope = "Site" + Url = "http://site.sharepoint.com" + Ensure = "Absent" + } + + Mock -CommandName Get-SPFeature -MockWith { + return @{} + } - It "returns null from the get method" { + It "Should return null from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "enables the feature in the set method" { + It "Should enable the feature in the set method" { Set-TargetResource @testParams - Assert-MockCalled Disable-SPFeature } } - Context "A farm scoped feature is enabled and should be" { - Mock Get-SPFeature { return @{} } - - $testParams.FeatureScope = "Farm" - $testParams.Ensure = "Present" + Context -Name "A farm scoped feature is enabled and should be" -Fixture { + $testParams = @{ + Name = "DemoFeature" + FeatureScope = "Farm" + Url = "http://site.sharepoint.com" + Ensure = "Present" + } + + Mock -CommandName Get-SPFeature -MockWith { return @{} } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "A site collection scoped feature is enabled and should be" { - Mock Get-SPFeature { return @{} } - - $testParams.FeatureScope = "Site" + Context -Name "A site collection scoped feature is enabled and should be" -Fixture { + $testParams = @{ + Name = "DemoFeature" + FeatureScope = "Site" + Url = "http://site.sharepoint.com" + Ensure = "Present" + } + + Mock -CommandName Get-SPFeature -MockWith { return @{} } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "A site collection scoped features is enabled but has the wrong version" { - - Mock Get-SPFeature { return @{ Version = "1.0.0.0" } } - Mock Disable-SPFeature { } -Verifiable - - $testParams.FeatureScope = "Site" - $testParams.Version = "1.1.0.0" - - It "returns the version from the get method" { + Context -Name "A site collection scoped features is enabled but has the wrong version" -Fixture { + $testParams = @{ + Name = "DemoFeature" + FeatureScope = "Site" + Url = "http://site.sharepoint.com" + Version = "1.1.0.0" + Ensure = "Present" + } + + Mock -CommandName Get-SPFeature -MockWith { return @{ Version = "1.0.0.0" } } + + It "Should return the version from the get method" { (Get-TargetResource @testParams).Version | Should Be "1.0.0.0" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } It "reactivates the feature in the set method" { Set-TargetResource @testParams - - Assert-MockCalled Disable-SPFeature -Times 1 - Assert-MockCalled Enable-SPFeature -Times 1 + Assert-MockCalled Disable-SPFeature + Assert-MockCalled Enable-SPFeature } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPHealthAnalyzerRuleState.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPHealthAnalyzerRuleState.Tests.ps1 index 893ce3fac..4f9d60f7a 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPHealthAnalyzerRuleState.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPHealthAnalyzerRuleState.Tests.ps1 @@ -1,136 +1,181 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPHealthAnalyzerRuleState" -$ModuleName = "MSFT_SPHealthAnalyzerRuleState" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPHealthAnalyzerRuleState - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Drives are at risk of running out of free space." - Enabled = $true - RuleScope = "All Servers" - Schedule = "Daily" - FixAutomatically = $false + # Initialize tests + Add-Type -TypeDefinition "namespace Microsoft.SharePoint { public class SPQuery { public string Query { get; set; } } }" + + # Mocks for all contexts + Mock -CommandName Get-SPFarm -MockWith { + return @{} } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + + Mock -CommandName Get-SPWebapplication -MockWith { + return @{ + Url = "" + IsAdministrationWebApplication=$true + } } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Add-Type -TypeDefinition "namespace Microsoft.SharePoint { public class SPQuery { public string Query { get; set; } } }" + # Test contexts + Context -Name "The server is not part of SharePoint farm" -Fixture { + $testParams = @{ + Name = "Drives are at risk of running out of free space." + Enabled = $true + RuleScope = "All Servers" + Schedule = "Daily" + FixAutomatically = $false + } - Context "The server is not part of SharePoint farm" { - Mock Get-SPFarm { throw "Unable to detect local farm" } + Mock -CommandName Get-SPFarm -MockWith { throw "Unable to detect local farm" } - It "return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Be $null } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws an exception in the set method to say there is no local farm" { + It "Should throw an exception in the set method to say there is no local farm" { { Set-TargetResource @testParams } | Should throw "No local SharePoint farm was detected" } } - Context "The server is in a farm, but no central admin site is found" { - Mock Get-SPwebapplication { return $null } + Context -Name "The server is in a farm, but no central admin site is found" -Fixture { + $testParams = @{ + Name = "Drives are at risk of running out of free space." + Enabled = $true + RuleScope = "All Servers" + Schedule = "Daily" + FixAutomatically = $false + } + + Mock -CommandName Get-SPWebapplication -MockWith { + return $null + } - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "No Central Admin web application was found. Health Analyzer Rule settings will not be applied" } } - Context "The server is in a farm, CA found, but no health analyzer rules list is found" { - Mock Get-SPwebapplication { return @{ Url = "";IsAdministrationWebApplication=$true } } - Mock Get-SPWeb { return @{ Lists = $null } } + Context -Name "The server is in a farm, CA found, but no health analyzer rules list is found" -Fixture { + $testParams = @{ + Name = "Drives are at risk of running out of free space." + Enabled = $true + RuleScope = "All Servers" + Schedule = "Daily" + FixAutomatically = $false + } + + Mock -CommandName Get-SPWeb -MockWith { + return @{ + Lists = $null + } + } - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "Could not find Health Analyzer Rules list. Health Analyzer Rule settings will not be applied" } } + Context -Name "The server is in a farm, CA found, Health Rules list found, but no rules match the specified rule name" -Fixture { + $testParams = @{ + Name = "Drives are at risk of running out of free space." + Enabled = $true + RuleScope = "All Servers" + Schedule = "Daily" + FixAutomatically = $false + } - Context "The server is in a farm, CA found, Health Rules list found, but no rules match the specified rule name" { - Mock Get-SPwebapplication { return @{ Url = "";IsAdministrationWebApplication=$true } } - Mock Get-SPWeb { + Mock -CommandName Get-SPWeb -MockWith { $web = @{ Lists = @{ BaseTemplate = "HealthRules" - } | Add-Member ScriptMethod GetItems { + } | Add-Member -MemberType ScriptMethod -Name GetItems -Value { return ,@() } -PassThru } return $web } - Mock Get-SPFarm { return @{} } + Mock -CommandName Get-SPFarm -MockWith { return @{} } - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "Could not find specified Health Analyzer Rule. Health Analyzer Rule settings will not be applied" } } - Context "The server is in a farm, CA/Health Rules list/Health Rule found, but the incorrect settings have been applied" { - Mock Get-SPwebapplication { return @{ Url = "";IsAdministrationWebApplication=$true } } - Mock Get-SPWeb { + Context -Name "The server is in a farm, CA/Health Rules list/Health Rule found, but the incorrect settings have been applied" -Fixture { + $testParams = @{ + Name = "Drives are at risk of running out of free space." + Enabled = $true + RuleScope = "All Servers" + Schedule = "Daily" + FixAutomatically = $false + } + + Mock -CommandName Get-SPWeb -MockWith { $web = @{ Lists = @{ BaseTemplate = "HealthRules" - } | Add-Member ScriptMethod GetItems { + } | Add-Member -MemberType ScriptMethod -Name GetItems -Value { $itemcol = @(@{ HealthRuleCheckEnabled = $false; HealthRuleScope = "Any Server"; HealthRuleSchedule = "Weekly"; HealthRuleAutoRepairEnabled = $true - } | Add-Member ScriptMethod Update { $Global:SPDSCHealthRulesUpdated = $true } -PassThru ) + } | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscHealthRulesUpdated = $true + } -PassThru ) return ,$itemcol } -PassThru } return $web } - Mock Get-SPFarm { return @{} } - - It "return values from the get method" { + + It "Should return values from the get method" { $result = Get-TargetResource @testParams $result.Enabled | Should Be $false $result.RuleScope | Should Be 'Any Server' @@ -138,38 +183,46 @@ Describe "SPHealthAnalyzerRuleState - SharePoint Build $((Get-Item $SharePointCm $result.FixAutomatically | Should Be $true } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPDSCHealthRulesUpdated = $false + $Global:SPDscHealthRulesUpdated = $false It "set the configured values for the specific Health Analyzer Rule" { Set-TargetResource @testParams - $Global:SPDSCHealthRulesUpdated | Should Be $true + $Global:SPDscHealthRulesUpdated | Should Be $true } } - Context "The server is in a farm and the correct settings have been applied" { - Mock Get-SPwebapplication { return @{ Url = "";IsAdministrationWebApplication=$true } } - Mock Get-SPWeb { + Context -Name "The server is in a farm and the correct settings have been applied" -Fixture { + $testParams = @{ + Name = "Drives are at risk of running out of free space." + Enabled = $true + RuleScope = "All Servers" + Schedule = "Daily" + FixAutomatically = $false + } + + Mock -CommandName Get-SPWeb -MockWith { $web = @{ Lists = @{ BaseTemplate = "HealthRules" - } | Add-Member ScriptMethod GetItems { + } | Add-Member -MemberType ScriptMethod -Name GetItems -Value { $itemcol = @(@{ HealthRuleCheckEnabled = $true; HealthRuleScope = "All Servers"; HealthRuleSchedule = "Daily"; HealthRuleAutoRepairEnabled = $false - } | Add-Member ScriptMethod Update { $Global:SPDSCHealthRulesUpdated = $true } -PassThru ) + } | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscHealthRulesUpdated = $true + } -PassThru ) return ,$itemcol } -PassThru } return $web } - Mock Get-SPFarm { return @{} } - It "return values from the get method" { + It "Should return values from the get method" { $result = Get-TargetResource @testParams $result.Enabled | Should Be $true $result.RuleScope | Should Be 'All Servers' @@ -177,10 +230,12 @@ Describe "SPHealthAnalyzerRuleState - SharePoint Build $((Get-Item $SharePointCm $result.FixAutomatically | Should Be $false } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPInstall.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPInstall.Tests.ps1 index 7d2f970e1..4193188b5 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPInstall.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPInstall.Tests.ps1 @@ -1,21 +1,25 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPInstall" -$ModuleName = "MSFT_SPInstall" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPInstall - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - - function New-SPDscMockPrereq() + # Initialize tests + function New-SPDscMockPrereq { param ( @@ -24,73 +28,105 @@ Describe "SPInstall - SharePoint Build $((Get-Item $SharePointCmdletModule).Dire $Name ) $object = New-Object -TypeName System.Object - $object = $object | Add-Member -type NoteProperty -Name "DisplayName" -Value $Name -PassThru + $object = $object | Add-Member -Type NoteProperty ` + -Name "DisplayName" ` + -Value $Name ` + -PassThru return $object } - - $testParams = @{ - BinaryDir = "C:\SPInstall" - ProductKey = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - $versionBeingTested = (Get-Item $Global:CurrentSharePointStubModule).Directory.BaseName - $majorBuildNumber = $versionBeingTested.Substring(0, $versionBeingTested.IndexOf(".")) - Mock Get-SPDSCAssemblyVersion { return $majorBuildNumber } - - Mock Get-ChildItem { - return @( - @{ + # Mocks for all contexts + Mock -CommandName Get-ChildItem -MockWith { + $full = @{ Version = "4.5.0.0" Release = "0" PSChildName = "Full" - }, - @{ + } + + $client = @{ Version = "4.5.0.0" Release = "0" PSChildName = "Client" - } - ) + } + + $returnval = @($full, $client) + $returnVal = $returnVal | Add-Member ScriptMethod GetValue { return 380000 } -PassThru + return $returnval } - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + + Mock -CommandName Get-SPDSCAssemblyVersion -MockWith { + return $Global:SPDscHelper.CurrentStubBuildNumber.Major } - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Context "SharePoint binaries are not installed but should be" { - Mock Get-ItemProperty { return $null } + # Test contexts + Context -Name "SharePoint binaries are not installed but should be" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + ProductKey = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" + Ensure = "Present" + } - It "returns absent from the get method" { + Mock -CommandName Get-ItemProperty -MockWith { + return $null + } + + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "SharePoint binaries are installed and should be" { - Mock Get-ItemProperty { return @( - (New-SPDscMockPrereq -Name "Microsoft SharePoint Server 2013"), - (New-SPDscMockPrereq -Name "Something else") - ) } + Context -Name "SharePoint binaries are installed and should be" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + ProductKey = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" + Ensure = "Present" + } + + Mock -CommandName Get-ItemProperty -MockWith { + return @( + (New-SPDscMockPrereq -Name "Microsoft SharePoint Server 2013"), + (New-SPDscMockPrereq -Name "Something else") + ) + } -ParameterFilter { $null -ne $Path } + + Mock -CommandName Get-ItemProperty -MockWith { + return @{ + VersionInfo = @{ + FileVersion = "15.0.4709.1000" + } + } + } + + Mock -CommandName Test-Path -MockWith { + return $true + } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "SharePoint installation executes as expected" { - Mock Start-Process { @{ ExitCode = 0 }} + Context -Name "SharePoint installation executes as expected" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + ProductKey = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" + Ensure = "Present" + } + + Mock -CommandName Start-Process -MockWith { + return @{ + ExitCode = 0 + } + } It "reboots the server after a successful installation" { Set-TargetResource @testParams @@ -98,74 +134,107 @@ Describe "SPInstall - SharePoint Build $((Get-Item $SharePointCmdletModule).Dire } } - Context "SharePoint installation fails" { - Mock Start-Process { @{ ExitCode = -1 }} + Context -Name "SharePoint installation fails" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + ProductKey = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" + Ensure = "Present" + } + + Mock -CommandName Start-Process -MockWith { + return @{ + ExitCode = -1 + } + } - It "throws an exception on an unknown exit code" { + It "Should throw an exception on an unknown exit code" { { Set-TargetResource @testParams } | Should Throw } } - $testParams.Ensure = "Absent" - - Context "SharePoint binaries are installed and should not be" { - Mock Get-ItemProperty { return @{} } + Context -Name "SharePoint binaries are installed and should not be" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + ProductKey = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" + Ensure = "Absent" + } + + Mock -CommandName Get-ItemProperty -MockWith { return @{} } -ParameterFilter { $null -ne $Path } - It "throws in the test method because uninstall is unsupported" { + It "Should throw in the test method because uninstall is unsupported" { { Test-TargetResource @testParams } | Should Throw } - It "throws in the set method because uninstall is unsupported" { + It "Should throw in the set method because uninstall is unsupported" { { Set-TargetResource @testParams } | Should Throw } } - Context "SharePoint 2013 is installing on a server with .NET 4.6" { - Mock Get-ChildItem { - return @( - @{ - Version = "4.6.0.0" - Release = "0" - PSChildName = "Full" - }, - @{ - Version = "4.6.0.0" - Release = "0" - PSChildName = "Client" - } - ) + Context -Name "SharePoint 2013 is installing on a server with .NET 4.6" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + ProductKey = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" + Ensure = "Present" + } + + Mock -CommandName Get-ChildItem -MockWith { + $full = @{ + Version = "4.6.0.0" + Release = "0" + PSChildName = "Full" + } + + $client = @{ + Version = "4.6.0.0" + Release = "0" + PSChildName = "Client" + } + + $returnval = @($full, $client) + $returnVal = $returnVal | Add-Member ScriptMethod GetValue { return 391000 } -PassThru + return $returnval } - It "throws an error in the set method" { + It "Should throw an error in the set method" { { Set-TargetResource @testParams } | Should Throw } } - - $testParams = @{ - BinaryDir = "C:\SPInstall" - ProductKey = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" - Ensure = "Present" - InstallPath = "C:\somewhere" - DataPath = "C:\somewhere\else" - } - Context "SharePoint is not installed and should be, using custom install directories" { - Mock Get-ItemProperty { return $null } + Context -Name "SharePoint is not installed and should be, using custom install directories" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + ProductKey = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" + Ensure = "Present" + InstallPath = "C:\somewhere" + DataPath = "C:\somewhere\else" + } + + Mock -CommandName Get-ItemProperty -MockWith { + return $null + } -ParameterFilter { + $null -ne $Path + } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - Mock Start-Process { @{ ExitCode = 0 }} + Mock -CommandName Start-Process { + return @{ + ExitCode = 0 + } + } It "reboots the server after a successful installation" { Set-TargetResource @testParams $global:DSCMachineStatus | Should Be 1 } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPInstallLanguagePack.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPInstallLanguagePack.Tests.ps1 index b05c93ca3..cdcb90a18 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPInstallLanguagePack.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPInstallLanguagePack.Tests.ps1 @@ -1,80 +1,95 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPInstallLanguagePack" -$ModuleName = "MSFT_SPInstallLanguagePack" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\Modules\SharePointDsc.Util\SharePointDsc.Util.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - BinaryDir = "C:\SPInstall" - Ensure = "Present" + # Initialize tests + + # Mocks for all contexts + Mock -CommandName Test-Path -MockWith { + return $true + } + + Mock -CommandName Get-ChildItem -MockWith { + return @{ + Name = "C:\SPInstall\osrv.nl-nl" + } + } + + Mock -CommandName Get-SPDSCRegistryKey -MockWith { + if ($Value -eq "SetupType") + { + return "CLEAN_INSTALL" + } + + if ($Value -eq "LanguagePackInstalled") + { + return 0 + } } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - $versionBeingTested = (Get-Item $Global:CurrentSharePointStubModule).Directory.BaseName - $majorBuildNumber = $versionBeingTested.Substring(0, $versionBeingTested.IndexOf(".")) - Mock Get-SPDSCAssemblyVersion { return $majorBuildNumber } - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + + Mock -CommandName Start-Process -MockWith { + return @{ + ExitCode = 0 + } } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Context "Specified update file not found" { - Mock Test-Path { return $false } - - It "should throw exception in the get method" { + + # Test contexts + Context -Name "Specified update file not found" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + Ensure = "Present" + } + + Mock -CommandName Test-Path { + return $false + } + + It "Should throw exception in the get method" { { Get-TargetResource @testParams } | Should Throw "Specified path cannot be found" } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should Throw "Specified path cannot be found" } - It "should throw exception in the test method" { + It "Should throw exception in the test method" { { Test-TargetResource @testParams } | Should Throw "Specified path cannot be found" } } - Context "Language Pack is installed, installation not required" { - Mock Test-Path { + Context -Name "Language Pack is installed, installation not required" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + Ensure = "Present" + } + + Mock -CommandName Test-Path -MockWith { return $true } - - Mock Get-ChildItem { + + Mock -CommandName Get-ChildItem -MockWith { return @{ Name = "C:\SPInstall\osrv.nl-nl" } } - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "CLEAN_INSTALL" @@ -86,54 +101,53 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet } } - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) - { - return @("Microsoft SharePoint Server 2013", "Language Pack for SharePoint and Project Server 2013 - Dutch/Nederlands") - } - else + Mock -CommandName Get-SPDscRegProductsInfo -MockWith { + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) { - return @("Microsoft SharePoint Server 2016", "Language Pack for SharePoint and Project Server 2016 - Dutch/Nederlands") + 15 { + return @("Microsoft SharePoint Server 2013", "Language Pack for SharePoint and Project Server 2013 - Dutch/Nederlands") + } + 16 { + return @("Microsoft SharePoint Server 2016", "Language Pack for SharePoint and Project Server 2016 - Dutch/Nederlands") + } + Default { + throw [Exception] "A supported version of SharePoint was not used in testing" + } } } - It "should return Ensure is Present from the get method" { + It "Should return Ensure is Present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Present" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Language Pack is not installed, installation executed successfully" { - Mock Test-Path { - return $true - } - - Mock Get-ChildItem { - return @{ - Name = "C:\SPInstall\osrv.nl-nl" - } + Context -Name "Language Pack is not installed, installation executed successfully" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + Ensure = "Present" } - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) { - return @{ - FileMajorPart = 15 + 15 { + return @("Microsoft SharePoint Server 2013") } - } - else - { - return @{ - FileMajorPart = 16 + 16 { + return @("Microsoft SharePoint Server 2016") + } + Default { + throw [Exception] "A supported version of SharePoint was not used in testing" } } } - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "CLEAN_INSTALL" @@ -145,8 +159,8 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet } } - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscRegProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013") } @@ -156,54 +170,49 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet } } - Mock Start-Process { + Mock -CommandName Start-Process -MockWith { return @{ ExitCode = 0 } } - It "should return Ensure is Present from the get method" { + It "Should return Ensure is Present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should run the Start-Process function in the set method" { + It "Should run the Start-Process function in the set method" { Set-TargetResource @testParams Assert-MockCalled Start-Process } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "Language Pack is not installed, installation executed, reboot required" { - Mock Test-Path { - return $true + Context -Name "Language Pack is not installed, installation executed, reboot required" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + Ensure = "Present" } - Mock Get-ChildItem { - return @{ - Name = "C:\SPInstall\osrv.nl-nl" - } - } - - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) { - return @{ - FileMajorPart = 15 + 15 { + return @("Microsoft SharePoint Server 2013") } - } - else - { - return @{ - FileMajorPart = 16 + 16 { + return @("Microsoft SharePoint Server 2016") + } + Default { + throw [Exception] "A supported version of SharePoint was not used in testing" } } } - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "CLEAN_INSTALL" @@ -215,8 +224,8 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet } } - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscRegProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013") } @@ -226,54 +235,49 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet } } - Mock Start-Process { + Mock -CommandName Start-Process -MockWith { return @{ ExitCode = 17022 } } - It "should return Ensure is Present from the get method" { + It "Should return Ensure is Present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should run the Start-Process function in the set method" { + It "Should run the Start-Process function in the set method" { Set-TargetResource @testParams Assert-MockCalled Start-Process } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "Language Pack is not installed, installation executed, which failed" { - Mock Test-Path { - return $true - } - - Mock Get-ChildItem { - return @{ - Name = "C:\SPInstall\osrv.nl-nl" - } + Context -Name "Language Pack is not installed, installation executed, which failed" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + Ensure = "Present" } - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) { - return @{ - FileMajorPart = 15 + 15 { + return @("Microsoft SharePoint Server 2013") } - } - else - { - return @{ - FileMajorPart = 16 + 16 { + return @("Microsoft SharePoint Server 2016") + } + Default { + throw [Exception] "A supported version of SharePoint was not used in testing" } } } - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "CLEAN_INSTALL" @@ -285,8 +289,8 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet } } - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscRegProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013") } @@ -296,54 +300,55 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet } } - Mock Start-Process { + Mock -CommandName Start-Process -MockWith { return @{ ExitCode = 1 } } - It "should return Ensure is Present from the get method" { + It "Should return Ensure is Present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should run the Start-Process function in the set method" { + It "Should run the Start-Process function in the set method" { { Set-TargetResource @testParams } | Should Throw "SharePoint Language Pack install failed, exit code was 1" Assert-MockCalled Start-Process } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "Language Pack does not have language in the name, throws exception" { - Mock Test-Path { - return $true + Context -Name "Language Pack does not have language in the name, throws exception" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + Ensure = "Present" } - - Mock Get-ChildItem { + + Mock -CommandName Get-ChildItem { return @{ Name = "C:\SPInstall\osrv" } } - - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) + + Mock -CommandName Get-SPDscFarmProductsInfo { + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) { - return @{ - FileMajorPart = 15 + 15 { + return @("Microsoft SharePoint Server 2013", "Language Pack for SharePoint and Project Server 2013 - Dutch/Nederlands") } - } - else - { - return @{ - FileMajorPart = 16 + 16 { + return @("Microsoft SharePoint Server 2016", "Language Pack for SharePoint and Project Server 2016 - Dutch/Nederlands") + } + Default { + throw [Exception] "A supported version of SharePoint was not used in testing" } } } - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "CLEAN_INSTALL" @@ -355,8 +360,8 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet } } - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscRegProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013", "Language Pack for SharePoint and Project Server 2013 - Dutch/Nederlands") } @@ -366,38 +371,39 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet } } - It "should throw exception in the get method" { + It "Should throw exception in the get method" { { Get-TargetResource @testParams } | Should Throw "Update does not contain the language code in the correct format." } } - Context "Language Pack has unknown language in the name, throws exception" { - Mock Test-Path { - return $true + Context -Name "Language Pack has unknown language in the name, throws exception" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + Ensure = "Present" } - - Mock Get-ChildItem { + + Mock -CommandName Get-ChildItem -MockWith { return @{ - Name = "C:\SPInstall\osrv.ab-cd" + Name = "C:\SPInstall\osrv.xx-xx" } } - - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) + + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) { - return @{ - FileMajorPart = 15 + 15 { + return @("Microsoft SharePoint Server 2013", "Language Pack for SharePoint and Project Server 2013 - Dutch/Nederlands") } - } - else - { - return @{ - FileMajorPart = 16 + 16 { + return @("Microsoft SharePoint Server 2016", "Language Pack for SharePoint and Project Server 2016 - Dutch/Nederlands") + } + Default { + throw [Exception] "A supported version of SharePoint was not used in testing" } } } - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "CLEAN_INSTALL" @@ -409,8 +415,8 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet } } - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscRegProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013", "Language Pack for SharePoint and Project Server 2013 - Dutch/Nederlands") } @@ -420,38 +426,18 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet } } - It "should throw exception in the get method" { + It "Should throw exception in the get method" { { Get-TargetResource @testParams } | Should Throw "Error while converting language information:" } } - Context "Upgrade pending - Skipping install" { - Mock Test-Path { - return $true + Context -Name "Upgrade pending - Skipping install" -Fixture { + $testParams = @{ + BinaryDir = "C:\SPInstall" + Ensure = "Present" } - Mock Get-ChildItem { - return @{ - Name = "C:\SPInstall\osrv.nl-nl" - } - } - - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "CLEAN_INSTALL" @@ -463,34 +449,30 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet } } - It "should return null from the set method" { + It "Should return null from the set method" { Set-TargetResource @testParams | Should BeNullOrEmpty } } - Context "BinaryInstallDays outside range" { + Context -Name "BinaryInstallDays outside range" -Fixture { $testParams = @{ BinaryDir = "C:\SPInstall" BinaryInstallDays = "mon" Ensure = "Present" } - Mock Test-Path { - return $true - } - $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should return null from the set method" { + It "Should return null from the set method" { Set-TargetResource @testParams | Should BeNullOrEmpty } } - Context "BinaryInstallTime outside range" { + Context -Name "BinaryInstallTime outside range" -Fixture { $testParams = @{ BinaryDir = "C:\SPInstall" BinaryInstallDays = "sun" @@ -498,22 +480,18 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet Ensure = "Present" } - Mock Test-Path { - return $true - } - $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should return null from the set method" { + It "Should return null from the set method" { Set-TargetResource @testParams | Should BeNullOrEmpty } } - Context "BinaryInstallTime incorrectly formatted, too many arguments" { + Context -Name "BinaryInstallTime incorrectly formatted, too many arguments" -Fixture { $testParams = @{ BinaryDir = "C:\SPInstall" BinaryInstallDays = "sun" @@ -521,22 +499,18 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet Ensure = "Present" } - Mock Test-Path { - return $true - } - $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should Throw "Time window incorrectly formatted." } } - Context "BinaryInstallTime incorrectly formatted, incorrect start time" { + Context -Name "BinaryInstallTime incorrectly formatted, incorrect start time" -Fixture { $testParams = @{ BinaryDir = "C:\SPInstall" BinaryInstallDays = "sun" @@ -544,22 +518,18 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet Ensure = "Present" } - Mock Test-Path { - return $true - } - $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should Throw "Error converting start time" } } - Context "BinaryInstallTime incorrectly formatted, incorrect end time" { + Context -Name "BinaryInstallTime incorrectly formatted, incorrect end time" -Fixture { $testParams = @{ BinaryDir = "C:\SPInstall" BinaryInstallDays = "sun" @@ -567,22 +537,18 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet Ensure = "Present" } - Mock Test-Path { - return $true - } - $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should Throw "Error converting end time" } } - Context "BinaryInstallTime start time larger than end time" { + Context -Name "BinaryInstallTime start time larger than end time" -Fixture { $testParams = @{ BinaryDir = "C:\SPInstall" BinaryInstallDays = "sun" @@ -590,35 +556,32 @@ Describe "SPInstallLanguagePack - SharePoint Build $((Get-Item $SharePointCmdlet Ensure = "Present" } - Mock Test-Path { - return $true - } - $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should Throw "Error: Start time cannot be larger than end time" } } - Context "Ensure is set to Absent" { + Context -Name "Ensure is set to Absent" -Fixture { $testParams = @{ BinaryDir = "C:\SPInstall" Ensure = "Absent" } - Mock Test-Path { return $true } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should Throw "SharePointDsc does not support uninstalling SharePoint Language Packs. Please remove this manually." } - It "should throw exception in the test method" { + It "Should throw exception in the test method" { { Test-TargetResource @testParams } | Should Throw "SharePointDsc does not support uninstalling SharePoint Language Packs. Please remove this manually." } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPInstallPrereqs.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPInstallPrereqs.Tests.ps1 index 4d553f3d2..45f1a66ec 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPInstallPrereqs.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPInstallPrereqs.Tests.ps1 @@ -1,21 +1,25 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPInstallPrereqs" -$ModuleName = "MSFT_SPInstallPrereqs" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPInstallPrereqs - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope - function New-SPDscMockPrereq() + # Initialize tests + function New-SPDscMockPrereq { param ( @@ -24,183 +28,207 @@ Describe "SPInstallPrereqs - SharePoint Build $((Get-Item $SharePointCmdletModul $Name ) $object = New-Object -TypeName System.Object - $object = $object | Add-Member -type NoteProperty -Name "DisplayName" -Value $Name -PassThru + $object = $object | Add-Member -Type NoteProperty ` + -Name "DisplayName" ` + -Value $Name ` + -PassThru return $object } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + if ($null -eq (Get-Command Get-WindowsFeature -ErrorAction SilentlyContinue)) + { + function Get-WindowsFeature { } + } + if ($null -eq (Get-Command Install-WindowsFeature -ErrorAction SilentlyContinue)) + { + function Install-WindowsFeature { } } - if ($null -eq (Get-Command Get-WindowsFeature -ErrorAction SilentlyContinue)) { - function Get-WindowsFeature() { } + # Mocks for all contexts + Mock -CommandName Get-ItemProperty -ParameterFilter { + $Path -eq "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" + } -MockWith { + return @() + } + + Mock -CommandName Get-ChildItem { + $full = @{ + Version = "4.5.0.0" + Release = "0" + PSChildName = "Full" + } + + $client = @{ + Version = "4.5.0.0" + Release = "0" + PSChildName = "Client" + } + + $returnval = @($full, $client) + $returnVal = $returnVal | Add-Member ScriptMethod GetValue { return 380000 } -PassThru + return $returnval } - if ($null -eq (Get-Command Install-WindowsFeature -ErrorAction SilentlyContinue)) { - function Install-WindowsFeature() { } + + Mock -CommandName Get-ItemProperty -ParameterFilter { + $Path -eq "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" + } -MockWith { + return @() } - Mock Get-ItemProperty -ParameterFilter { - $Path -eq "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" - } -MockWith { - return @() - } - - Mock Get-ChildItem { - return @( - @{ - Version = "4.5.0.0" - Release = "0" - PSChildName = "Full" - }, - @{ - Version = "4.5.0.0" - Release = "0" - PSChildName = "Client" - } - ) + Mock -CommandName Test-Path -MockWith { + return $true } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - $versionBeingTested = (Get-Item $Global:CurrentSharePointStubModule).Directory.BaseName - $majorBuildNumber = $versionBeingTested.Substring(0, $versionBeingTested.IndexOf(".")) - Mock Get-SPDSCAssemblyVersion { return $majorBuildNumber } - Mock Get-SPDscOSVersion { + Mock -CommandName Get-SPDscOSVersion -MockWith { return @{ Major = 6 Minor = 3 } } - Context "Prerequisites are not installed but should be and are to be installed in online mode" { + Mock -CommandName Get-WindowsFeature -MockWith { + return @(@{ + Name = "ExampleFeature" + Installed = $false + }) + } + + # Test contexts + Context -Name "Prerequisites are not installed but should be and are to be installed in online mode" -Fixture { $testParams = @{ - InstallerPath = "C:\SPInstall" + InstallerPath = "C:\SPInstall\Prerequisiteinstaller.exe" OnlineMode = $true Ensure = "Present" } - - Mock Get-WindowsFeature { @( @{ Name = "ExampleFeature"; Installed = $false}) } - Mock Get-ItemProperty -MockWith { + + Mock -CommandName Get-ItemProperty -MockWith { return @() - } + } -ParameterFilter { $null -ne $Path } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "Calls the prerequisite installer from the set method and records the need for a reboot" { - Mock Start-Process { return @{ ExitCode = 3010 } } + It "Should call the prerequisite installer from the set method and records the need for a reboot" { + Mock -CommandName Start-Process { return @{ ExitCode = 3010 } } Set-TargetResource @testParams Assert-MockCalled Start-Process } - It "Calls the prerequisite installer from the set method and a pending reboot is preventing it from running" { - Mock Start-Process { return @{ ExitCode = 1001 } } + It "Should call the prerequisite installer from the set method and a pending reboot is preventing it from running" { + Mock -CommandName Start-Process { return @{ ExitCode = 1001 } } Set-TargetResource @testParams Assert-MockCalled Start-Process } - It "Calls the prerequisite installer from the set method and passes a successful installation" { - Mock Start-Process { return @{ ExitCode = 0 } } + It "Should call the prerequisite installer from the set method and passes a successful installation" { + Mock -CommandName Start-Process { return @{ ExitCode = 0 } } Set-TargetResource @testParams Assert-MockCalled Start-Process } - It "Calls the prerequisite installer from the set method when the prerequisite installer is already running" { - Mock Start-Process { return @{ ExitCode = 1 } } + It "Should call the prerequisite installer from the set method when the prerequisite installer is already running" { + Mock -CommandName Start-Process { return @{ ExitCode = 1 } } { Set-TargetResource @testParams } | Should Throw "already running" } - It "Calls the prerequisite installer from the set method and invalid arguments are passed to the installer" { - Mock Start-Process { return @{ ExitCode = 2 } } + It "Should call the prerequisite installer from the set method and invalid arguments are passed to the installer" { + Mock -CommandName Start-Process { return @{ ExitCode = 2 } } { Set-TargetResource @testParams } | Should Throw "Invalid command line parameters" } - It "Calls the prerequisite installer from the set method and throws for unknown error codes" { - Mock Start-Process { return @{ ExitCode = -1 } } + It "Should call the prerequisite installer from the set method and throws for unknown error codes" { + Mock -CommandName Start-Process { return @{ ExitCode = -1 } } { Set-TargetResource @testParams } | Should Throw "unknown exit code" } } - Context "Prerequisites are installed and should be" { + Context -Name "Prerequisites are installed and should be" -Fixture { $testParams = @{ - InstallerPath = "C:\SPInstall" + InstallerPath = "C:\SPInstall\Prerequisiteinstaller.exe" OnlineMode = $true Ensure = "Present" } - - Mock Get-WindowsFeature { @( @{ Name = "ExampleFeature"; Installed = $true }) } - - if ($majorBuildNumber -eq 15) { - Mock Get-ItemProperty -ParameterFilter { - $Path -eq "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" - } -MockWith { - return @( - (New-SPDscMockPrereq -Name "Microsoft CCR and DSS Runtime 2008 R3"), - (New-SPDscMockPrereq -Name "Microsoft Sync Framework Runtime v1.0 SP1 (x64)"), - (New-SPDscMockPrereq -Name "AppFabric 1.1 for Windows Server"), - (New-SPDscMockPrereq -Name "WCF Data Services 5.6.0 Runtime"), - (New-SPDscMockPrereq -Name "WCF Data Services 5.0 (for OData v3) Primary Components"), - (New-SPDscMockPrereq -Name "Microsoft SQL Server 2008 R2 Native Client"), - (New-SPDscMockPrereq -Name "Active Directory Rights Management Services Client 2.0"), - (New-SPDscMockPrereq -Name "Microsoft Identity Extensions" ) - ) + + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) + { + 15 { + Mock -CommandName Get-ItemProperty -ParameterFilter { + $Path -eq "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" + } -MockWith { + return @( + (New-SPDscMockPrereq -Name "Microsoft CCR and DSS Runtime 2008 R3"), + (New-SPDscMockPrereq -Name "Microsoft Sync Framework Runtime v1.0 SP1 (x64)"), + (New-SPDscMockPrereq -Name "AppFabric 1.1 for Windows Server"), + (New-SPDscMockPrereq -Name "WCF Data Services 5.6.0 Runtime"), + (New-SPDscMockPrereq -Name "WCF Data Services 5.0 (for OData v3) Primary Components"), + (New-SPDscMockPrereq -Name "Microsoft SQL Server 2008 R2 Native Client"), + (New-SPDscMockPrereq -Name "Active Directory Rights Management Services Client 2.0"), + (New-SPDscMockPrereq -Name "Microsoft Identity Extensions" ) + ) + } } - } - if ($majorBuildNumber -eq 16) { - Mock Get-ItemProperty -ParameterFilter { - $Path -eq "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" - } -MockWith { - return @( - (New-SPDscMockPrereq -Name "Microsoft CCR and DSS Runtime 2008 R3"), - (New-SPDscMockPrereq -Name "Microsoft Sync Framework Runtime v1.0 SP1 (x64)"), - (New-SPDscMockPrereq -Name "AppFabric 1.1 for Windows Server"), - (New-SPDscMockPrereq -Name "WCF Data Services 5.6.0 Runtime"), - (New-SPDscMockPrereq -Name "Microsoft ODBC Driver 11 for SQL Server"), - (New-SPDscMockPrereq -Name "Microsoft Visual C++ 2012 x64 Minimum Runtime - 11.0.61030"), - (New-SPDscMockPrereq -Name "Microsoft Visual C++ 2012 x64 Additional Runtime - 11.0.61030"), - (New-SPDscMockPrereq -Name "Microsoft Visual C++ 2015 x64 Minimum Runtime - 14.0.23026"), - (New-SPDscMockPrereq -Name "Microsoft Visual C++ 2015 x64 Additional Runtime - 14.0.23026"), - (New-SPDscMockPrereq -Name "Microsoft SQL Server 2012 Native Client"), - (New-SPDscMockPrereq -Name "Active Directory Rights Management Services Client 2.1"), - (New-SPDscMockPrereq -Name "Microsoft Identity Extensions") - ) + 16 { + Mock -CommandName Get-ItemProperty -ParameterFilter { + $Path -eq "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" + } -MockWith { + return @( + (New-SPDscMockPrereq -Name "Microsoft CCR and DSS Runtime 2008 R3"), + (New-SPDscMockPrereq -Name "Microsoft Sync Framework Runtime v1.0 SP1 (x64)"), + (New-SPDscMockPrereq -Name "AppFabric 1.1 for Windows Server"), + (New-SPDscMockPrereq -Name "WCF Data Services 5.6.0 Runtime"), + (New-SPDscMockPrereq -Name "Microsoft ODBC Driver 11 for SQL Server"), + (New-SPDscMockPrereq -Name "Microsoft Visual C++ 2012 x64 Minimum Runtime - 11.0.61030"), + (New-SPDscMockPrereq -Name "Microsoft Visual C++ 2012 x64 Additional Runtime - 11.0.61030"), + (New-SPDscMockPrereq -Name "Microsoft Visual C++ 2015 x64 Minimum Runtime - 14.0.23026"), + (New-SPDscMockPrereq -Name "Microsoft Visual C++ 2015 x64 Additional Runtime - 14.0.23026"), + (New-SPDscMockPrereq -Name "Microsoft SQL Server 2012 Native Client"), + (New-SPDscMockPrereq -Name "Active Directory Rights Management Services Client 2.1"), + (New-SPDscMockPrereq -Name "Microsoft Identity Extensions") + ) + } } + Default { + throw [Exception] "A supported version of SharePoint was not used in testing" + } + } + + Mock -CommandName Get-WindowsFeature -MockWith { + return @(@{ + Name = "ExampleFeature" + Installed = $true + }) } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - if ($majorBuildNumber -eq 15) + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { - Context "Prerequisites are installed and should be (with SQL 2012 native client for SP2013)" { + Context -Name "Prerequisites are installed and should be (with SQL 2012 native client for SP2013)" -Fixture { $testParams = @{ - InstallerPath = "C:\SPInstall" + InstallerPath = "C:\SPInstall\Prerequisiteinstaller.exe" OnlineMode = $true Ensure = "Present" } - Mock Get-WindowsFeature { @( @{ Name = "ExampleFeature"; Installed = $true }) } - Mock Get-ItemProperty -ParameterFilter { + Mock -CommandName Get-ItemProperty -ParameterFilter { $Path -eq "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" } -MockWith { return @( @@ -215,173 +243,302 @@ Describe "SPInstallPrereqs - SharePoint Build $((Get-Item $SharePointCmdletModul ) } - It "returns present from the get method" { + Mock -CommandName Get-WindowsFeature -MockWith { + return @(@{ + Name = "ExampleFeature" + Installed = $true + }) + } + + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } } - - Context "Prerequisites are installed but should not be" { + Context -Name "Prerequisites are installed but should not be" -Fixture { $testParams = @{ - InstallerPath = "C:\SPInstall" + InstallerPath = "C:\SPInstall\Prerequisiteinstaller.exe" OnlineMode = $true Ensure = "Absent" } - It "throws an exception from the set method" { + It "Should throw an exception from the set method" { {Test-TargetResource @testParams} | Should Throw } - It "throws an exception from the set method" { + It "Should throw an exception from the set method" { {Set-TargetResource @testParams} | Should Throw } } - Context "Prerequisites are not installed but should be and are to be installed in offline mode" { + Context -Name "Prerequisites are not installed but should be and are to be installed in offline mode" -Fixture { $testParams = @{ - InstallerPath = "C:\SPInstall" + InstallerPath = "C:\SPInstall\Prerequisiteinstaller.exe" OnlineMode = $false Ensure = "Present" } - Mock Get-WindowsFeature { @( @{ Name = "ExampleFeature"; Installed = $false}) } - Mock Get-ItemProperty -MockWith { + Mock -CommandName Get-ItemProperty -MockWith { return @() + } -ParameterFilter { $null -ne $Path } + + Mock -CommandName Start-Process -MockWith { + return @{ + ExitCode = 0 + } + } + Mock -CommandName Test-Path -MockWith { + return $true } - It "throws an exception in the set method if required parameters are not set" { + It "Should throw an exception in the set method if required parameters are not set" { {Set-TargetResource @testParams} | Should Throw } - if ($majorBuildNumber -eq 15) { - $requiredParams = @("SQLNCli","PowerShell","NETFX","IDFX","Sync","AppFabric","IDFX11","MSIPCClient","WCFDataServices","KB2671763","WCFDataServices56") - } - if ($majorBuildNumber -eq 16) { - $requiredParams = @("SQLNCli","Sync","AppFabric","IDFX11","MSIPCClient","KB3092423","WCFDataServices56","DotNetFx","MSVCRT11","MSVCRT14","ODBC") + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) + { + 15 { + $requiredParams = @("SQLNCli","PowerShell","NETFX","IDFX","Sync","AppFabric","IDFX11","MSIPCClient","WCFDataServices","KB2671763","WCFDataServices56") + } + 16 { + $requiredParams = @("SQLNCli","Sync","AppFabric","IDFX11","MSIPCClient","KB3092423","WCFDataServices56","DotNetFx","MSVCRT11","MSVCRT14","ODBC") + } + Default { + throw [Exception] "A supported version of SharePoint was not used in testing" + } } - $requiredParams | ForEach-Object { + + $requiredParams | ForEach-Object -Process { $testParams.Add($_, "C:\fake\value.exe") } It "does not throw an exception where the required parameters are included" { - Mock Start-Process { return @{ ExitCode = 0 } } - Mock Test-Path { return $true } - {Set-TargetResource @testParams} | Should Not Throw } } - Context "Prerequisites are not installed but should be and are to be installed in offline mode, but invalid paths have been passed" { + Context -Name "Prerequisites are not installed but should be and are to be installed in offline mode, but invalid paths have been passed" -Fixture { $testParams = @{ - InstallerPath = "C:\SPInstall" + InstallerPath = "C:\SPInstall\Prerequisiteinstaller.exe" OnlineMode = $false Ensure = "Present" } - Mock Get-WindowsFeature { @( @{ Name = "ExampleFeature"; Installed = $false }) } - Mock Get-ItemProperty -MockWith { + Mock -CommandName Get-WindowsFeature -MockWith { + return @( @{ + Name = "ExampleFeature" + Installed = $false + }) + } + + Mock -CommandName Get-ItemProperty -MockWith { return @() } - It "throws an exception in the set method if required parameters are not set" { - {Set-TargetResource @testParams} | Should Throw + Mock -CommandName Start-Process -MockWith { + return @{ + ExitCode = 0 + } + } + Mock -CommandName Test-Path -MockWith { + return $false } - if ($majorBuildNumber -eq 15) { - $requiredParams = @("SQLNCli","PowerShell","NETFX","IDFX","Sync","AppFabric","IDFX11","MSIPCClient","WCFDataServices","KB2671763","WCFDataServices56") + It "Should throw an exception in the set method if required parameters are not set" { + {Set-TargetResource @testParams} | Should Throw } - if ($majorBuildNumber -eq 16) { - $requiredParams = @("SQLNCli","Sync","AppFabric","IDFX11","MSIPCClient","KB3092423","WCFDataServices56","DotNetFx","MSVCRT11","MSVCRT14","ODBC") + + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) + { + 15 { + $requiredParams = @("SQLNCli","PowerShell","NETFX","IDFX","Sync","AppFabric","IDFX11","MSIPCClient","WCFDataServices","KB2671763","WCFDataServices56") + } + 16 { + $requiredParams = @("SQLNCli","Sync","AppFabric","IDFX11","MSIPCClient","KB3092423","WCFDataServices56","DotNetFx","MSVCRT11","MSVCRT14","ODBC") + } + Default { + throw [Exception] "A supported version of SharePoint was not used in testing" + } } - $requiredParams | ForEach-Object { + $requiredParams | ForEach-Object -Process { $testParams.Add($_, "C:\fake\value.exe") } It "does not throw an exception where the required parameters are included" { - Mock Start-Process { return @{ ExitCode = 0 } } - Mock Test-Path { return $false } - {Set-TargetResource @testParams} | Should Throw } } - Context "SharePoint 2013 is installing on a server with .NET 4.6" { - Mock Get-ChildItem { - return @( - @{ + if ($majorBuildNumber -eq 15) + { + Context -Name "SharePoint 2013 is installing on a server with .NET 4.6" -Fixture { + $testParams = @{ + InstallerPath = "C:\SPInstall\Prerequisiteinstaller.exe" + OnlineMode = $true + Ensure = "Present" + } + + Mock -CommandName Get-ChildItem { + $full = @{ Version = "4.6.0.0" Release = "0" PSChildName = "Full" - }, - @{ + } + + $client = @{ Version = "4.6.0.0" Release = "0" PSChildName = "Client" + } + + $returnval = @($full, $client) + $returnVal = $returnVal | Add-Member ScriptMethod GetValue { return 391000 } -PassThru + return $returnval + } + + Mock -CommandName Get-ItemProperty -MockWith { + return @{ + VersionInfo = @{ + FileVersion = "15.0.4600.1000" + } } - ) + } -ParameterFilter { + $Path -eq "C:\SPInstall\updates\svrsetup.dll" + } + + It "throws an error in the set method" { + { Set-TargetResource @testParams } | Should Throw ("A known issue prevents installation of SharePoint 2013 on " + ` + "servers that have .NET 4.6 already installed") + } } - - It "throws an error in the set method" { - { Set-TargetResource @testParams } | Should Throw + + Context -Name "SharePoint 2013 is installing on a server with .NET 4.6 with compatibility update" { + $testParams = @{ + InstallerPath = "C:\SPInstall\Prerequisiteinstaller.exe" + OnlineMode = $true + Ensure = "Present" + } + + Mock -CommandName Get-ChildItem { + $full = @{ + Version = "4.6.0.0" + Release = "0" + PSChildName = "Full" + } + + $client = @{ + Version = "4.6.0.0" + Release = "0" + PSChildName = "Client" + } + + $returnval = @($full, $client) + $returnVal = $returnVal | Add-Member ScriptMethod GetValue { return 391000 } -PassThru + return $returnval + } + + Mock -CommandName Get-ItemProperty -MockWith { + return @{ + VersionInfo = @{ + FileVersion = "15.0.4709.1000" + } + } + } -ParameterFilter { + $Path -eq "C:\SPInstall\updates\svrsetup.dll" + } + + It "should install prereqs" { + Mock Start-Process { return @{ ExitCode = 0 } } + Mock Test-Path { return $true } + + Set-TargetResource @testParams + Assert-MockCalled Start-Process -Scope It + } } - } + } - Context "Prerequisites are not installed but should be and are to be installed in offline mode, with SXSstore specified" { + Context -Name "Prerequisites are not installed but should be and are to be installed in offline mode, with SXSstore specified" -Fixture { $testParams = @{ - InstallerPath = "C:\SPInstall" + InstallerPath = "C:\SPInstall\Prerequisiteinstaller.exe" OnlineMode = $false SXSpath = "C:\SPInstall\SXS" Ensure = "Present" } - Mock Get-WindowsFeature { @( @{ Name = "ExampleFeature"; Installed = $false}) } - Mock Get-ItemProperty -MockWith { + Mock -CommandName Get-ItemProperty -MockWith { return @() } - if ($majorBuildNumber -eq 15) { - $requiredParams = @("SQLNCli","PowerShell","NETFX","IDFX","Sync","AppFabric","IDFX11","MSIPCClient","WCFDataServices","KB2671763","WCFDataServices56") + Mock -CommandName Start-Process -MockWith { + return @{ + ExitCode = 0 + } + } + + Mock -CommandName Test-Path -MockWith { + return $true } - if ($majorBuildNumber -eq 16) { - $requiredParams = @("SQLNCli","Sync","AppFabric","IDFX11","MSIPCClient","KB3092423","WCFDataServices56","DotNetFx","MSVCRT11","MSVCRT14","ODBC") + + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) + { + 15 { + $requiredParams = @("SQLNCli","PowerShell","NETFX","IDFX","Sync","AppFabric","IDFX11","MSIPCClient","WCFDataServices","KB2671763","WCFDataServices56") + } + 16 { + $requiredParams = @("SQLNCli","Sync","AppFabric","IDFX11","MSIPCClient","KB3092423","WCFDataServices56","DotNetFx","MSVCRT11","MSVCRT14","ODBC") + } + Default { + throw [Exception] "A supported version of SharePoint was not used in testing" + } } - $requiredParams | ForEach-Object { + $requiredParams | ForEach-Object -Process { $testParams.Add($_, "C:\fake\value.exe") } It "installs required Windows features from specified path" { - Mock Install-WindowsFeature { @( @{ Name = "ExampleFeature"; Success = $true ; restartneeded = "no"}) } - Mock Start-Process { return @{ ExitCode = 0 } } - Mock Test-Path { return $true } + Mock -CommandName Install-WindowsFeature -MockWith { + return @( @{ + Name = "ExampleFeature" + Success = $true + RestartNeeded = "No" + }) + } Set-TargetResource @testParams - Assert-MockCalled Install-WindowsFeature -Scope It + Assert-MockCalled Install-WindowsFeature } It "feature install requires a reboot" { - Mock Install-WindowsFeature { @( @{ Name = "ExampleFeature"; Success = $true ; restartneeded = "yes"}) } - Mock Start-Process { return @{ ExitCode = 0 } } - Mock Test-Path { return $true } + Mock -CommandName Install-WindowsFeature -MockWith { + return @( @{ + Name = "ExampleFeature" + Success = $true + RestartNeeded = "Yes" + }) + } Set-TargetResource @testParams - $global:DSCMachineStatus | Should Be 1 - + $global:DSCMachineStatus | Should Be 1 } It "feature install failure throws an error" { - Mock Install-WindowsFeature { @( @{ Name = "ExampleFeature"; Success = $false ; restartneeded = "no"}) } - Mock Start-Process { return @{ ExitCode = 0 } } - Mock Test-Path { return $true } + Mock -CommandName Install-WindowsFeature -MockWith { + return @( @{ + Name = "ExampleFeature" + Success = $false + RestartNeeded = "No" + }) + } - {Set-TargetResource @testParams} | should Throw "Error installing ExampleFeature" - + {Set-TargetResource @testParams} | should Throw "Error installing ExampleFeature" } - } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPIrmSettings.tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPIrmSettings.tests.ps1 index 90f6b1c55..d1d2a4fde 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPIrmSettings.tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPIrmSettings.tests.ps1 @@ -1,128 +1,127 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4693.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPIrmSettings" -$ModuleName = "MSFT_SPIrmSettings" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + # Initialize tests -Describe "SPIrmSettings - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + # Mocks for all contexts + Mock -CommandName Get-SPFarm -MockWith { + return @{} } - - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - - Context "The server is not part of SharePoint farm" { - Mock Get-SPFarm { throw "Unable to detect local farm" } + # Test contexts + Context -Name "The server is not part of SharePoint farm" -Fixture { $testParams = @{ Ensure = "Present" RMSserver = "https://myRMSserver.local" } + + Mock -CommandName Get-SPFarm -MockWith { + throw "Unable to detect local farm" + } - It "return null from the get method" { + It "Should return null from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws an exception in the set method to say there is no local farm" { + It "Should throw an exception in the set method to say there is no local farm" { { Set-TargetResource @testParams } | Should throw "No local SharePoint farm was detected" } } - - Context "IRM settings match desired settings" { - - Mock Get-SPDSCContentService { - $returnVal = @{ - IrmSettings = @{ - IrmRMSEnabled = $true - IrmRMSUseAD = $false - IrmRMSCertServer = "https://myRMSserver.local" - } - } - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCIRMUpdated = $true } -PassThru - return $returnVal - } - - Mock Get-SPFarm { return @{} } - - $TestParams = @{ + Context -Name "IRM settings match desired settings" -Fixture { + $testParams = @{ Ensure = "Present" RMSserver = "https://myRMSserver.local" } + + Mock -CommandName Get-SPDSCContentService -MockWith { + $returnVal = @{ + IrmSettings = @{ + IrmRMSEnabled = $true + IrmRMSUseAD = $false + IrmRMSCertServer = "https://myRMSserver.local" + } + } + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value { + $Global:SPDscIRMUpdated = $true + } -PassThru + return $returnVal + } - It "Get returns current settings" { + It "Should return present in the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "Test returns True" { + It "Should return true in the test method" { Test-TargetResource @testParams | Should Be $true } } - - Context "IRM settings do not match desired settings" { - - Mock Get-SPDSCContentService { - $returnVal = @{ - IrmSettings = @{ - IrmRMSEnabled = $false - IrmRMSUseAD = $false - IrmRMSCertServer = $null - } - } - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCIRMUpdated = $true } -PassThru - return $returnVal - } - - Mock Get-SPFarm { return @{} } - - $TestParams = @{ + Context -Name "IRM settings do not match desired settings" -Fixture { + $testParams = @{ Ensure = "Present" RMSserver = "https://myRMSserver.local" } + + Mock -CommandName Get-SPDSCContentService -MockWith { + $returnVal = @{ + IrmSettings = @{ + IrmRMSEnabled = $false + IrmRMSUseAD = $false + IrmRMSCertServer = $null + } + } + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value { + $Global:SPDscIRMUpdated = $true + } -PassThru + return $returnVal + } - It "Get returns current settings" { + It "Should return absent in the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "Test returns False" { + It "Should return false in the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPDSCIRMUpdated = - It "Set applies desired settings" { + $Global:SPDscIRMUpdated = $false + It "Should apply the settings in the set method" { Set-TargetResource @testParams - $Global:SPDSCIRMUpdated | Should Be $true + $Global:SPDscIRMUpdated | Should Be $true } - It "UseAD and RMSserver both supplied (can only use one), should throw" { - $TestParams.Add("UseADRMS",$true) - { Set-TargetResource @testParams }| Should Throw + It "Should throw when UseAD and RMSserver are both supplied" { + $testParams.Add("UseADRMS",$true) + { Set-TargetResource @testParams } | Should Throw } } - - - - - - } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPJoinFarm.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPJoinFarm.Tests.ps1 index 57f672c52..ad2f3f75e 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPJoinFarm.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPJoinFarm.Tests.ps1 @@ -1,62 +1,63 @@ [CmdletBinding()] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPJoinFarm" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPJoinFarm - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - FarmConfigDatabaseName = "SP_Config" - DatabaseServer = "DatabaseServer\Instance" - Passphrase = New-Object System.Management.Automation.PSCredential ("PASSPHRASEUSER", (ConvertTo-SecureString "MyFarmPassphrase" -AsPlainText -Force)) - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Mock Connect-SPConfigurationDatabase {} - Mock Install-SPHelpCollection {} - Mock Initialize-SPResourceSecurity {} - Mock Install-SPService {} - Mock Install-SPFeature {} - Mock New-SPCentralAdministration {} - Mock Install-SPApplicationContent {} - Mock Start-Service {} - Mock Start-Sleep {} - - $versionBeingTested = (Get-Item $Global:CurrentSharePointStubModule).Directory.BaseName - $majorBuildNumber = $versionBeingTested.Substring(0, $versionBeingTested.IndexOf(".")) - - Mock Get-SPDSCInstalledProductVersion { return @{ FileMajorPart = $majorBuildNumber } } - +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPJoinFarm" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Initialize tests + $mockPassphrase = ConvertTo-SecureString -String "MyFarmPassphrase" -AsPlainText -Force + $mockPassphraseCredential = New-Object -TypeName System.Management.Automation.PSCredential ` + -ArgumentList @("passphrase", $mockPassphrase) + + # Mocks for all contexts + Mock Connect-SPConfigurationDatabase -MockWith {} + Mock -CommandName Install-SPHelpCollection -MockWith {} + Mock Initialize-SPResourceSecurity -MockWith {} + Mock -CommandName Install-SPService -MockWith {} + Mock -CommandName Install-SPFeature -MockWith {} + Mock -CommandName New-SPCentralAdministration -MockWith {} + Mock -CommandName Install-SPApplicationContent -MockWith {} + Mock -CommandName Start-Service -MockWith {} + Mock -CommandName Start-Sleep -MockWith {} + + # Test contexts + Context -Name "no farm is configured locally and a supported version of SharePoint is installed" { + $testParams = @{ + FarmConfigDatabaseName = "SP_Config" + DatabaseServer = "DatabaseServer\Instance" + Passphrase = $mockPassphraseCredential + } - Context "no farm is configured locally and a supported version of SharePoint is installed" { - Mock Get-SPFarm { throw "Unable to detect local farm" } + Mock -CommandName Get-SPFarm -MockWith { + throw "Unable to detect local farm" + } - It "the get method returns null when the farm is not configured" { + It "Should return null from the get method when the farm is not configured" { Get-TargetResource @testParams | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "calls the appropriate cmdlets in the set method" { + It "Should call the appropriate cmdlets in the set method" { Set-TargetResource @testParams - switch ($majorBuildNumber) + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) { 15 { Assert-MockCalled Connect-SPConfigurationDatabase @@ -68,72 +69,111 @@ Describe "SPJoinFarm - SharePoint Build $((Get-Item $SharePointCmdletModule).Dir throw [Exception] "A supported version of SharePoint was not used in testing" } } - } } - if ($majorBuildNumber -eq 15) { - $testParams.Add("ServerRole", "WebFrontEnd") + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) + { + Context -Name "only valid parameters for SharePoint 2013 are used" { + $testParams = @{ + FarmConfigDatabaseName = "SP_Config" + DatabaseServer = "DatabaseServer\Instance" + Passphrase = $mockPassphraseCredential + ServerRole = "WebFrontEnd" + } - Context "only valid parameters for SharePoint 2013 are used" { - It "throws if server role is used in the get method" { + It "Should throw if server role is used in the get method" { { Get-TargetResource @testParams } | Should Throw } - It "throws if server role is used in the test method" { + It "Should throw if server role is used in the test method" { { Test-TargetResource @testParams } | Should Throw } - It "throws if server role is used in the set method" { + It "Should throw if server role is used in the set method" { { Set-TargetResource @testParams } | Should Throw } } - - $testParams.Remove("ServerRole") } - Context "no farm is configured locally and an unsupported version of SharePoint is installed on the server" { - Mock Get-SPDSCInstalledProductVersion { return @{ FileMajorPart = 14 } } + Context -Name "no farm is configured locally and an unsupported version of SharePoint is installed on the server" { + $testParams = @{ + FarmConfigDatabaseName = "SP_Config" + DatabaseServer = "DatabaseServer\Instance" + Passphrase = $mockPassphraseCredential + } + + Mock -CommandName Get-SPDSCInstalledProductVersion { + return @{ FileMajorPart = 14 } + } - It "throws when an unsupported version is installed and set is called" { + It "Should throw when an unsupported version is installed and set is called" { { Set-TargetResource @testParams } | Should throw } } - Context "a farm exists locally and is the correct farm" { - Mock Get-SPFarm { return @{ - DefaultServiceAccount = @{ Name = $testParams.FarmAccount.UserName } - Name = $testParams.FarmConfigDatabaseName - }} - Mock Get-SPDatabase { return @(@{ - Name = $testParams.FarmConfigDatabaseName - Type = "Configuration Database" - Server = @{ Name = $testParams.DatabaseServer } - })} + Context -Name "a farm exists locally and is the correct farm" { + $testParams = @{ + FarmConfigDatabaseName = "SP_Config" + DatabaseServer = "DatabaseServer\Instance" + Passphrase = $mockPassphraseCredential + } + + Mock -CommandName Get-SPFarm -MockWith { + return @{ + DefaultServiceAccount = @{ + Name = $testParams.FarmAccount.UserName + } + Name = $testParams.FarmConfigDatabaseName + } + } + + Mock -CommandName Get-SPDatabase -MockWith { + return @(@{ + Name = $testParams.FarmConfigDatabaseName + Type = "Configuration Database" + Server = @{ + Name = $testParams.DatabaseServer + } + }) + } It "the get method returns values when the farm is configured" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "a farm exists locally and is not the correct farm" { - Mock Get-SPFarm { return @{ - DefaultServiceAccount = @{ Name = $testParams.FarmAccount.UserName } - Name = "WrongDBName" - }} - Mock Get-SPDatabase { return @(@{ - Name = "WrongDBName" - Type = "Configuration Database" - Server = @{ Name = $testParams.DatabaseServer } - })} - - It "throws an error in the set method" { + Context -Name "a farm exists locally and is not the correct farm" { + $testParams = @{ + FarmConfigDatabaseName = "SP_Config" + DatabaseServer = "DatabaseServer\Instance" + Passphrase = $mockPassphraseCredential + } + + Mock -CommandName Get-SPFarm -MockWith { + return @{ + DefaultServiceAccount = @{ Name = $testParams.FarmAccount.UserName } + Name = "WrongDBName" + } + } + + Mock -CommandName Get-SPDatabase -MockWith { + return @(@{ + Name = "WrongDBName" + Type = "Configuration Database" + Server = @{ Name = $testParams.DatabaseServer } + }) + } + + It "Should throw an error in the set method" { { Set-TargetResource @testParams } | Should throw } } - } -} \ No newline at end of file + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPManagedAccount.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPManagedAccount.Tests.ps1 index bcbd30898..93101b27d 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPManagedAccount.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPManagedAccount.Tests.ps1 @@ -1,106 +1,144 @@ [CmdletBinding()] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPManagedAccount" -$ModuleName = "MSFT_SPManagedAccount" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPManagedAccount - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Account = New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)) - EmailNotification = 7 - PreExpireDays = 7 - Schedule = "" - Ensure = "Present" - AccountName = "username" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Mock New-SPManagedAccount { } - Mock Set-SPManagedAccount { } - Mock Remove-SPManagedAccount { } + # Initialize tests + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential ` + -ArgumentList @("username", $mockPassword) - Context "The specified managed account does not exist in the farm and it should" { - Mock Get-SPManagedAccount { return $null } + # Mocks for all contexts + Mock -CommandName New-SPManagedAccount -MockWith { } + Mock -CommandName Set-SPManagedAccount -MockWith { } + Mock -CommandName Remove-SPManagedAccount -MockWith { } - It "returns null from the get method" { + # Test contexts + Context -Name "The specified managed account does not exist in the farm and it should" -Fixture { + $testParams = @{ + Account = $mockCredential + EmailNotification = 7 + PreExpireDays = 7 + Schedule = "" + Ensure = "Present" + AccountName = $mockCredential.Username + } + + Mock -CommandName Get-SPManagedAccount -MockWith { return $null } + + It "Should return null from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "calls the new and set methods from the set function" { + It "Should call the new and set methods from the set function" { Set-TargetResource @testParams Assert-MockCalled New-SPManagedAccount Assert-MockCalled Set-SPManagedAccount } } - Context "The specified managed account exists and it should but has an incorrect schedule" { - Mock Get-SPManagedAccount { return @{ - Username = $testParams.AccountName - DaysBeforeChangeToEmail = $testParams.EmailNotification - DaysBeforeExpiryToChange = $testParams.PreExpireDays - ChangeSchedule = "wrong schedule" - }} + Context -Name "The specified managed account exists and it should but has an incorrect schedule" -Fixture { + $testParams = @{ + Account = $mockCredential + EmailNotification = 7 + PreExpireDays = 7 + Schedule = "" + Ensure = "Present" + AccountName = $mockCredential.Username + } + + Mock -CommandName Get-SPManagedAccount -MockWith { + return @{ + Username = $testParams.AccountName + DaysBeforeChangeToEmail = $testParams.EmailNotification + DaysBeforeExpiryToChange = $testParams.PreExpireDays + ChangeSchedule = "wrong schedule" + } + } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "calls the set methods from the set function" { + It "Should call the set methods from the set function" { Set-TargetResource @testParams Assert-MockCalled Set-SPManagedAccount } } - Context "The specified managed account exists and it should but has incorrect notifcation settings" { - Mock Get-SPManagedAccount { return @{ - Username = $testParams.AccountName - DaysBeforeChangeToEmail = 0 - DaysBeforeExpiryToChange = 0 - ChangeSchedule = $testParams.Schedule - }} + Context -Name "The specified managed account exists and it should but has incorrect notifcation settings" -Fixture { + $testParams = @{ + Account = $mockCredential + EmailNotification = 7 + PreExpireDays = 7 + Schedule = "" + Ensure = "Present" + AccountName = $mockCredential.Username + } + + Mock -CommandName Get-SPManagedAccount -MockWith { + return @{ + Username = $testParams.AccountName + DaysBeforeChangeToEmail = 0 + DaysBeforeExpiryToChange = 0 + ChangeSchedule = $testParams.Schedule + } + } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "The specified managed account exists and it should and is also configured correctly" { - Mock Get-SPManagedAccount { return @{ - Username = $testParams.AccountName - DaysBeforeChangeToEmail = $testParams.EmailNotification - DaysBeforeExpiryToChange = $testParams.PreExpireDays - ChangeSchedule = $testParams.Schedule - }} + Context -Name "The specified managed account exists and it should and is also configured correctly" -Fixture { + $testParams = @{ + Account = $mockCredential + EmailNotification = 7 + PreExpireDays = 7 + Schedule = "" + Ensure = "Present" + AccountName = $mockCredential.Username + } + + Mock -CommandName Get-SPManagedAccount -MockWith { + return @{ + Username = $testParams.AccountName + DaysBeforeChangeToEmail = $testParams.EmailNotification + DaysBeforeExpiryToChange = $testParams.PreExpireDays + ChangeSchedule = $testParams.Schedule + } + } - It "returns the current values from the get method" { + It "Should return the current values from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The specified account should exist but the account property has not been specified" { + Context -Name "The specified account should exist but the account property has not been specified" -Fixture { $testParams = @{ EmailNotification = 7 PreExpireDays = 7 @@ -109,55 +147,68 @@ Describe "SPManagedAccount - SharePoint Build $((Get-Item $SharePointCmdletModul AccountName = "username" } - Mock Get-SPManagedAccount { return @{ - Username = $testParams.AccountName - DaysBeforeChangeToEmail = $testParams.EmailNotification - DaysBeforeExpiryToChange = $testParams.PreExpireDays - ChangeSchedule = $testParams.Schedule - }} + Mock -CommandName Get-SPManagedAccount -MockWith { + return @{ + Username = $testParams.AccountName + DaysBeforeChangeToEmail = $testParams.EmailNotification + DaysBeforeExpiryToChange = $testParams.PreExpireDays + ChangeSchedule = $testParams.Schedule + } + } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should Throw } } - - $testParams = @{ - Ensure = "Absent" - AccountName = "username" - } - Context "The specified account exists but it should not" { - Mock Get-SPManagedAccount { return @{ - Username = $testParams.AccountName - DaysBeforeChangeToEmail = $testParams.EmailNotification - DaysBeforeExpiryToChange = $testParams.PreExpireDays - ChangeSchedule = $testParams.Schedule - }} + Context -Name "The specified account exists but it should not" -Fixture { + $testParams = @{ + Ensure = "Absent" + AccountName = "username" + } + + Mock -CommandName Get-SPManagedAccount -MockWith { + return @{ + Username = $testParams.AccountName + DaysBeforeChangeToEmail = $testParams.EmailNotification + DaysBeforeExpiryToChange = $testParams.PreExpireDays + ChangeSchedule = $testParams.Schedule + } + } - It "should return present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should call the remove cmdlet from the set method" { + It "Should call the remove cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPManagedAccount } } - Context "The specified account does not exist and it should not" { - Mock Get-SPManagedAccount { return $null } + Context -Name "The specified account does not exist and it should not" -Fixture { + $testParams = @{ + Ensure = "Absent" + AccountName = "username" + } + + Mock -CommandName Get-SPManagedAccount -MockWith { + return $null + } - It "should return absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPManagedMetadataServiceApp.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPManagedMetadataServiceApp.Tests.ps1 index f6e9a6724..74855c5d3 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPManagedMetadataServiceApp.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPManagedMetadataServiceApp.Tests.ps1 @@ -1,170 +1,324 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPManagedMetaDataServiceApp" -$ModuleName = "MSFT_SPManagedMetaDataServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPManagedMetaDataServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Managed Metadata Service App" - ApplicationPool = "SharePoint Service Applications" - DatabaseServer = "databaseserver\instance" - DatabaseName = "SP_MMS" - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Remove-SPServiceApplication { } + #Initialize Tests + $getTypeFullName = "Microsoft.SharePoint.Taxonomy.MetadataWebServiceApplication" + + # Mocks for all contexts + Mock -CommandName New-SPMetadataServiceApplication -MockWith { return @{} } + Mock -CommandName New-SPMetadataServiceApplicationProxy -MockWith { return @{} } + Mock -CommandName Set-SPMetadataServiceApplication -MockWith { } + Mock -CommandName Remove-SPServiceApplication -MockWith { } - Context "When no service applications exist in the current farm" { + # Test contexts + Context -Name "When no service applications exist in the current farm" -Fixture { + $testParams = @{ + Name = "Managed Metadata Service App" + ApplicationPool = "SharePoint Service Applications" + DatabaseServer = "databaseserver\instance" + DatabaseName = "SP_MMS" + Ensure = "Present" + } - Mock Get-SPServiceApplication { return $null } - Mock New-SPMetadataServiceApplication { return @{} } - Mock New-SPMetadataServiceApplicationProxy { return @{} } + Mock -CommandName Get-SPServiceApplication -MockWith { return $null } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPMetadataServiceApplication } - - $testParams.Add("InstallAccount", (New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)))) - It "creates a new service application in the set method where InstallAccount is used" { - Set-TargetResource @testParams - Assert-MockCalled New-SPMetadataServiceApplication - } - $testParams.Remove("InstallAccount") } - Context "When service applications exist in the current farm but the specific MMS app does not" { + Context -Name "When service applications exist in the current farm but the specific MMS app does not" -Fixture { + $testParams = @{ + Name = "Managed Metadata Service App" + ApplicationPool = "SharePoint Service Applications" + DatabaseServer = "databaseserver\instance" + DatabaseName = "SP_MMS" + Ensure = "Present" + } - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Some other service app type" - }) } + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = "Microsoft.Office.UnKnownWebServiceApplication" + } + } -PassThru -Force + return $spServiceApp + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } } - Context "When a service application exists and is configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When a service application exists and is configured correctly" -Fixture { + $testParams = @{ + Name = "Managed Metadata Service App" + ApplicationPool = "SharePoint Service Applications" + DatabaseServer = "databaseserver\instance" + DatabaseName = "SP_MMS" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Managed Metadata Service" DisplayName = $testParams.Name - ApplicationPool = @{ Name = $testParams.ApplicationPool } + ApplicationPool = @{ + Name = $testParams.ApplicationPool + } Database = @{ Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return (@{ + FullName = $getTypeFullName + }) | Add-Member -MemberType ScriptMethod -Name GetMethods -Value { + return (@( + Name = "GetContentTypeSyndicationHubLocal" + )) | Add-Member -MemberType ScriptMethod -Name Invoke -Value { + return @{ + AbsoluteUri = "" + } + } -PassThru -Force + } -PassThru -Force + } -PassThru -Force + return $spServiceApp } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } - Context "When a service application exists and the app pool is not configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ + + Context -Name "When a service application exists and the app pool is not configured correctly" -Fixture { + $testParams = @{ + Name = "Managed Metadata Service App" + ApplicationPool = "SharePoint Service Applications" + DatabaseServer = "databaseserver\instance" + DatabaseName = "SP_MMS" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Managed Metadata Service" DisplayName = $testParams.Name - ApplicationPool = @{ Name = "Wrong App Pool Name" } + ApplicationPool = @{ + Name = "Wrong App Pool Name" + } Database = @{ Name = $testParams.DatabaseName - Server = @{ Name = $testParams.DatabaseServer } + Server = @{ + Name = $testParams.DatabaseServer + } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return (@{ + FullName = $getTypeFullName + }) | Add-Member -MemberType ScriptMethod -Name GetMethods -Value { + return (@( + Name = "GetContentTypeSyndicationHubLocal" + )) | Add-Member -MemberType ScriptMethod -Name Invoke -Value { + return @{ + AbsoluteUri = "" + } + } -PassThru -Force + } -PassThru -Force + } -PassThru -Force + return $spServiceApp + } + + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return @{ + Name = $testParams.ApplicationPool + } } - Mock Get-SPServiceApplicationPool { return @{ Name = $testParams.ApplicationPool } } - Mock Set-SPMetadataServiceApplication { } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "calls the update service app cmdlet from the set method" { + It "Should call the update service app cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Get-SPServiceApplicationPool - Assert-MockCalled Set-SPMetadataServiceApplication -ParameterFilter { $ApplicationPool.Name -eq $testParams.ApplicationPool } + Assert-MockCalled Set-SPMetadataServiceApplication -ParameterFilter { + $ApplicationPool.Name -eq $testParams.ApplicationPool + } } } - - $testParams = @{ - Name = "Test App" - ApplicationPool = "-" - Ensure = "Absent" + + Context -Name "When a service application exists and the content type hub is not configured correctly" -Fixture { + $testParams = @{ + Name = "Managed Metadata Service App" + ApplicationPool = "SharePoint Service Applications" + DatabaseServer = "databaseserver\instance" + DatabaseName = "SP_MMS" + ContentTypeHubUrl = "https://contenttypes.contoso.com" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + TypeName = "Managed Metadata Service" + DisplayName = $testParams.Name + ApplicationPool = @{ + Name = $testParams.AookucationPool + } + Database = @{ + Name = $testParams.DatabaseName + Server = @{ + Name = $testParams.DatabaseServer + } + } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return (@{ + FullName = $getTypeFullName + }) | Add-Member -MemberType ScriptMethod -Name GetMethods -Value { + return (@( + Name = "GetContentTypeSyndicationHubLocal" + )) | Add-Member -MemberType ScriptMethod -Name Invoke -Value { + return @{ + AbsoluteUri = "" + } + } -PassThru -Force + } -PassThru -Force + } -PassThru -Force + return $spServiceApp + } + + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return @{ + Name = $testParams.ApplicationPool + } + } + + It "Should return false when the Test method is called" { + Test-TargetResource @testParams | Should Be $false + } + + It "Should call the update service app cmdlet from the set method" { + Set-TargetResource @testParams + + Assert-MockCalled set-SPMetadataServiceApplication + } } - Context "When the service application exists but it shouldn't" { - Mock Get-SPServiceApplication { - return @(@{ + + Context -Name "When the service application exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Managed Metadata Service" DisplayName = $testParams.Name - ApplicationPool = @{ Name = "Wrong App Pool Name" } + ApplicationPool = @{ + Name = "Wrong App Pool Name" + } Database = @{ Name = $testParams.DatabaseName - Server = @{ Name = $testParams.DatabaseServer } + Server = @{ + Name = $testParams.DatabaseServer + } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return (@{ + FullName = $getTypeFullName + }) | Add-Member -MemberType ScriptMethod -Name GetMethods -Value { + return (@( + Name = "GetContentTypeSyndicationHubLocal" + )) | Add-Member -MemberType ScriptMethod -Name Invoke -Value { + return @{ + AbsoluteUri = "" + } + } -PassThru -Force + } -PassThru -Force + } -PassThru -Force + return $spServiceApp } - It "returns present from the Get method" { + It "Should return present from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "calls the remove service application cmdlet in the set method" { + It "Should call the remove service application cmdlet in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplication } } - Context "When the serivce application doesn't exist and it shouldn't" { - Mock Get-SPServiceApplication { return $null } + Context -Name "When the serivce application doesn't exist and it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPManagedPath.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPManagedPath.Tests.ps1 index 7144d56d9..5ed1f25d4 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPManagedPath.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPManagedPath.Tests.ps1 @@ -1,135 +1,159 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPManagedPath" -$ModuleName = "MSFT_SPManagedPath" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPManagedPath - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - WebAppUrl = "http://sites.sharepoint.com" - RelativeUrl = "teams" - Explicit = $false - HostHeader = $false - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Mock New-SPManagedPath { } - Mock Remove-SPManagedPath { } + # Mocks for all contexts + Mock -CommandName New-SPManagedPath -MockWith { } + Mock -CommandName Remove-SPManagedPath -MockWith { } + + # Test contexts + Context -Name "The managed path does not exist and should" -Fixture { + $testParams = @{ + WebAppUrl = "http://sites.sharepoint.com" + RelativeUrl = "teams" + Explicit = $false + HostHeader = $false + Ensure = "Present" + } - Context "The managed path does not exist and should" { - Mock Get-SPManagedPath { return $null } + Mock -CommandName Get-SPManagedPath -MockWith { + return $null + } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "creates a host header path in the set method" { + It "Should create a host header path in the set method" { Set-TargetResource @testParams - Assert-MockCalled New-SPManagedPath } $testParams.HostHeader = $true - It "creates a host header path in the set method" { + It "Should create a host header path in the set method" { Set-TargetResource @testParams - Assert-MockCalled New-SPManagedPath } - $testParams.HostHeader = $false - - $testParams.Add("InstallAccount", (New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)))) - It "creates a host header path in the set method where InstallAccount is used" { - Set-TargetResource @testParams - - Assert-MockCalled New-SPManagedPath - } - $testParams.Remove("InstallAccount") } - Context "The path exists but is of the wrong type" { - Mock Get-SPManagedPath { return @{ - Name = $testParams.RelativeUrl - Type = "ExplicitInclusion" - } } + Context -Name "The path exists but is of the wrong type" -Fixture { + $testParams = @{ + WebAppUrl = "http://sites.sharepoint.com" + RelativeUrl = "teams" + Explicit = $false + HostHeader = $false + Ensure = "Present" + } + + Mock -CommandName Get-SPManagedPath -MockWith { + return @{ + Name = $testParams.RelativeUrl + Type = "ExplicitInclusion" + } + } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "The path exists and is the correct type" { - Mock Get-SPManagedPath { return @{ - Name = $testParams.RelativeUrl - Type = "WildcardInclusion" - } } + Context -Name "The path exists and is the correct type" -Fixture { + $testParams = @{ + WebAppUrl = "http://sites.sharepoint.com" + RelativeUrl = "teams" + Explicit = $false + HostHeader = $false + Ensure = "Present" + } + + Mock -CommandName Get-SPManagedPath -MockWith { + return @{ + Name = $testParams.RelativeUrl + Type = "WildcardInclusion" + } + } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - $testParams = @{ - WebAppUrl = "http://sites.sharepoint.com" - RelativeUrl = "teams" - Explicit = $false - HostHeader = $false - Ensure = "Absent" - } - - Context "The managed path exists but shouldn't" { - Mock Get-SPManagedPath { return @{ - Name = $testParams.RelativeUrl - Type = "WildcardInclusion" - } } + Context -Name "The managed path exists but shouldn't" -Fixture { + $testParams = @{ + WebAppUrl = "http://sites.sharepoint.com" + RelativeUrl = "teams" + Explicit = $false + HostHeader = $false + Ensure = "Absent" + } + + Mock -CommandName Get-SPManagedPath -MockWith { + return @{ + Name = $testParams.RelativeUrl + Type = "WildcardInclusion" + } + } - It "should return present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should call the remove cmdlet from the set method" { + It "Should call the remove cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPManagedPath } } - Context "The managed path doesn't exist and shouldn't" { - Mock Get-SPManagedPath { return $null } + Context -Name "The managed path doesn't exist and shouldn't" -Fixture { + $testParams = @{ + WebAppUrl = "http://sites.sharepoint.com" + RelativeUrl = "teams" + Explicit = $false + HostHeader = $false + Ensure = "Absent" + } - It "should return absent from the set method" { + Mock -CommandName Get-SPManagedPath -MockWith { + return $null + } + + It "Should return absent from the set method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPOfficeOnlineServerBinding.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPOfficeOnlineServerBinding.Tests.ps1 index 12cc8e7ca..68cb1e9f3 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPOfficeOnlineServerBinding.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPOfficeOnlineServerBinding.Tests.ps1 @@ -1,67 +1,64 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPOfficeOnlineServerBinding" -$ModuleName = "MSFT_SPOfficeOnlineServerBinding" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPOfficeOnlineServerBinding - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") + # Mocks for all contexts + Mock -CommandName Remove-SPWOPIBinding -MockWith {} + Mock -CommandName New-SPWOPIBinding -MockWith {} + Mock -CommandName Set-SPWOPIZone -MockWith {} + Mock -CommandName Get-SPWOPIZone -MockWith { return "internal-https" } - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Remove-SPWOPIBinding {} - Mock New-SPWOPIBinding {} - Mock Set-SPWOPIZone {} - Mock Get-SPWOPIZone { return "internal-https" } - - Context "No bindings are set for the specified zone, but they should be" { + # Test contexts + Context -Name "No bindings are set for the specified zone, but they should be" -Fixture { $testParams = @{ Zone = "internal-https" DnsName = "webapps.contoso.com" Ensure = "Present" } - Mock Get-SPWOPIBinding { + Mock -CommandName Get-SPWOPIBinding -MockWith { return $null } - It "should return absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should create the bindings in the set method" { + It "Should create the bindings in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPWOPIBinding Assert-MockCalled Set-SPWOPIZone } } - Context "Incorrect bindings are set for the specified zone that should be configured" { + Context -Name "Incorrect bindings are set for the specified zone that should be configured" -Fixture { $testParams = @{ Zone = "internal-https" DnsName = "webapps.contoso.com" Ensure = "Present" } - Mock Get-SPWOPIBinding { + Mock -CommandName Get-SPWOPIBinding -MockWith { return @( @{ ServerName = "wrong.contoso.com" @@ -69,15 +66,15 @@ Describe "SPOfficeOnlineServerBinding - SharePoint Build $((Get-Item $SharePoint ) } - It "should return present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the old bindings and create the new bindings in the set method" { + It "Should remove the old bindings and create the new bindings in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPWOPIBinding Assert-MockCalled New-SPWOPIBinding @@ -85,14 +82,14 @@ Describe "SPOfficeOnlineServerBinding - SharePoint Build $((Get-Item $SharePoint } } - Context "Correct bindings are set for the specified zone" { + Context -Name "Correct bindings are set for the specified zone" -Fixture { $testParams = @{ Zone = "internal-https" DnsName = "webapps.contoso.com" Ensure = "Present" } - Mock Get-SPWOPIBinding { + Mock -CommandName Get-SPWOPIBinding -MockWith { return @( @{ ServerName = "webapps.contoso.com" @@ -100,23 +97,23 @@ Describe "SPOfficeOnlineServerBinding - SharePoint Build $((Get-Item $SharePoint ) } - It "should return present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Bindings are set for the specified zone, but they should not be" { + Context -Name "Bindings are set for the specified zone, but they should not be" -Fixture { $testParams = @{ Zone = "internal-https" DnsName = "webapps.contoso.com" Ensure = "Absent" } - Mock Get-SPWOPIBinding { + Mock -CommandName Get-SPWOPIBinding -MockWith { return @( @{ ServerName = "webapps.contoso.com" @@ -124,38 +121,40 @@ Describe "SPOfficeOnlineServerBinding - SharePoint Build $((Get-Item $SharePoint ) } - It "should return present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the bindings in the set method" { + It "Should remove the bindings in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPWOPIBinding } } - Context "Bindings are not set for the specified zone, and they should not be" { + Context -Name "Bindings are not set for the specified zone, and they should not be" -Fixture { $testParams = @{ Zone = "internal-https" DnsName = "webapps.contoso.com" Ensure = "Absent" } - Mock Get-SPWOPIBinding { + Mock -CommandName Get-SPWOPIBinding -MockWith { return $null } - It "should return absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPOutgoingEmailSettings.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPOutgoingEmailSettings.Tests.ps1 index 8eefdc792..fc49f72bf 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPOutgoingEmailSettings.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPOutgoingEmailSettings.Tests.ps1 @@ -1,109 +1,135 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPOutgoingEmailSettings" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPOutgoingEmailSettings - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - WebAppUrl = "http://sharepoint.contoso.com" - SMTPServer = "smtp.contoso.com" - FromAddress = "from@email.com" - ReplyToAddress = "reply@email.com" - CharacterSet= "65001" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPOutgoingEmailSettings" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Test contexts + Context -Name "The Web Application isn't available" -Fixture { + $testParams = @{ + WebAppUrl = "http://sharepoint.contoso.com" + SMTPServer = "smtp.contoso.com" + FromAddress = "from@email.com" + ReplyToAddress = "reply@email.com" + CharacterSet= "65001" + } - Context "The Web Application isn't available" { - Mock Get-SPWebApplication -MockWith { return $null + Mock -CommandName Get-SPWebApplication -MockWith { + return $null } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should be $false } - It "throws an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw } } - - Context "The web application exists and the properties match" { - Mock Get-SPWebApplication { + Context -Name "The web application exists and the properties match" -Fixture { + $testParams = @{ + WebAppUrl = "http://sharepoint.contoso.com" + SMTPServer = "smtp.contoso.com" + FromAddress = "from@email.com" + ReplyToAddress = "reply@email.com" + CharacterSet= "65001" + } + + Mock -CommandName Get-SPWebapplication -MockWith { return @{ - Url= "http://sharepoint.contoso.com" - OutboundMailServiceInstance= @{ - Server = @{ - Name = "smtp.contoso.com" - } + Url= "http://sharepoint.contoso.com" + OutboundMailServiceInstance= @{ + Server = @{ + Name = "smtp.contoso.com" } - OutboundMailSenderAddress = "from@email.com" - OutboundMailReplyToAddress= "reply@email.com" - OutboundMailCodePage= "65001" } + OutboundMailSenderAddress = "from@email.com" + OutboundMailReplyToAddress= "reply@email.com" + OutboundMailCodePage= "65001" + } } - It "returns web app properties from the get method" { + It "Should return web app properties from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The web application exists and the properties don't match" { - Mock Get-SPWebApplication { + Context -Name "The web application exists and the properties don't match" -Fixture { + $testParams = @{ + WebAppUrl = "http://sharepoint.contoso.com" + SMTPServer = "smtp.contoso.com" + FromAddress = "from@email.com" + ReplyToAddress = "reply@email.com" + CharacterSet= "65001" + } + + Mock -CommandName Get-SPWebapplication -MockWith { $result = @{ - Url= "http://sharepoint.contoso.com" - OutboundMailServiceInstance= @{ - Server = @{ - Name = "smtp2.contoso.com" - } + Url= "http://sharepoint.contoso.com" + OutboundMailServiceInstance= @{ + Server = @{ + Name = "smtp2.contoso.com" } - OutboundMailSenderAddress = "from@email.com" - OutboundMailReplyToAddress= "reply@email.com" - OutboundMailCodePage= "65001" } - $result = $result | Add-Member ScriptMethod UpdateMailSettings { - param( [string]$SMTPServer, [string]$FromAddress, [string]$ReplyToAddress, [string]$CharacterSet ) - $Global:UpdateMailSettingsCalled = $true; - return ; } -passThru + OutboundMailSenderAddress = "from@email.com" + OutboundMailReplyToAddress= "reply@email.com" + OutboundMailCodePage= "65001" + } + $result = $result | Add-Member -MemberType ScriptMethod ` + -Name UpdateMailSettings ` + -Value { + param( + [string] + $SMTPServer, + + [string] + $FromAddress, + + [string] + $ReplyToAddress, + [string] + $CharacterSet + ) + $Global:SPDscUpdateMailSettingsCalled = $true; + } -PassThru return $result } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "calls the new and set methods from the set function" { - $Global:UpdateMailSettingsCalled=$false; + It "Should call the new and set methods from the set function" { + $Global:SPDscUpdateMailSettingsCalled = $false Set-TargetResource @testParams - Assert-MockCalled Get-SPWebApplication - $Global:UpdateMailSettingsCalled | Should Be $true + $Global:SPDscUpdateMailSettingsCalled | Should Be $true } } - } -} \ No newline at end of file + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPPasswordChangeSettings.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPPasswordChangeSettings.Tests.ps1 index 1f934b427..88be36c38 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPPasswordChangeSettings.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPPasswordChangeSettings.Tests.ps1 @@ -1,49 +1,53 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPPasswordChangeSettings" -$ModuleName = "MSFT_SPPasswordChangeSettings" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPPasswordChangeSettings - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - MailAddress = "e@mail.com" - DaysBeforeExpiry = 7 - PasswordChangeWaitTimeSeconds = 60 - - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue + # Test contexts + Context -Name "No local SharePoint farm is available" { + $testParams = @{ + MailAddress = "e@mail.com" + DaysBeforeExpiry = 7 + PasswordChangeWaitTimeSeconds = 60 + } - Context "No local SharePoint farm is available" { - Mock Get-SPFarm { return $null } + Mock -CommandName Get-SPFarm -MockWith { + return $null + } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should be $false } } - Context "There is a local SharePoint farm and the properties are set correctly" { - Mock Get-SPFarm { + Context -Name "There is a local SharePoint farm and the properties are set correctly" { + $testParams = @{ + MailAddress = "e@mail.com" + DaysBeforeExpiry = 7 + PasswordChangeWaitTimeSeconds = 60 + } + + Mock -CommandName Get-SPFarm -MockWith { return @{ PasswordChangeEmailAddress = "e@mail.com" DaysBeforePasswordExpirationToSendEmail = 7 @@ -52,49 +56,53 @@ Describe "SPPasswordChangeSettings - SharePoint Build $((Get-Item $SharePointCmd } } - It "returns farm properties from the get method" { + It "Should return farm properties from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - - Context "There is a local SharePoint farm and the properties are not set correctly" { - Mock Get-SPFarm { + Context -Name "There is a local SharePoint farm and the properties are not set correctly" { + $testParams = @{ + MailAddress = "e@mail.com" + DaysBeforeExpiry = 7 + PasswordChangeWaitTimeSeconds = 60 + } + + Mock -CommandName Get-SPFarm -MockWith { $result = @{ - PasswordChangeEmailAddress = ""; + PasswordChangeEmailAddress = "" PasswordChangeGuardTime = 0 PasswordChangeMaximumTries = 0 DaysBeforePasswordExpirationToSendEmail = 0 } $result = $result | Add-Member ScriptMethod Update { - $Global:SPFarmUpdateCalled = $true; + $Global:SPDscFarmUpdateCalled = $true return $true; } -PassThru return $result } - It "returns farm properties from the get method" { + It "Should return farm properties from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "calls the new and set methods from the set function" { - $Global:SPFarmUpdateCalled = $false; + It "Should call the new and set methods from the set function" { + $Global:SPDscFarmUpdateCalled = $false Set-TargetResource @testParams Assert-MockCalled Get-SPFarm - $Global:SPFarmUpdateCalled | Should Be $true + $Global:SPDscFarmUpdateCalled | Should Be $true } } + } +} - - - } -} \ No newline at end of file +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPPerformancePointServiceApp.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPPerformancePointServiceApp.Tests.ps1 index af9d0d90c..330f50b2a 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPPerformancePointServiceApp.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPPerformancePointServiceApp.Tests.ps1 @@ -1,143 +1,208 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPPerformancePointServiceApp" -$ModuleName = "MSFT_SPPerformancePointServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPPerformancePointServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Test Performance Point App" - ApplicationPool = "Test App Pool" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } + #Initialize tests + $getTypeFullName = "Microsoft.PerformancePoint.Scorecards.BIMonitoringServiceApplication" - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Mock Remove-SPServiceApplication { } + # Mocks for all contexts + Mock -CommandName Remove-SPServiceApplication -MockWith { } + Mock -CommandName Get-SPServiceApplication -MockWith { return $null } + Mock -CommandName New-SPPerformancePointServiceApplication -MockWith { } + Mock -CommandName New-SPPerformancePointServiceApplicationProxy -MockWith { } - Context "When no service applications exist in the current farm" { - - Mock Get-SPServiceApplication { return $null } - Mock New-SPPerformancePointServiceApplication { } - Mock New-SPPerformancePointServiceApplicationProxy { } + # Test contexts + Context -Name "When no service applications exist in the current farm" -Fixture { + $testParams = @{ + Name = "Test Performance Point App" + ApplicationPool = "Test App Pool" + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPPerformancePointServiceApplication } } - Context "When service applications exist in the current farm but the specific Performance Point app does not" { + Context -Name "When service applications exist in the current farm but the specific Performance Point app does not" -Fixture { + $testParams = @{ + Name = "Test Performance Point App" + ApplicationPool = "Test App Pool" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = "Microsoft.Office.UnKnownWebServiceApplication" + } + } -PassThru -Force + return $spServiceApp + } - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Some other service app type" - }) } + It "Should return null from the Get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Absent" + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } } - Context "When a service application exists and is configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ - TypeName = "PerformancePoint Service Application" - DisplayName = $testParams.Name - ApplicationPool = @{ Name = $testParams.ApplicationPool } - }) + Context -Name "When a service application exists and is configured correctly" -Fixture { + $testParams = @{ + Name = "Test Performance Point App" + ApplicationPool = "Test App Pool" } - It "returns present from the get method" { + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + TypeName = "PerformancePoint Service Application" + DisplayName = $testParams.Name + ApplicationPool = @{ + Name = $testParams.ApplicationPool + } + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = $getTypeFullName + } + } -PassThru -Force + return $spServiceApp + } + + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } - Context "When a service application exists and is not configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ - TypeName = "PerformancePoint Service Application" - DisplayName = $testParams.Name - ApplicationPool = @{ Name = "Wrong App Pool Name" } - }) + Context -Name "When a service application exists and is not configured correctly" -Fixture { + $testParams = @{ + Name = "Test Performance Point App" + ApplicationPool = "Test App Pool" } - Mock Get-SPServiceApplicationPool { return @{ Name = $testParams.ApplicationPool } } - It "returns false when the Test method is called" { + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + TypeName = "Access Services Web Service Application" + DisplayName = $testParams.Name + DatabaseServer = $testParams.DatabaseName + ApplicationPool = @{ Name = "Wrong app pool name" } + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = $getTypeFullName + } + } -PassThru -Force + return $spServiceApp + } + + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return @{ + Name = $testParams.ApplicationPool + } + } + + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "calls the update service app cmdlet from the set method" { + It "Should call the update service app cmdlet from the set method" { Set-TargetResource @testParams - Assert-MockCalled Get-SPServiceApplicationPool } } - $testParams = @{ - Name = "Test App" - ApplicationPool = "-" - Ensure = "Absent" - } - Context "When the service application exists but it shouldn't" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When the service application exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "PerformancePoint Service Application" DisplayName = $testParams.Name - ApplicationPool = @{ Name = $testParams.ApplicationPool } - }) + ApplicationPool = @{ Name = "Wrong App Pool Name" } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns present from the Get method" { + It "Should return present from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "calls the remove service application cmdlet in the set method" { + It "Should call the remove service application cmdlet in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplication } } - Context "When the serivce application doesn't exist and it shouldn't" { - Mock Get-SPServiceApplication { return $null } + Context -Name "When the serivce application doesn't exist and it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPProductUpdate.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPProductUpdate.Tests.ps1 index 7322c73e1..2ef6aca24 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPProductUpdate.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPProductUpdate.Tests.ps1 @@ -1,81 +1,136 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPProductUpdate" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Mocks for all contexts + Mock -CommandName Test-Path { + return $true + } + + Mock -CommandName Get-Service -MockWith { + $service = @{ + Status = "Running" + } + $service = $service | Add-Member -MemberType ScriptMethod ` + -Name Stop ` + -Value { + return $null + } -PassThru + $service = $service | Add-Member -MemberType ScriptMethod ` + -Name Start ` + -Value { + return $null + } -PassThru + $service = $service | Add-Member -MemberType ScriptMethod ` + -Name WaitForStatus ` + -Value { + return $null + } -PassThru + return $service + } + + Mock -CommandName Set-Service { + return $null + } -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule + Mock -CommandName Start-Process { + return @{ + ExitCode = 0 + } + } -$ModuleName = "MSFT_SPProductUpdate" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\Modules\SharePointDsc.Util\SharePointDsc.Util.psm1") -Force + Mock -CommandName Get-SPDSCRegistryKey -MockWith { + if ($Value -eq "SetupType") + { + return "CLEAN_INSTALL" + } -Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" - ShutdownServices = $true - Ensure = "Present" + if ($Value -eq "LanguagePackInstalled") + { + return 0 + } } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - $versionBeingTested = (Get-Item $Global:CurrentSharePointStubModule).Directory.BaseName - $majorBuildNumber = $versionBeingTested.Substring(0, $versionBeingTested.IndexOf(".")) - Mock Get-SPDSCAssemblyVersion { return $majorBuildNumber } - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + + Mock -CommandName Get-SPDscFarmVersionInfo -MockWith { + return @{ + Lowest = $Global:SPDscHelper.CurrentStubBuildNumber + } } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Context "Specified update file not found" { - Mock Test-Path { return $false } - - It "should throw exception in the get method" { + + # Test contexts + Context -Name "Specified update file not found" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Present" + } + + Mock -CommandName Test-Path -MockWith { + return $false + } + + It "Should throw exception in the get method" { { Get-TargetResource @testParams } | Should Throw "Setup file cannot be found." } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should Throw "Setup file cannot be found." } - It "should throw exception in the test method" { + It "Should throw exception in the test method" { { Test-TargetResource @testParams } | Should Throw "Setup file cannot be found." } } - Context "Ensure is set to Absent" { - Mock Test-Path { return $false } + Context -Name "Ensure is set to Absent" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Absent" + } - It "should throw exception in the get method" { - { Get-TargetResource @testParams } | Should Throw "Setup file cannot be found." + It "Should throw exception in the get method" { + { Get-TargetResource @testParams } | Should Throw "SharePoint does not support uninstalling updates." } - It "should throw exception in the set method" { - { Set-TargetResource @testParams } | Should Throw "Setup file cannot be found." + It "Should throw exception in the set method" { + { Set-TargetResource @testParams } | Should Throw "SharePoint does not support uninstalling updates." } - It "should throw exception in the test method" { - { Test-TargetResource @testParams } | Should Throw "Setup file cannot be found." + It "Should throw exception in the test method" { + { Test-TargetResource @testParams } | Should Throw "SharePoint does not support uninstalling updates." } } - Context "Update CU has lower version, update not required" { - Mock Test-Path { - return $true + Context -Name "Update CU has lower version, update not required" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Present" } - Mock Get-ItemProperty { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-ItemProperty -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @{ VersionInfo = @{ - FileVersion = $versionBeingTested + FileVersion = $Global:SPDscHelper.CurrentStubBuildNumber FileDescription = "Cumulative Update" } Name = "serverlpksp2013-kb2880554-fullfile-x64-en-us.exe" @@ -85,43 +140,16 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule { return @{ VersionInfo = @{ - FileVersion = $versionBeingTested + FileVersion = $Global:SPDscHelper.CurrentStubBuildNumber FileDescription = "Cumulative Update" } Name = "serverlpksp2016-kb2880554-fullfile-x64-en-us.exe" } } } - - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { - if ($Value -eq "SetupType") - { - return "CLEAN_INSTALL" - } - - if ($Value -eq "LanguagePackInstalled") - { - return 0 - } - } - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013") } @@ -130,56 +158,26 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule return @("Microsoft SharePoint Server 2016") } } - - Mock Get-SPDscFarmVersionInfo { - return @{ - Lowest = $versionBeingTested - } - } - - Mock Get-Service { - $service = @{ - Status = "Running" - } - $service = $service | Add-Member ScriptMethod Stop { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod Start { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod WaitForStatus { - return $null - } -PassThru - return $service - } - - Mock Set-Service { - return $null - } - Mock Start-Process { - return @{ - ExitCode = 0 - } - } - - It "should return Ensure is Present from the get method" { + It "Should return Ensure is Present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Present" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Update CU has higher version, update executed successfully" { - Mock Test-Path { - return $true + Context -Name "Update CU has higher version, update executed successfully" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Present" } - - Mock Get-ItemProperty { - if ($majorBuildNumber -eq 15) + + Mock -CommandName Get-ItemProperty -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @{ VersionInfo = @{ @@ -200,36 +198,9 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule } } } - - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { - if ($Value -eq "SetupType") - { - return "CLEAN_INSTALL" - } - - if ($Value -eq "LanguagePackInstalled") - { - return 0 - } - } - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013") } @@ -238,61 +209,31 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule return @("Microsoft SharePoint Server 2016") } } - - Mock Get-SPDscFarmVersionInfo { - return @{ - Lowest = $versionBeingTested - } - } - - Mock Get-Service { - $service = @{ - Status = "Running" - } - $service = $service | Add-Member ScriptMethod Stop { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod Start { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod WaitForStatus { - return $null - } -PassThru - return $service - } - - Mock Set-Service { - return $null - } - - Mock Start-Process { - return @{ - ExitCode = 0 - } - } - It "should return Ensure is Present from the get method" { + It "Should return Ensure is Present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should run the Start-Process function in the set method" { + It "Should run the Start-Process function in the set method" { Set-TargetResource @testParams Assert-MockCalled Start-Process } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "Update CU has higher version, update executed, reboot required" { - Mock Test-Path { - return $true + Context -Name "Update CU has higher version, update executed, reboot required" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Present" } - Mock Get-ItemProperty { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-ItemProperty -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @{ VersionInfo = @{ @@ -313,36 +254,9 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule } } } - - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { - if ($Value -eq "SetupType") - { - return "CLEAN_INSTALL" - } - - if ($Value -eq "LanguagePackInstalled") - { - return 0 - } - } - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013") } @@ -351,61 +265,37 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule return @("Microsoft SharePoint Server 2016") } } - - Mock Get-SPDscFarmVersionInfo { - return @{ - Lowest = $versionBeingTested - } - } - Mock Get-Service { - $service = @{ - Status = "Running" - } - $service = $service | Add-Member ScriptMethod Stop { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod Start { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod WaitForStatus { - return $null - } -PassThru - return $service - } - - Mock Set-Service { - return $null - } - - Mock Start-Process { + Mock -CommandName Start-Process { return @{ ExitCode = 17022 } } - It "should return Ensure is Present from the get method" { + It "Should return Ensure is Present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should run the Start-Process function in the set method" { + It "Should run the Start-Process function in the set method" { Set-TargetResource @testParams Assert-MockCalled Start-Process } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "Update CU has higher version, update executed, which failed" { - Mock Test-Path { - return $true + Context -Name "Update CU has higher version, update executed, which failed" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Present" } - Mock Get-ItemProperty { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-ItemProperty -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @{ VersionInfo = @{ @@ -427,35 +317,8 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule } } - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { - if ($Value -eq "SetupType") - { - return "CLEAN_INSTALL" - } - - if ($Value -eq "LanguagePackInstalled") - { - return 0 - } - } - - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013") } @@ -464,65 +327,41 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule return @("Microsoft SharePoint Server 2016") } } - - Mock Get-SPDscFarmVersionInfo { - return @{ - Lowest = $versionBeingTested - } - } - - Mock Get-Service { - $service = @{ - Status = "Running" - } - $service = $service | Add-Member ScriptMethod Stop { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod Start { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod WaitForStatus { - return $null - } -PassThru - return $service - } - Mock Set-Service { - return $null - } - - Mock Start-Process { + Mock -CommandName Start-Process { return @{ ExitCode = 1 } } - It "should return Ensure is Present from the get method" { + It "Should return Ensure is Present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should run the Start-Process function in the set method" { + It "Should run the Start-Process function in the set method" { { Set-TargetResource @testParams } | Should Throw "SharePoint update install failed, exit code was 1" Assert-MockCalled Start-Process } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "Update SP has lower version, update not required" { - Mock Test-Path { - return $true + Context -Name "Update SP has lower version, update not required" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Present" } - Mock Get-ItemProperty { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-ItemProperty -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @{ VersionInfo = @{ - FileVersion = $versionBeingTested + FileVersion = $Global:SPDscHelper.CurrentStubBuildNumber FileDescription = "Service Pack" } Name = "serverlpksp2013-kb2880554-fullfile-x64-en-us.exe" @@ -532,7 +371,7 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule { return @{ VersionInfo = @{ - FileVersion = $versionBeingTested + FileVersion = $Global:SPDscHelper.CurrentStubBuildNumber FileDescription = "Service Pack" } Name = "serverlpksp2016-kb2880554-fullfile-x64-en-us.exe" @@ -540,35 +379,8 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule } } - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { - if ($Value -eq "SetupType") - { - return "CLEAN_INSTALL" - } - - if ($Value -eq "LanguagePackInstalled") - { - return 0 - } - } - - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013") } @@ -577,56 +389,26 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule return @("Microsoft SharePoint Server 2016") } } - - Mock Get-SPDscFarmVersionInfo { - return @{ - Lowest = $versionBeingTested - } - } - - Mock Get-Service { - $service = @{ - Status = "Running" - } - $service = $service | Add-Member ScriptMethod Stop { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod Start { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod WaitForStatus { - return $null - } -PassThru - return $service - } - - Mock Set-Service { - return $null - } - - Mock Start-Process { - return @{ - ExitCode = 0 - } - } - It "should return Ensure is Present from the get method" { + It "Should return Ensure is Present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Present" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Update SP has higher version, update executed" { - Mock Test-Path { - return $true + Context -Name "Update SP has higher version, update executed" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Present" } - Mock Get-ItemProperty { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-ItemProperty -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @{ VersionInfo = @{ @@ -648,35 +430,8 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule } } - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { - if ($Value -eq "SetupType") - { - return "CLEAN_INSTALL" - } - - if ($Value -eq "LanguagePackInstalled") - { - return 0 - } - } - - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013") } @@ -685,65 +440,35 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule return @("Microsoft SharePoint Server 2016") } } - - Mock Get-SPDscFarmVersionInfo { - return @{ - Lowest = $versionBeingTested - } - } - Mock Get-Service { - $service = @{ - Status = "Running" - } - $service = $service | Add-Member ScriptMethod Stop { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod Start { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod WaitForStatus { - return $null - } -PassThru - return $service - } - - Mock Set-Service { - return $null - } - - Mock Start-Process { - return @{ - ExitCode = 0 - } - } - - It "should return Ensure is Present from the get method" { + It "Should return Ensure is Present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should run the Start-Process function in the set method" { + It "Should run the Start-Process function in the set method" { Set-TargetResource @testParams Assert-MockCalled Start-Process } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "Update SP for LP has lower version, update not required" { - Mock Test-Path { - return $true + Context -Name "Update SP for LP has lower version, update not required" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Present" } - Mock Get-ItemProperty { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-ItemProperty -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @{ VersionInfo = @{ - FileVersion = $versionBeingTested + FileVersion = $Global:SPDscHelper.CurrentStubBuildNumber FileDescription = "Service Pack Language Pack" } Name = "serverlpksp2013-kb2880554-fullfile-x64-nl-nl.exe" @@ -753,7 +478,7 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule { return @{ VersionInfo = @{ - FileVersion = $versionBeingTested + FileVersion = $Global:SPDscHelper.CurrentStubBuildNumber FileDescription = "Service Pack Language Pack" } Name = "serverlpksp2016-kb2880554-fullfile-x64-nl-nl.exe" @@ -761,35 +486,8 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule } } - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { - if ($Value -eq "SetupType") - { - return "CLEAN_INSTALL" - } - - if ($Value -eq "LanguagePackInstalled") - { - return 0 - } - } - - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013", "Language Pack for SharePoint and Project Server 2013 - Dutch/Nederlands") } @@ -798,56 +496,26 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule return @("Microsoft SharePoint Server 2016", "Language Pack for SharePoint and Project Server 2016 - Dutch/Nederlands") } } - - Mock Get-SPDscFarmVersionInfo { - return @{ - Lowest = $versionBeingTested - } - } - - Mock Get-Service { - $service = @{ - Status = "Running" - } - $service = $service | Add-Member ScriptMethod Stop { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod Start { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod WaitForStatus { - return $null - } -PassThru - return $service - } - Mock Set-Service { - return $null - } - - Mock Start-Process { - return @{ - ExitCode = 0 - } - } - - It "should return Ensure is Present from the get method" { + It "Should return Ensure is Present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Present" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Update SP for LP has higher version, update required" { - Mock Test-Path { - return $true + Context -Name "Update SP for LP has higher version, update required" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Present" } - - Mock Get-ItemProperty { - if ($majorBuildNumber -eq 15) + + Mock -CommandName Get-ItemProperty -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @{ VersionInfo = @{ @@ -869,35 +537,8 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule } } - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { - if ($Value -eq "SetupType") - { - return "CLEAN_INSTALL" - } - - if ($Value -eq "LanguagePackInstalled") - { - return 0 - } - } - - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013", "Language Pack for SharePoint and Project Server 2013 - Dutch/Nederlands") } @@ -906,61 +547,31 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule return @("Microsoft SharePoint Server 2016", "Language Pack for SharePoint and Project Server 2016 - Dutch/Nederlands") } } - - Mock Get-SPDscFarmVersionInfo { - return @{ - Lowest = $versionBeingTested - } - } - - Mock Get-Service { - $service = @{ - Status = "Running" - } - $service = $service | Add-Member ScriptMethod Stop { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod Start { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod WaitForStatus { - return $null - } -PassThru - return $service - } - - Mock Set-Service { - return $null - } - - Mock Start-Process { - return @{ - ExitCode = 0 - } - } - It "should return Ensure is Present from the get method" { + It "Should return Ensure is Present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should run the Start-Process function in the set method" { + It "Should run the Start-Process function in the set method" { Set-TargetResource @testParams Assert-MockCalled Start-Process } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "Update SP LP does not have language in the name, throws exception" { - Mock Test-Path { - return $true + Context -Name "Update SP LP does not have language in the name, throws exception" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Present" } - Mock Get-ItemProperty { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-ItemProperty -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @{ VersionInfo = @{ @@ -982,35 +593,8 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule } } - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { - if ($Value -eq "SetupType") - { - return "CLEAN_INSTALL" - } - - if ($Value -eq "LanguagePackInstalled") - { - return 0 - } - } - - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013", "Language Pack for SharePoint and Project Server 2013 - Dutch/Nederlands") } @@ -1019,51 +603,21 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule return @("Microsoft SharePoint Server 2016", "Language Pack for SharePoint and Project Server 2016 - Dutch/Nederlands") } } - - Mock Get-SPDscFarmVersionInfo { - return @{ - Lowest = $versionBeingTested - } - } - - Mock Get-Service { - $service = @{ - Status = "Running" - } - $service = $service | Add-Member ScriptMethod Stop { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod Start { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod WaitForStatus { - return $null - } -PassThru - return $service - } - - Mock Set-Service { - return $null - } - Mock Start-Process { - return @{ - ExitCode = 0 - } - } - - It "should throw exception in the get method" { + It "Should throw exception in the get method" { { Get-TargetResource @testParams } | Should Throw "Update does not contain the language code in the correct format." } } - Context "Update SP LP has unknown language in the name, throws exception" { - Mock Test-Path { - return $true + Context -Name "Update SP LP has unknown language in the name, throws exception" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Present" } - Mock Get-ItemProperty { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-ItemProperty -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @{ VersionInfo = @{ @@ -1085,35 +639,8 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule } } - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { - if ($Value -eq "SetupType") - { - return "CLEAN_INSTALL" - } - - if ($Value -eq "LanguagePackInstalled") - { - return 0 - } - } - - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013", "Language Pack for SharePoint and Project Server 2013 - Dutch/Nederlands") } @@ -1122,51 +649,21 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule return @("Microsoft SharePoint Server 2016", "Language Pack for SharePoint and Project Server 2016 - Dutch/Nederlands") } } - - Mock Get-SPDscFarmVersionInfo { - return @{ - Lowest = $versionBeingTested - } - } - - Mock Get-Service { - $service = @{ - Status = "Running" - } - $service = $service | Add-Member ScriptMethod Stop { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod Start { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod WaitForStatus { - return $null - } -PassThru - return $service - } - Mock Set-Service { - return $null - } - - Mock Start-Process { - return @{ - ExitCode = 0 - } - } - - It "should throw exception in the get method" { + It "Should throw exception in the get method" { { Get-TargetResource @testParams } | Should Throw "Error while converting language information:" } } - Context "Update SP LP specified language is not installed, throws exception" { - Mock Test-Path { - return $true + Context -Name "Update SP LP specified language is not installed, throws exception" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Present" } - Mock Get-ItemProperty { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-ItemProperty -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @{ VersionInfo = @{ @@ -1188,35 +685,8 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule } } - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { - if ($Value -eq "SetupType") - { - return "CLEAN_INSTALL" - } - - if ($Value -eq "LanguagePackInstalled") - { - return 0 - } - } - - Mock Get-SPDscFarmProductsInfo { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-SPDscFarmProductsInfo -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @("Microsoft SharePoint Server 2013", "Language Pack for SharePoint and Project Server 2013 - Dutch/Nederlands") } @@ -1225,51 +695,21 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule return @("Microsoft SharePoint Server 2016", "Language Pack for SharePoint and Project Server 2016 - Dutch/Nederlands") } } - - Mock Get-SPDscFarmVersionInfo { - return @{ - Lowest = $versionBeingTested - } - } - - Mock Get-Service { - $service = @{ - Status = "Running" - } - $service = $service | Add-Member ScriptMethod Stop { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod Start { - return $null - } -PassThru - $service = $service | Add-Member ScriptMethod WaitForStatus { - return $null - } -PassThru - return $service - } - - Mock Set-Service { - return $null - } - - Mock Start-Process { - return @{ - ExitCode = 0 - } - } - It "should throw exception in the get method" { + It "Should throw exception in the get method" { { Get-TargetResource @testParams } | Should Throw "Error: Product for language fr-fr is not found." } } - Context "Upgrade pending - Skipping install" { - Mock Test-Path { - return $true + Context -Name "Upgrade pending - Skipping install" -Fixture { + $testParams = @{ + SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" + ShutdownServices = $true + Ensure = "Present" } - Mock Get-ItemProperty { - if ($majorBuildNumber -eq 15) + Mock -CommandName Get-ItemProperty -MockWith { + if ($Global:SPDscHelper.CurrentStubBuildNumber.Major -eq 15) { return @{ VersionInfo = @{ @@ -1291,22 +731,7 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule } } - Mock Get-SPDSCInstalledProductVersion { - if ($majorBuildNumber -eq 15) - { - return @{ - FileMajorPart = 15 - } - } - else - { - return @{ - FileMajorPart = 16 - } - } - } - - Mock Get-SPDSCRegistryKey { + Mock -CommandName Get-SPDSCRegistryKey -MockWith { if ($Value -eq "SetupType") { return "CLEAN_INSTALL" @@ -1318,12 +743,12 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule } } - It "should return null from the set method" { + It "Should return null from the set method" { Set-TargetResource @testParams | Should BeNullOrEmpty } } - Context "BinaryInstallDays outside range" { + Context -Name "BinaryInstallDays outside range" -Fixture { $testParams = @{ SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" ShutdownServices = $true @@ -1331,22 +756,18 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule Ensure = "Present" } - Mock Test-Path { - return $true - } - $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should return null from the set method" { + It "Should return null from the set method" { Set-TargetResource @testParams | Should BeNullOrEmpty } } - Context "BinaryInstallTime outside range" { + Context -Name "BinaryInstallTime outside range" -Fixture { $testParams = @{ SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" ShutdownServices = $true @@ -1355,22 +776,18 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule Ensure = "Present" } - Mock Test-Path { - return $true - } - $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should return null from the set method" { + It "Should return null from the set method" { Set-TargetResource @testParams | Should BeNullOrEmpty } } - Context "BinaryInstallTime incorrectly formatted, too many arguments" { + Context -Name "BinaryInstallTime incorrectly formatted, too many arguments" -Fixture { $testParams = @{ SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" ShutdownServices = $true @@ -1379,22 +796,18 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule Ensure = "Present" } - Mock Test-Path { - return $true - } - $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should Throw "Time window incorrectly formatted." } } - Context "BinaryInstallTime incorrectly formatted, incorrect start time" { + Context -Name "BinaryInstallTime incorrectly formatted, incorrect start time" -Fixture { $testParams = @{ SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" ShutdownServices = $true @@ -1403,22 +816,18 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule Ensure = "Present" } - Mock Test-Path { - return $true - } - $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should Throw "Error converting start time" } } - Context "BinaryInstallTime incorrectly formatted, incorrect end time" { + Context -Name "BinaryInstallTime incorrectly formatted, incorrect end time" -Fixture { $testParams = @{ SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" ShutdownServices = $true @@ -1427,22 +836,18 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule Ensure = "Present" } - Mock Test-Path { - return $true - } - $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should Throw "Error converting end time" } } - Context "BinaryInstallTime start time larger than end time" { + Context -Name "BinaryInstallTime start time larger than end time" -Fixture { $testParams = @{ SetupFile = "C:\Install\CUMay2016\ubersrv2013-kb3115029-fullfile-x64-glb.exe" ShutdownServices = $true @@ -1451,19 +856,17 @@ Describe "SPProductUpdate - SharePoint Build $((Get-Item $SharePointCmdletModule Ensure = "Present" } - Mock Test-Path { - return $true - } - $testDate = Get-Date -Day 17 -Month 7 -Year 2016 -Hour 12 -Minute 00 -Second 00 - Mock Get-Date { + Mock -CommandName Get-Date -MockWith { return $testDate } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should Throw "Error: Start time cannot be larger than end time" } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPPublishServiceApplication.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPPublishServiceApplication.Tests.ps1 index decf0fbb5..9f918b3cb 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPPublishServiceApplication.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPPublishServiceApplication.Tests.ps1 @@ -29,19 +29,19 @@ Describe "SPPublishServiceApplication - SharePoint Build $((Get-Item $SharePoint Mock Publish-SPServiceApplication { } Mock Unpublish-SPServiceApplication { } - Context "An invalid service application is specified to be published" { - Mock Get-SPServiceApplication { + Context -Name "An invalid service application is specified to be published" { + Mock -CommandName Get-SPServiceApplication { $spServiceApp = [pscustomobject]@{ Name = $testParams.Name Uri = $null } return $spServiceApp } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } @@ -50,8 +50,8 @@ Describe "SPPublishServiceApplication - SharePoint Build $((Get-Item $SharePoint } } - Context "The service application is not published but should be" { - Mock Get-SPServiceApplication { + Context -Name "The service application is not published but should be" { + Mock -CommandName Get-SPServiceApplication { $spServiceApp = [pscustomobject]@{ Name = $testParams.Name Uri = "urn:schemas-microsoft-com:sharepoint:service:mmsid" @@ -60,11 +60,11 @@ Describe "SPPublishServiceApplication - SharePoint Build $((Get-Item $SharePoint return $spServiceApp } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } @@ -75,8 +75,8 @@ Describe "SPPublishServiceApplication - SharePoint Build $((Get-Item $SharePoint } } - Context "The service application is published and should be" { - Mock Get-SPServiceApplication { + Context -Name "The service application is published and should be" { + Mock -CommandName Get-SPServiceApplication { $spServiceApp = [pscustomobject]@{ Name = $testParams.Name Uri = "urn:schemas-microsoft-com:sharepoint:service:mmsid" @@ -85,23 +85,23 @@ Describe "SPPublishServiceApplication - SharePoint Build $((Get-Item $SharePoint return $spServiceApp } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The service application specified does not exist" { - Mock Get-SPServiceApplication { return $null } + Context -Name "The service application specified does not exist" { + Mock -CommandName Get-SPServiceApplication { return $null } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } @@ -112,8 +112,8 @@ Describe "SPPublishServiceApplication - SharePoint Build $((Get-Item $SharePoint $testParams.Ensure = "Absent" - Context "The service application is not published and should not be" { - Mock Get-SPServiceApplication { + Context -Name "The service application is not published and should not be" { + Mock -CommandName Get-SPServiceApplication { $spServiceApp = [pscustomobject]@{ Name = $testParams.Name Uri = "urn:schemas-microsoft-com:sharepoint:service:mmsid" @@ -122,17 +122,17 @@ Describe "SPPublishServiceApplication - SharePoint Build $((Get-Item $SharePoint return $spServiceApp } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The service application is published and should not be" { - Mock Get-SPServiceApplication { + Context -Name "The service application is published and should not be" { + Mock -CommandName Get-SPServiceApplication { $spServiceApp = [pscustomobject]@{ Name = $testParams.Name Uri = "urn:schemas-microsoft-com:sharepoint:service:mmsid" @@ -141,11 +141,11 @@ Describe "SPPublishServiceApplication - SharePoint Build $((Get-Item $SharePoint return $spServiceApp } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPQuotaTemplate.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPQuotaTemplate.Tests.ps1 index 65bf1faa8..544c875b7 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPQuotaTemplate.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPQuotaTemplate.Tests.ps1 @@ -1,56 +1,82 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPQuotaTemplate" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPQuotaTemplate - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Test" - StorageMaxInMB = 1024 - StorageWarningInMB = 512 - MaximumUsagePointsSolutions = 1000 - WarningUsagePointsSolutions = 800 - Ensure = "Present" +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPQuotaTemplate" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Initialize tests + Add-Type -TypeDefinition @" + namespace Microsoft.SharePoint.Administration + { + public class SPQuotaTemplate + { + public string Name { get; set; } + public long StorageMaximumLevel { get; set; } + public long StorageWarningLevel { get; set; } + public double UserCodeMaximumLevel { get; set; } + public double UserCodeWarningLevel { get; set; } } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + } +"@ + + # Mocks for all contexts + Mock -CommandName Get-SPFarm -MockWith { + return @{} } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Add-Type -TypeDefinition "namespace Microsoft.SharePoint.Administration { public class SPQuotaTemplate { public string Name { get; set; } public long StorageMaximumLevel { get; set; } public long StorageWarningLevel { get; set; } public double UserCodeMaximumLevel { get; set; } public double UserCodeWarningLevel { get; set; }}}" + # Test contexts + Context -Name "The server is not part of SharePoint farm" -Fixture { + $testParams = @{ + Name = "Test" + StorageMaxInMB = 1024 + StorageWarningInMB = 512 + MaximumUsagePointsSolutions = 1000 + WarningUsagePointsSolutions = 800 + Ensure = "Present" + } - Context "The server is not part of SharePoint farm" { - Mock Get-SPFarm { throw "Unable to detect local farm" } + Mock -CommandName Get-SPFarm -MockWith { + throw "Unable to detect local farm" + } - It "return null from the get method" { + It "Should return null from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws an exception in the set method to say there is no local farm" { + It "Should throw an exception in the set method to say there is no local farm" { { Set-TargetResource @testParams } | Should throw "No local SharePoint farm was detected" } } - Context "The server is in a farm and the incorrect settings have been applied to the template" { - Mock Get-SPDSCContentService { + Context -Name "The server is in a farm and the incorrect settings have been applied to the template" -Fixture { + $testParams = @{ + Name = "Test" + StorageMaxInMB = 1024 + StorageWarningInMB = 512 + MaximumUsagePointsSolutions = 1000 + WarningUsagePointsSolutions = 800 + Ensure = "Present" + } + + Mock -CommandName Get-SPDSCContentService -MockWith { $quotaTemplates = @(@{ Test = @{ StorageMaximumLevel = 512 @@ -61,67 +87,87 @@ Describe "SPQuotaTemplate - SharePoint Build $((Get-Item $SharePointCmdletModule }) $quotaTemplatesCol = {$quotaTemplates}.Invoke() - $contentService = @{ QuotaTemplates = $quotaTemplatesCol } - $contentService = $contentService | Add-Member ScriptMethod Update { $Global:SPDSCQuotaTemplatesUpdated = $true } -PassThru + $contentService = $contentService | Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value { + $Global:SPDscQuotaTemplatesUpdated = $true + } -PassThru return $contentService } - Mock Get-SPFarm { return @{} } - - It "return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPDSCQuotaTemplatesUpdated = $false - It "updates the quota template settings" { + $Global:SPDscQuotaTemplatesUpdated = $false + It "Should update the quota template settings" { Set-TargetResource @testParams - $Global:SPDSCQuotaTemplatesUpdated | Should Be $true + $Global:SPDscQuotaTemplatesUpdated | Should Be $true } } - Context "The server is in a farm and the template doesn't exist" { - Mock Get-SPDSCContentService { + Context -Name "The server is in a farm and the template doesn't exist" -Fixture { + $testParams = @{ + Name = "Test" + StorageMaxInMB = 1024 + StorageWarningInMB = 512 + MaximumUsagePointsSolutions = 1000 + WarningUsagePointsSolutions = 800 + Ensure = "Present" + } + + Mock -CommandName Get-SPDSCContentService -MockWith { $quotaTemplates = @(@{ Test = $null }) $quotaTemplatesCol = {$quotaTemplates}.Invoke() - $contentService = @{ QuotaTemplates = $quotaTemplatesCol } - $contentService = $contentService | Add-Member ScriptMethod Update { $Global:SPDSCQuotaTemplatesUpdated = $true } -PassThru + $contentService = $contentService | Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value { + $Global:SPDscQuotaTemplatesUpdated = $true + } -PassThru return $contentService } - Mock Get-SPFarm { return @{} } - - It "return values from the get method" { + It "Should return values from the get method" { (Get-TargetResource @testParams).Ensure | Should Be 'Absent' } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPDSCQuotaTemplatesUpdated = $false - It "creates a new quota template" { + $Global:SPDscQuotaTemplatesUpdated = $false + It "Should create a new quota template" { Set-TargetResource @testParams - $Global:SPDSCQuotaTemplatesUpdated | Should Be $true + $Global:SPDscQuotaTemplatesUpdated | Should Be $true } } - Context "The server is in a farm and the correct settings have been applied" { - Mock Get-SPDSCContentService { + Context -Name "The server is in a farm and the correct settings have been applied" -Fixture { + $testParams = @{ + Name = "Test" + StorageMaxInMB = 1024 + StorageWarningInMB = 512 + MaximumUsagePointsSolutions = 1000 + WarningUsagePointsSolutions = 800 + Ensure = "Present" + } + + Mock -CommandName Get-SPDSCContentService -MockWith { $returnVal = @{ QuotaTemplates = @{ Test = @{ @@ -132,23 +178,26 @@ Describe "SPQuotaTemplate - SharePoint Build $((Get-Item $SharePointCmdletModule } } } - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCQuotaTemplatesUpdated = $true } -PassThru + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value { + $Global:SPDscQuotaTemplatesUpdated = $true + } -PassThru return $returnVal } - - Mock Get-SPFarm { return @{} } - - It "return values from the get method" { + It "Should return values from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be 'Present' $result.StorageMaxInMB | Should Be 1024 } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPRemoteFarmTrust.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPRemoteFarmTrust.Tests.ps1 index 3d147b173..505fddba9 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPRemoteFarmTrust.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPRemoteFarmTrust.Tests.ps1 @@ -1,165 +1,179 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPRemoteFarmTrust" -$ModuleName = "MSFT_SPRemoteFarmTrust" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPRemoteFarmTrust - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "SendingFarm" - LocalWebAppUrl = "https://sharepoint.adventureworks.com" - RemoteWebAppUrl = "https://sharepoint.contoso.com" - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Get-SPSite { + # Mocks for all contexts + Mock -CommandName Get-SPSite -MockWith { return @{ Url = $Identity } } - Mock Get-SPServiceContext { + Mock -CommandName Get-SPServiceContext { return @{ Site = $Site } } - Mock Get-SPAuthenticationRealm { + Mock -CommandName Get-SPAuthenticationRealm { return "14757a87-4d74-4323-83b9-fb1e77e8f22f" } - Mock Get-SPAppPrincipal { + Mock -CommandName Get-SPAppPrincipal { return @{ Site = $Site } } - Mock Set-SPAuthenticationRealm {} - Mock Set-SPAppPrincipalPermission {} - Mock Remove-SPAppPrincipalPermission {} - Mock Remove-SPTrustedRootAuthority {} - Mock Remove-SPTrustedSecurityTokenIssuer {} - Mock New-SPTrustedSecurityTokenIssuer { + Mock -CommandName Set-SPAuthenticationRealm {} + Mock -CommandName Set-SPAppPrincipalPermission {} + Mock -CommandName Remove-SPAppPrincipalPermission {} + Mock -CommandName Remove-SPTrustedRootAuthority {} + Mock -CommandName Remove-SPTrustedSecurityTokenIssuer {} + Mock -CommandName New-SPTrustedSecurityTokenIssuer { return @{ NameId = "f5a433c7-69f9-48ef-916b-dde8b5fa6fdb@14757a87-4d74-4323-83b9-fb1e77e8f22f" } } - Mock New-SPTrustedRootAuthority { + Mock -CommandName New-SPTrustedRootAuthority { return @{ NameId = "f5a433c7-69f9-48ef-916b-dde8b5fa6fdb@14757a87-4d74-4323-83b9-fb1e77e8f22f" } } + # Test contexts + Context -Name "A remote farm trust doesn't exist, but should" -Fixture { + $testParams = @{ + Name = "SendingFarm" + LocalWebAppUrl = "https://sharepoint.adventureworks.com" + RemoteWebAppUrl = "https://sharepoint.contoso.com" + Ensure = "Present" + } - Context "A remote farm trust doesn't exist, but should" { - - Mock Get-SPTrustedSecurityTokenIssuer { + Mock -CommandName Get-SPTrustedSecurityTokenIssuer -MockWith { return $null } - Mock Get-SPTrustedRootAuthority { + Mock -CommandName Get-SPTrustedRootAuthority -MockWith { return $null } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "adds the trust in the set method" { + It "Should add the trust in the set method" { Set-TargetResource @testParams Assert-MockCalled -CommandName New-SPTrustedSecurityTokenIssuer Assert-MockCalled -CommandName New-SPTrustedRootAuthority } } - Context "A remote farm trust exists and should" { + Context -Name "A remote farm trust exists and should" -Fixture { + $testParams = @{ + Name = "SendingFarm" + LocalWebAppUrl = "https://sharepoint.adventureworks.com" + RemoteWebAppUrl = "https://sharepoint.contoso.com" + Ensure = "Present" + } - Mock Get-SPTrustedSecurityTokenIssuer { + Mock -CommandName Get-SPTrustedSecurityTokenIssuer -MockWith { return @( @{ NameId = "f5a433c7-69f9-48ef-916b-dde8b5fa6fdb@14757a87-4d74-4323-83b9-fb1e77e8f22f" } ) } - Mock Get-SPTrustedRootAuthority { + Mock -CommandName Get-SPTrustedRootAuthority -MockWith { return @{ NameId = "f5a433c7-69f9-48ef-916b-dde8b5fa6fdb@14757a87-4d74-4323-83b9-fb1e77e8f22f" } } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - $testParams.Ensure = "Absent" - - Context "A remote farm trust exists and shouldn't" { + Context -Name "A remote farm trust exists and shouldn't" -Fixture { + $testParams = @{ + Name = "SendingFarm" + LocalWebAppUrl = "https://sharepoint.adventureworks.com" + RemoteWebAppUrl = "https://sharepoint.contoso.com" + Ensure = "Absent" + } - Mock Get-SPTrustedSecurityTokenIssuer { + Mock -CommandName Get-SPTrustedSecurityTokenIssuer -MockWith { return @( @{ NameId = "f5a433c7-69f9-48ef-916b-dde8b5fa6fdb@14757a87-4d74-4323-83b9-fb1e77e8f22f" } ) } - Mock Get-SPTrustedRootAuthority { + Mock -CommandName Get-SPTrustedRootAuthority -MockWith { return @{ NameId = "f5a433c7-69f9-48ef-916b-dde8b5fa6fdb@14757a87-4d74-4323-83b9-fb1e77e8f22f" } } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "removes the trust in the set method" { + It "Should remove the trust in the set method" { Set-TargetResource @testParams Assert-MockCalled -CommandName Remove-SPTrustedSecurityTokenIssuer Assert-MockCalled -CommandName Remove-SPTrustedRootAuthority } } - Context "A remote farm trust doesn't exist and shouldn't" { + Context -Name "A remote farm trust doesn't exist and shouldn't" -Fixture { + $testParams = @{ + Name = "SendingFarm" + LocalWebAppUrl = "https://sharepoint.adventureworks.com" + RemoteWebAppUrl = "https://sharepoint.contoso.com" + Ensure = "Absent" + } - Mock Get-SPTrustedSecurityTokenIssuer { + Mock -CommandName Get-SPTrustedSecurityTokenIssuer -MockWith { return $null } - Mock Get-SPTrustedRootAuthority { + Mock -CommandName Get-SPTrustedRootAuthority -MockWith { return $null } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchContentSource.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchContentSource.Tests.ps1 index a46f18a97..84e4fe8b1 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchContentSource.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchContentSource.Tests.ps1 @@ -1,30 +1,24 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPSearchContentSource" -$ModuleName = "MSFT_SPSearchContentSource" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPSearchContentSource - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - Mock Start-Sleep {} - Mock Set-SPEnterpriseSearchCrawlContentSource {} - Mock Remove-SPEnterpriseSearchCrawlContentSource {} - + # Initialize tests Add-Type -TypeDefinition @" namespace Microsoft.Office.Server.Search.Administration { [System.Flags] @@ -60,9 +54,13 @@ namespace Microsoft.Office.Server.Search.Administration { } "@ + # Mocks for all contexts + Mock -CommandName Start-Sleep -MockWith {} + Mock -CommandName Set-SPEnterpriseSearchCrawlContentSource -MockWith {} + Mock -CommandName Remove-SPEnterpriseSearchCrawlContentSource -MockWith {} - - Context "A SharePoint content source doesn't exist but should" { + # Test contexts + Context -Name "A SharePoint content source doesn't exist but should" { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -71,10 +69,12 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Present" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return $null } - Mock New-SPEnterpriseSearchCrawlContentSource { + + Mock -CommandName New-SPEnterpriseSearchCrawlContentSource -MockWith { return @{ Type = "SharePoint" SharePointCrawlBehavior = "CrawlVirtualServers" @@ -91,16 +91,16 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return absent from the get method" { + It "Should return absent from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should create the content source in the set method" { + It "Should create the content source in the set method" { Set-TargetResource @testParams Assert-MockCalled -CommandName New-SPEnterpriseSearchCrawlContentSource @@ -108,7 +108,7 @@ namespace Microsoft.Office.Server.Search.Administration { } } - Context "A SharePoint content source does exist and should" { + Context -Name "A SharePoint content source does exist and should" { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -117,7 +117,7 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Present" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return @{ Type = "SharePoint" SharePointCrawlBehavior = "CrawlVirtualServers" @@ -134,17 +134,17 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return present from the get method" { + It "Should return present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Present" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "A SharePoint content source does exist and shouldn't" { + Context -Name "A SharePoint content source does exist and shouldn't" { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -153,7 +153,7 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Absent" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return @{ Type = "SharePoint" SharePointCrawlBehavior = "CrawlVirtualServers" @@ -170,23 +170,23 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return present from the get method" { + It "Should return present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the content source in the set method" { + It "Should remove the content source in the set method" { Set-TargetResource @testParams Assert-MockCalled -CommandName Remove-SPEnterpriseSearchCrawlContentSource } } - Context "A SharePoint content source doesn't exist and shouldn't" { + Context -Name "A SharePoint content source doesn't exist and shouldn't" { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -195,21 +195,21 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Absent" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return $null } - It "should return absent from the get method" { + It "Should return absent from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "A SharePoint source that uses continuous crawl has incorrect settings applied" { + Context -Name "A SharePoint source that uses continuous crawl has incorrect settings applied" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -219,7 +219,7 @@ namespace Microsoft.Office.Server.Search.Administration { ContinuousCrawl = $true Ensure = "Present" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return @{ Type = "SharePoint" SharePointCrawlBehavior = "CrawlVirtualServers" @@ -236,19 +236,23 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should disable continuous crawl and then re-enable it when updating the content source" { + It "Should disable continuous crawl and then re-enable it when updating the content source" { Set-TargetResource @testParams - Assert-MockCalled -CommandName Set-SPEnterpriseSearchCrawlContentSource -ParameterFilter { $EnableContinuousCrawls -eq $false } - Assert-MockCalled -CommandName Set-SPEnterpriseSearchCrawlContentSource -ParameterFilter { $EnableContinuousCrawls -eq $true } + Assert-MockCalled -CommandName Set-SPEnterpriseSearchCrawlContentSource -ParameterFilter { + $EnableContinuousCrawls -eq $false + } + Assert-MockCalled -CommandName Set-SPEnterpriseSearchCrawlContentSource -ParameterFilter { + $EnableContinuousCrawls -eq $true + } } } - Context "A website content source doesn't exist but should" { + Context -Name "A website content source doesn't exist but should" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -257,10 +261,10 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Present" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return $null } - Mock New-SPEnterpriseSearchCrawlContentSource { + Mock -CommandName New-SPEnterpriseSearchCrawlContentSource -MockWith { return @{ Type = "Web" MaxPageEnumerationDepth = [System.Int32]::MaxValue @@ -277,16 +281,16 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return absent from the get method" { + It "Should return absent from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should create the content source in the set method" { + It "Should create the content source in the set method" { Set-TargetResource @testParams Assert-MockCalled -CommandName New-SPEnterpriseSearchCrawlContentSource @@ -294,7 +298,7 @@ namespace Microsoft.Office.Server.Search.Administration { } } - Context "A website content source does exist and should" { + Context -Name "A website content source does exist and should" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -303,7 +307,7 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Present" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return @{ Type = "Web" MaxPageEnumerationDepth = [System.Int32]::MaxValue @@ -320,18 +324,17 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return present from the get method" { + It "Should return present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Present" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "A website content source does exist and shouldn't" { - + Context -Name "A website content source does exist and shouldn't" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -340,7 +343,8 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Absent" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return @{ Type = "Web" MaxPageEnumerationDepth = [System.Int32]::MaxValue @@ -357,23 +361,23 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return present from the get method" { + It "Should return present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the content source in the set method" { + It "Should remove the content source in the set method" { Set-TargetResource @testParams Assert-MockCalled -CommandName Remove-SPEnterpriseSearchCrawlContentSource } } - Context "A website content source doesn't exist and shouldn't" { + Context -Name "A website content source doesn't exist and shouldn't" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -382,21 +386,22 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Absent" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return $null } - It "should return absent from the get method" { + It "Should return absent from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "A website content source has incorrect crawl depth settings applied" { + Context -Name "A website content source has incorrect crawl depth settings applied" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -405,7 +410,8 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Present" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return @{ Type = "Web" MaxPageEnumerationDepth = 0 @@ -422,18 +428,18 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should update the settings in the set method" { + It "Should update the settings in the set method" { Set-TargetResource @testParams Assert-MockCalled -CommandName Set-SPEnterpriseSearchCrawlContentSource } } - Context "A file share content source doesn't exist but should" { + Context -Name "A file share content source doesn't exist but should" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -442,10 +448,10 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Present" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return $null } - Mock New-SPEnterpriseSearchCrawlContentSource { + Mock -CommandName New-SPEnterpriseSearchCrawlContentSource -MockWith { return @{ Type = "File" FollowDirectories = $true @@ -461,16 +467,16 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return absent from the get method" { + It "Should return absent from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should create the content source in the set method" { + It "Should create the content source in the set method" { Set-TargetResource @testParams Assert-MockCalled -CommandName New-SPEnterpriseSearchCrawlContentSource @@ -478,7 +484,7 @@ namespace Microsoft.Office.Server.Search.Administration { } } - Context "A file share content source does exist and should" { + Context -Name "A file share content source does exist and should" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -487,7 +493,8 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Present" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return @{ Type = "File" FollowDirectories = $true @@ -503,17 +510,17 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return present from the get method" { + It "Should return present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Present" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "A file share content source does exist and shouldn't" { + Context -Name "A file share content source does exist and shouldn't" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -522,7 +529,8 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Absent" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return @{ Type = "File" FollowDirectories = $true @@ -538,23 +546,23 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return present from the get method" { + It "Should return present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the content source in the set method" { + It "Should remove the content source in the set method" { Set-TargetResource @testParams Assert-MockCalled -CommandName Remove-SPEnterpriseSearchCrawlContentSource } } - Context "A file share content source doesn't exist and shouldn't" { + Context -Name "A file share content source doesn't exist and shouldn't" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -563,21 +571,21 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Absent" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return $null } - It "should return absent from the get method" { + It "Should return absent from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Absent" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "A file share content source has incorrect crawl depth settings applied" { + Context -Name "A file share content source has incorrect crawl depth settings applied" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -586,7 +594,7 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlSetting = "CrawlEverything" Ensure = "Present" } - Mock Get-SPEnterpriseSearchCrawlContentSource { + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { return @{ Type = "File" FollowDirectories = $false @@ -602,18 +610,18 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should update the settings in the set method" { + It "Should update the settings in the set method" { Set-TargetResource @testParams Assert-MockCalled -CommandName Set-SPEnterpriseSearchCrawlContentSource } } - Context "A content source has a full schedule that does not match the desired schedule" { + Context -Name "A content source has a full schedule that does not match the desired schedule" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -629,7 +637,8 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlScheduleRepeatInterval = "5" } -ClientOnly) } - Mock Get-SPEnterpriseSearchCrawlContentSource { + + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { $schedule = New-Object -TypeName Microsoft.Office.Server.Search.Administration.DailySchedule $schedule.RepeatDuration = 1439 $schedule.RepeatInterval = 5 @@ -652,17 +661,17 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should update the schedule in the set method" { + It "Should update the schedule in the set method" { Set-TargetResource @testParams Assert-MockCalled -CommandName Set-SPEnterpriseSearchCrawlContentSource -ParameterFilter { $ScheduleType -eq "Full" } } } - Context "A content source has a full schedule that does match the desired schedule" { + Context -Name "A content source has a full schedule that does match the desired schedule" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -678,7 +687,8 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlScheduleRepeatInterval = "5" } -ClientOnly) } - Mock Get-SPEnterpriseSearchCrawlContentSource { + + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { $schedule = New-Object -TypeName Microsoft.Office.Server.Search.Administration.DailySchedule $schedule.RepeatDuration = 1440 $schedule.RepeatInterval = 5 @@ -701,12 +711,12 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "A content source has a incremental schedule that does not match the desired schedule" { + Context -Name "A content source has a incremental schedule that does not match the desired schedule" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -721,7 +731,8 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlScheduleDaysOfWeek = @("Monday", "Wednesday") } -ClientOnly) } - Mock Get-SPEnterpriseSearchCrawlContentSource { + + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { $schedule = New-Object -TypeName Microsoft.Office.Server.Search.Administration.WeeklySchedule $schedule.StartHour = 0 $schedule.StartMinute = 0 @@ -742,17 +753,17 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should update the schedule in the set method" { + It "Should update the schedule in the set method" { Set-TargetResource @testParams Assert-MockCalled -CommandName Set-SPEnterpriseSearchCrawlContentSource -ParameterFilter { $ScheduleType -eq "Incremental" } } } - Context "A content source has a incremental schedule that does match the desired schedule" { + Context -Name "A content source has a incremental schedule that does match the desired schedule" -Fixture { $testParams = @{ Name = "Example content source" ServiceAppName = "Search Service Application" @@ -767,7 +778,8 @@ namespace Microsoft.Office.Server.Search.Administration { CrawlScheduleDaysOfWeek = @("Monday", "Wednesday", "Friday") } -ClientOnly) } - Mock Get-SPEnterpriseSearchCrawlContentSource { + + Mock -CommandName Get-SPEnterpriseSearchCrawlContentSource -MockWith { $schedule = New-Object -TypeName Microsoft.Office.Server.Search.Administration.WeeklySchedule $schedule.StartHour = 0 $schedule.StartMinute = 0 @@ -788,9 +800,11 @@ namespace Microsoft.Office.Server.Search.Administration { } } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } } -} \ No newline at end of file +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchCrawlRule.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchCrawlRule.Tests.ps1 index 3f78ffd8f..5b3451a40 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchCrawlRule.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchCrawlRule.Tests.ps1 @@ -1,41 +1,48 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPSearchCrawlRule" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPSearchCrawlRule - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Path = "http://www.contoso.com" - ServiceAppName = "Search Service Application" - RuleType = "InclusionRule" - CrawlConfigurationRules = "FollowLinksNoPageCrawl","CrawlComplexUrls", "CrawlAsHTTP" - AuthenticationType = "DefaultRuleAccess" - Ensure = "Present" +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPSearchCrawlRule" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Initialize tests + $getTypeFullName = "Microsoft.Office.Server.Search.Administration.SearchServiceApplication" + + # Mocks for all contexts + Mock -CommandName Remove-SPEnterpriseSearchCrawlRule -MockWith {} + Mock -CommandName New-SPEnterpriseSearchCrawlRule -MockWith {} + Mock -CommandName Set-SPEnterpriseSearchCrawlRule -MockWith {} + + Mock -CommandName Get-SPServiceApplication -MockWith { + return @( + New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name FullName ` + -Value $getTypeFullName ` + -PassThru + } ` + -PassThru -Force) } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Remove-SPEnterpriseSearchCrawlRule {} - Mock New-SPEnterpriseSearchCrawlRule {} - Mock Set-SPEnterpriseSearchCrawlRule {} - - Context "AuthenticationType=CertificateRuleAccess specified, but CertificateName missing" { + + # Test contexts + Context -Name "AuthenticationType=CertificateRuleAccess specified, but CertificateName missing" -Fixture { $testParams = @{ Path = "http://www.contoso.com" ServiceAppName = "Search Service Application" @@ -43,25 +50,21 @@ Describe "SPSearchCrawlRule - SharePoint Build $((Get-Item $SharePointCmdletModu AuthenticationType = "CertificateRuleAccess" Ensure = "Present" } - - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Search Service Application" - }) } - It "returns null from the Get method" { + It "Should return null from the Get method" { { Get-TargetResource @testParams } | Should throw "When AuthenticationType=CertificateRuleAccess, the parameter CertificateName is required" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { { Test-TargetResource @testParams } | Should throw "When AuthenticationType=CertificateRuleAccess, the parameter CertificateName is required" } - It "throws exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should throw "When AuthenticationType=CertificateRuleAccess, the parameter CertificateName is required" } } - Context "CertificateName specified, but AuthenticationType is not CertificateRuleAccess" { + Context -Name "CertificateName specified, but AuthenticationType is not CertificateRuleAccess" -Fixture { $testParams = @{ Path = "http://www.contoso.com" ServiceAppName = "Search Service Application" @@ -70,25 +73,21 @@ Describe "SPSearchCrawlRule - SharePoint Build $((Get-Item $SharePointCmdletModu CertificateName = "Test Certificate" Ensure = "Present" } - - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Search Service Application" - }) } - It "returns null from the Get method" { + It "Should return null from the Get method" { { Get-TargetResource @testParams } | Should throw "When specifying CertificateName, the AuthenticationType parameter is required" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { { Test-TargetResource @testParams } | Should throw "When specifying CertificateName, the AuthenticationType parameter is required" } - It "throws exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should throw "When specifying CertificateName, the AuthenticationType parameter is required" } } - Context " AuthenticationType=NTLMAccountRuleAccess and AuthenticationCredentialsparameters not specified" { + Context -Name " AuthenticationType=NTLMAccountRuleAccess and AuthenticationCredentialsparameters not specified" -Fixture { $testParams = @{ Path = "http://www.contoso.com" ServiceAppName = "Search Service Application" @@ -96,25 +95,21 @@ Describe "SPSearchCrawlRule - SharePoint Build $((Get-Item $SharePointCmdletModu AuthenticationType = "NTLMAccountRuleAccess" Ensure = "Present" } - - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Search Service Application" - }) } - It "returns null from the Get method" { + It "Should return null from the Get method" { { Get-TargetResource @testParams } | Should throw "When AuthenticationType is NTLMAccountRuleAccess or BasicAccountRuleAccess, the parameter AuthenticationCredentials is required" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { { Test-TargetResource @testParams } | Should throw "When AuthenticationType is NTLMAccountRuleAccess or BasicAccountRuleAccess, the parameter AuthenticationCredentials is required" } - It "throws exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should throw "When AuthenticationType is NTLMAccountRuleAccess or BasicAccountRuleAccess, the parameter AuthenticationCredentials is required" } } - Context "AuthenticationCredentials parameters, but AuthenticationType is not NTLMAccountRuleAccess or BasicAccountRuleAccess" { + Context -Name "AuthenticationCredentials parameters, but AuthenticationType is not NTLMAccountRuleAccess or BasicAccountRuleAccess" -Fixture { $User = "Domain01\User01" $PWord = ConvertTo-SecureString -String "P@sSwOrd" -AsPlainText -Force $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord @@ -128,24 +123,20 @@ Describe "SPSearchCrawlRule - SharePoint Build $((Get-Item $SharePointCmdletModu Ensure = "Present" } - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Search Service Application" - }) } - - It "returns null from the Get method" { + It "Should return null from the Get method" { { Get-TargetResource @testParams } | Should throw "When specifying AuthenticationCredentials, the AuthenticationType parameter is required" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { { Test-TargetResource @testParams } | Should throw "When specifying AuthenticationCredentials, the AuthenticationType parameter is required" } - It "throws exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should throw "When specifying AuthenticationCredentials, the AuthenticationType parameter is required" } } - Context "ExclusionRule only with CrawlConfigurationRules=CrawlComplexUrls" { + Context -Name "ExclusionRule only with CrawlConfigurationRules=CrawlComplexUrls" -Fixture { $testParams = @{ Path = "http://www.contoso.com" ServiceAppName = "Search Service Application" @@ -155,24 +146,20 @@ Describe "SPSearchCrawlRule - SharePoint Build $((Get-Item $SharePointCmdletModu Ensure = "Present" } - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Search Service Application" - }) } - - It "returns null from the Get method" { + It "Should return null from the Get method" { { Get-TargetResource @testParams } | Should throw "When RuleType=ExclusionRule, CrawlConfigurationRules cannot contain the values FollowLinksNoPageCrawl or CrawlAsHTTP" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { { Test-TargetResource @testParams } | Should throw "When RuleType=ExclusionRule, CrawlConfigurationRules cannot contain the values FollowLinksNoPageCrawl or CrawlAsHTTP" } - It "throws exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should throw "When RuleType=ExclusionRule, CrawlConfigurationRules cannot contain the values FollowLinksNoPageCrawl or CrawlAsHTTP" } } - Context "ExclusionRule cannot be used with AuthenticationCredentials, CertificateName or AuthenticationType parameters" { + Context -Name "ExclusionRule cannot be used with AuthenticationCredentials, CertificateName or AuthenticationType parameters" -Fixture { $testParams = @{ Path = "http://www.contoso.com" ServiceAppName = "Search Service Application" @@ -181,65 +168,89 @@ Describe "SPSearchCrawlRule - SharePoint Build $((Get-Item $SharePointCmdletModu RuleType = "ExclusionRule" Ensure = "Present" } - - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Search Service Application" - }) } - It "returns null from the Get method" { + It "Should return null from the Get method" { { Get-TargetResource @testParams } | Should throw "When Type=ExclusionRule, parameters AuthenticationCredentials, CertificateName or AuthenticationType are not allowed" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { { Test-TargetResource @testParams } | Should throw "When Type=ExclusionRule, parameters AuthenticationCredentials, CertificateName or AuthenticationType are not allowed" } - It "throws exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should throw "When Type=ExclusionRule, parameters AuthenticationCredentials, CertificateName or AuthenticationType are not allowed" } } - Context "When no service applications exist in the current farm" { + Context -Name "When no service applications exist in the current farm" -Fixture { + $testParams = @{ + Path = "http://www.contoso.com" + ServiceAppName = "Search Service Application" + RuleType = "InclusionRule" + CrawlConfigurationRules = "FollowLinksNoPageCrawl","CrawlComplexUrls", "CrawlAsHTTP" + AuthenticationType = "DefaultRuleAccess" + Ensure = "Present" + } - Mock Get-SPServiceApplication { return $null } + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPEnterpriseSearchCrawlRule } } - Context "When service applications exist in the current farm but the specific search app does not" { + Context -Name "When service applications exist in the current farm but the specific search app does not" -Fixture { + $testParams = @{ + Path = "http://www.contoso.com" + ServiceAppName = "Search Service Application" + RuleType = "InclusionRule" + CrawlConfigurationRules = "FollowLinksNoPageCrawl","CrawlComplexUrls", "CrawlAsHTTP" + AuthenticationType = "DefaultRuleAccess" + Ensure = "Present" + } - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Some other service app type" - }) } + Mock -CommandName Get-SPServiceApplication -MockWith { + return @(@{ + TypeName = "Some other service app type" + }) + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPEnterpriseSearchCrawlRule } } - Context "When a crawl rule exists and is configured correctly" { + Context -Name "When a crawl rule exists and is configured correctly" -Fixture { + $testParams = @{ + Path = "http://www.contoso.com" + ServiceAppName = "Search Service Application" + RuleType = "InclusionRule" + CrawlConfigurationRules = "FollowLinksNoPageCrawl","CrawlComplexUrls", "CrawlAsHTTP" + AuthenticationType = "DefaultRuleAccess" + Ensure = "Present" + } - Mock Get-SPEnterpriseSearchCrawlRule { return @{ + Mock -CommandName Get-SPEnterpriseSearchCrawlRule -MockWith { return @{ Path = "http://www.contoso.com" Type = "InclusionRule" SuppressIndexing = $true @@ -248,22 +259,27 @@ Describe "SPSearchCrawlRule - SharePoint Build $((Get-Item $SharePointCmdletModu AuthenticationType = "DefaultRuleAccess" } } - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Search Service Application" - }) } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } - Context "When a crawl rule exists, but isn't configured correctly" { + Context -Name "When a crawl rule exists, but isn't configured correctly" -Fixture { + $testParams = @{ + Path = "http://www.contoso.com" + ServiceAppName = "Search Service Application" + RuleType = "InclusionRule" + CrawlConfigurationRules = "FollowLinksNoPageCrawl","CrawlComplexUrls", "CrawlAsHTTP" + AuthenticationType = "DefaultRuleAccess" + Ensure = "Present" + } - Mock Get-SPEnterpriseSearchCrawlRule { return @{ + Mock -CommandName Get-SPEnterpriseSearchCrawlRule -MockWith { return @{ Path = "http://www.contoso.com" Type = "InclusionRule" SuppressIndexing = $false @@ -272,23 +288,22 @@ Describe "SPSearchCrawlRule - SharePoint Build $((Get-Item $SharePointCmdletModu AuthenticationType = "DefaultRuleAccess" } } - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Search Service Application" - }) } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "calls the update service app cmdlet from the set method" { + It "Should call the update service app cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Set-SPEnterpriseSearchCrawlRule } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchIndexPartition.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchIndexPartition.Tests.ps1 index 8e4d82f3b..05bcff9dc 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchIndexPartition.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchIndexPartition.Tests.ps1 @@ -1,56 +1,68 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPSearchIndexPartition" -$ModuleName = "MSFT_SPSearchIndexPartition" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPSearchIndexPartition - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Index = "0" - Servers = @($env:COMPUTERNAME) - RootDirectory = "C:\SearchIndex\0" - ServiceAppName = "Search Service Application" + # Initialize tests + Add-Type -TypeDefinition @" + public class IndexComponent + { + public string ServerName { get; set; } + public System.Guid ComponentId {get; set;} + public System.Int32 IndexPartitionOrdinal {get; set;} } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue +"@ + $indexComponent = New-Object -TypeName IndexComponent + $indexComponent.ServerName = $env:COMPUTERNAME + $indexComponent.IndexPartitionOrdinal = 0 - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - Mock New-PSSession { + # Mocks for all contexts + Mock -CommandName New-PSSession -MockWith { return $null } - Mock New-Item { return @{} } - Mock Start-Sleep {} - Mock Get-SPEnterpriseSearchServiceApplication { + Mock -CommandName New-Item -MockWith { + return @{} + } + Mock -CommandName Start-Sleep -MockWith {} + Mock -CommandName Get-SPEnterpriseSearchServiceApplication -MockWith { return @{ ActiveTopology = @{} } } - Mock New-SPEnterpriseSearchTopology { return @{} } + Mock -CommandName New-SPEnterpriseSearchTopology -MockWith { + return @{} + } - $Global:SPDSCSearchRoleInstanceCallCount = 0 - Mock Get-SPEnterpriseSearchServiceInstance { - if ($Global:SPDSCSearchRoleInstanceCallCount -eq 2) { - $Global:SPDSCSearchRoleInstanceCallCount = 0 + $Global:SPDscSearchRoleInstanceCallCount = 0 + Mock -CommandName Get-SPEnterpriseSearchServiceInstance -MockWith { + if ($Global:SPDscSearchRoleInstanceCallCount -eq 2) + { + $Global:SPDscSearchRoleInstanceCallCount = 0 return @{ Server = @{ Address = $env:COMPUTERNAME } Status = "Online" } - } else { - $Global:SPDSCSearchRoleInstanceCallCount++ + } + else + { + $Global:SPDscSearchRoleInstanceCallCount++ return @{ Server = @{ Address = $env:COMPUTERNAME @@ -59,67 +71,93 @@ Describe "SPSearchIndexPartition - SharePoint Build $((Get-Item $SharePointCmdle } } } - Mock Start-SPEnterpriseSearchServiceInstance { return $null } - Mock New-SPEnterpriseSearchIndexComponent { return $null } - Mock Remove-SPEnterpriseSearchComponent { return $null } - Mock Set-SPEnterpriseSearchTopology { return $null } + Mock -CommandName Start-SPEnterpriseSearchServiceInstance -MockWith { + return $null + } + Mock -CommandName New-SPEnterpriseSearchIndexComponent -MockWith { + return $null + } + Mock -CommandName Remove-SPEnterpriseSearchComponent -MockWith { + return $null + } + Mock -CommandName Set-SPEnterpriseSearchTopology -MockWith { + return $null + } - Add-Type -TypeDefinition "public class IndexComponent { public string ServerName { get; set; } public System.Guid ComponentId {get; set;} public System.Int32 IndexPartitionOrdinal {get; set;}}" - $indexComponent = New-Object IndexComponent - $indexComponent.ServerName = $env:COMPUTERNAME - $indexComponent.IndexPartitionOrdinal = 0 - - Context "Search index doesn't exist and it should" { - Mock Get-SPEnterpriseSearchComponent { return @() } - $Global:SPDSCSearchRoleInstanceCallCount = 0 + # Test contexts + Context -Name "Search index doesn't exist and it should" { + $testParams = @{ + Index = "0" + Servers = @($env:COMPUTERNAME) + RootDirectory = "C:\SearchIndex\0" + ServiceAppName = "Search Service Application" + } - It "returns an empty server list from the get method" { + Mock -CommandName Get-SPEnterpriseSearchComponent { + return @() + } + + $Global:SPDscSearchRoleInstanceCallCount = 0 + + It "Should return an empty server list from the get method" { $result = Get-TargetResource @testParams $result.Servers | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "creates the search index in the set method" { + It "Should create the search index in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPEnterpriseSearchIndexComponent } } - Context "Search index does exist and it should" { - Mock Get-SPEnterpriseSearchComponent { return @($indexComponent) } + Context -Name "Search index does exist and it should" { + $testParams = @{ + Index = "0" + Servers = @($env:COMPUTERNAME) + RootDirectory = "C:\SearchIndex\0" + ServiceAppName = "Search Service Application" + } + + Mock -CommandName Get-SPEnterpriseSearchComponent -MockWith { + return @($indexComponent) + } - It "returns present from the get method" { + It "Should return present from the get method" { $result = Get-TargetResource @testParams $result.Servers | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - $testParams.Servers = @("SharePoint2") - - Context "Search index exists and it shouldn't" { - Mock Get-SPEnterpriseSearchComponent { - Add-Type -TypeDefinition "public class IndexComponent { public string ServerName { get; set; } public System.Guid ComponentId {get; set;} public System.Int32 IndexPartitionOrdinal {get; set;}}" - $indexComponent = New-Object IndexComponent - $indexComponent.ServerName = $env:COMPUTERNAME - $indexComponent.IndexPartitionOrdinal = 0 + Context -Name "Search index exists and it shouldn't" { + $testParams = @{ + Index = "0" + Servers = @("SharePoint2") + RootDirectory = "C:\SearchIndex\0" + ServiceAppName = "Search Service Application" + } + + Mock -CommandName Get-SPEnterpriseSearchComponent -MockWith { return @($indexComponent) } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "removes the search index in the set method" { + It "Should remove the search index in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPEnterpriseSearchComponent } } } -} \ No newline at end of file +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchResultSource.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchResultSource.Tests.ps1 index 8297d87b2..4dd5fc88c 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchResultSource.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchResultSource.Tests.ps1 @@ -1,35 +1,24 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPSearchresultSource" -$ModuleName = "MSFT_SPSearchresultSource" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPSearchresultSource - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Test source" - SearchServiceAppName = "Search Service Application" - ProviderType = "Remote SharePoint Provider" - Query = "{searchTerms}" - ConnectionUrl = "https://sharepoint.contoso.com" - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + # Initialize tests Add-Type -TypeDefinition @" namespace Microsoft.Office.Server.Search.Administration { @@ -38,15 +27,18 @@ Describe "SPSearchresultSource - SharePoint Build $((Get-Item $SharePointCmdletM } } "@ - - Mock Get-SPEnterpriseSearchServiceApplication { + + # Mocks for all contexts + Mock -CommandName Get-SPEnterpriseSearchServiceApplication { return @{ SearchCenterUrl = "http://example.sharepoint.com/pages" } } - Mock Get-SPWeb { + + Mock -CommandName Get-SPWeb -MockWith { return @{} } + $Global:SPDscResultSourceProvicers = @( @{ Id = "c1e2843d-1825-4a37-ad15-dce5d50f46d2" @@ -74,7 +66,7 @@ Describe "SPSearchresultSource - SharePoint Build $((Get-Item $SharePointCmdletM } ) - Mock New-Object { + Mock -CommandName New-Object { switch ($TypeName) { "Microsoft.Office.Server.Search.Administration.SearchObjectOwner" { return [System.Object]::new() @@ -117,26 +109,43 @@ Describe "SPSearchresultSource - SharePoint Build $((Get-Item $SharePointCmdletM -Value { } } } - } - - Context "A search result source doesn't exist and should" { + } + # Test contexts + Context -Name "A search result source doesn't exist and should" -Fixture { + $testParams = @{ + Name = "Test source" + SearchServiceAppName = "Search Service Application" + ProviderType = "Remote SharePoint Provider" + Query = "{searchTerms}" + ConnectionUrl = "https://sharepoint.contoso.com" + Ensure = "Present" + } + $Global:SPDscCurrentResultSourceMocks = $null - It "should return absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should create the result source in the set method" { + It "Should create the result source in the set method" { Set-TargetResource @testParams } } - Context "A search result source exists and should" { + Context -Name "A search result source exists and should" -Fixture { + $testParams = @{ + Name = "Test source" + SearchServiceAppName = "Search Service Application" + ProviderType = "Remote SharePoint Provider" + Query = "{searchTerms}" + ConnectionUrl = "https://sharepoint.contoso.com" + Ensure = "Present" + } $Global:SPDscCurrentResultSourceMocks = @{ Name = $testParams.Name @@ -146,18 +155,24 @@ Describe "SPSearchresultSource - SharePoint Build $((Get-Item $SharePointCmdletM ProviderId = "f7a3db86-fb85-40e4-a178-7ad85c732ba6" } - It "should return present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - $testParams.Ensure = "Absent" - - Context "A search result source exists and shouldn't" { + Context -Name "A search result source exists and shouldn't" -Fixture { + $testParams = @{ + Name = "Test source" + SearchServiceAppName = "Search Service Application" + ProviderType = "Remote SharePoint Provider" + Query = "{searchTerms}" + ConnectionUrl = "https://sharepoint.contoso.com" + Ensure = "Absent" + } $Global:SPDscCurrentResultSourceMocks = @{ Name = $testParams.Name @@ -167,30 +182,67 @@ Describe "SPSearchresultSource - SharePoint Build $((Get-Item $SharePointCmdletM ProviderId = "f7a3db86-fb85-40e4-a178-7ad85c732ba6" } - It "should return present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the result source in the set method" { + It "Should remove the result source in the set method" { Set-TargetResource @testParams } } - Context "A search result source doesn't exist and shouldn't" { + Context -Name "A search result source doesn't exist and shouldn't" -Fixture { + $testParams = @{ + Name = "Test source" + SearchServiceAppName = "Search Service Application" + ProviderType = "Remote SharePoint Provider" + Query = "{searchTerms}" + ConnectionUrl = "https://sharepoint.contoso.com" + Ensure = "Absent" + } $Global:SPDscCurrentResultSourceMocks = $null - It "should return absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should be "Absent" } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } + + Context -Name "The search centre site collection does not exist when trying to set a result source" -Fixture { + $testParams = @{ + Name = "Test source" + SearchServiceAppName = "Search Service Application" + ProviderType = "Remote SharePoint Provider" + Query = "{searchTerms}" + ConnectionUrl = "https://sharepoint.contoso.com" + Ensure = "Present" + } + + Mock -CommandName Get-SPWeb -MockWith { + return $null + } + + 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 throw an exception trying to create the result source in the set method" { + { Set-TargetResource @testParams } | Should throw + } + } } -} \ No newline at end of file +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchServiceApp.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchServiceApp.Tests.ps1 index e4f0bcafc..ec1866edf 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchServiceApp.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchServiceApp.Tests.ps1 @@ -1,45 +1,27 @@ [CmdletBinding()] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPSearchServiceApp" -$ModuleName = "MSFT_SPSearchServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Initialize tests + $getTypeFullName = "Microsoft.Office.Server.Search.Administration.SearchServiceApplication" -Describe "SPSearchServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Search Service Application" - ApplicationPool = "SharePoint Search Services" - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Start-SPEnterpriseSearchServiceInstance {} - Mock Remove-SPServiceApplication {} - Mock New-SPEnterpriseSearchServiceApplicationProxy {} - Mock Set-SPEnterpriseSearchServiceApplication {} - Mock Get-SPEnterpriseSearchServiceInstance { return @{} } - Mock New-SPEnterpriseSearchServiceApplication { return @{} } - Mock Get-SPServiceApplicationPool { return @{ Name = $testParams.ApplicationPool } } - - $versionBeingTested = (Get-Item $Global:CurrentSharePointStubModule).Directory.BaseName - $majorBuildNumber = $versionBeingTested.Substring(0, $versionBeingTested.IndexOf(".")) - Mock Get-SPDSCInstalledProductVersion { return @{ FileMajorPart = $majorBuildNumber; FileBuildPart = 0 } } - Add-Type -TypeDefinition @" namespace Microsoft.Office.Server.Search.Administration { public static class SearchContext { @@ -49,70 +31,119 @@ Describe "SPSearchServiceApp - SharePoint Build $((Get-Item $SharePointCmdletMod } } "@ + + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential ` + -ArgumentList @("DOMAIN\username", $mockPassword) - Mock Get-SPWebApplication { return @(@{ + # Mocks for all contexts + Mock -CommandName Start-SPEnterpriseSearchServiceInstance -MockWith {} + Mock -CommandName Remove-SPServiceApplication -MockWith {} + Mock -CommandName New-SPEnterpriseSearchServiceApplicationProxy -MockWith {} + Mock -CommandName Set-SPEnterpriseSearchServiceApplication -MockWith {} + Mock -CommandName New-SPBusinessDataCatalogServiceApplication -MockWith { } + Mock -CommandName Set-SPEnterpriseSearchServiceApplication -MockWith { } + + Mock -CommandName Get-SPEnterpriseSearchServiceInstance -MockWith { + return @{} + } + Mock -CommandName New-SPEnterpriseSearchServiceApplication -MockWith { + return @{} + } + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return @{ + Name = $testParams.ApplicationPool + } + } + Mock -CommandName Get-SPWebapplication -MockWith { + return @(@{ Url = "http://centraladmin.contoso.com" IsAdministrationWebApplication = $true - }) } - Mock Get-SPSite { @{} } - - Mock New-Object { - return @{ - DefaultGatheringAccount = "Domain\username" - } - } -ParameterFilter { $TypeName -eq "Microsoft.Office.Server.Search.Administration.Content" } - - Mock Import-Module {} -ParameterFilter { $_.Name -eq $ModuleName } + }) + } + Mock -CommandName Get-SPSite -MockWith { + @{} + } + Mock -CommandName New-Object -MockWith { + return @{ + DefaultGatheringAccount = "Domain\username" + } + } -ParameterFilter { + $TypeName -eq "Microsoft.Office.Server.Search.Administration.Content" + } + + Mock Import-Module -MockWith {} -ParameterFilter { $_.Name -eq $ModuleName } - Context "When no service applications exist in the current farm" { + # Test contexts + Context -Name "When no service applications exist in the current farm" -Fixture { + $testParams = @{ + Name = "Search Service Application" + ApplicationPool = "SharePoint Search Services" + Ensure = "Present" + } - Mock Get-SPServiceApplication { return $null } + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { - Set-TargetResource @testParams - Assert-MockCalled New-SPEnterpriseSearchServiceApplication - } - - $testParams.Add("InstallAccount", (New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)))) - It "creates a new service application in the set method where InstallAccount is used" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPEnterpriseSearchServiceApplication } - $testParams.Remove("InstallAccount") } - Context "When service applications exist in the current farm but the specific search app does not" { + Context -Name "When service applications exist in the current farm but the specific search app does not" -Fixture { + $testParams = @{ + Name = "Search Service Application" + ApplicationPool = "SharePoint Search Services" + Ensure = "Present" + } - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Some other service app type" - }) } + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = "Microsoft.Office.UnKnownWebServiceApplication" + } + } -PassThru -Force + return $spServiceApp + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPEnterpriseSearchServiceApplication } } - Context "When a service application exists and is configured correctly" { + Context -Name "When a service application exists and is configured correctly" -Fixture { + $testParams = @{ + Name = "Search Service Application" + ApplicationPool = "SharePoint Search Services" + Ensure = "Present" + } - Mock Get-SPServiceApplication { - return @(@{ + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Search Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool } @@ -120,23 +151,32 @@ Describe "SPSearchServiceApp - SharePoint Build $((Get-Item $SharePointCmdletMod Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.Name } } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } - Context "When a service application exists and the app pool is not configured correctly" { + Context -Name "When a service application exists and the app pool is not configured correctly" -Fixture { + $testParams = @{ + Name = "Search Service Application" + ApplicationPool = "SharePoint Search Services" + Ensure = "Present" + } - Mock Get-SPServiceApplication { - return @(@{ + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Search Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = "Wrong App Pool Name" } @@ -144,16 +184,24 @@ Describe "SPSearchServiceApp - SharePoint Build $((Get-Item $SharePointCmdletMod Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - Mock Get-SPServiceApplicationPool { return @{ Name = $testParams.ApplicationPool } } - Mock Set-SPEnterpriseSearchServiceApplication { } - It "returns false when the Test method is called" { + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return @{ + Name = $testParams.ApplicationPool + } + } + + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "calls the update service app cmdlet from the set method" { + It "Should call the update service app cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Get-SPServiceApplicationPool @@ -161,11 +209,16 @@ Describe "SPSearchServiceApp - SharePoint Build $((Get-Item $SharePointCmdletMod } } - $testParams.Add("DefaultContentAccessAccount", (New-Object System.Management.Automation.PSCredential ("DOMAIN\username", (ConvertTo-SecureString "password" -AsPlainText -Force)))) - - Context "When the default content access account does not match" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When the default content access account does not match" -Fixture { + $testParams = @{ + Name = "Search Service Application" + ApplicationPool = "SharePoint Search Services" + Ensure = "Present" + DefaultContentAccessAccount = $mockCredential + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Search Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool } @@ -173,16 +226,22 @@ Describe "SPSearchServiceApp - SharePoint Build $((Get-Item $SharePointCmdletMod Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - Mock New-Object { + Mock -CommandName New-Object -MockWith { return @{ DefaultGatheringAccount = "WRONG\username" } - } -ParameterFilter { $TypeName -eq "Microsoft.Office.Server.Search.Administration.Content" } + } -ParameterFilter { + $TypeName -eq "Microsoft.Office.Server.Search.Administration.Content" + } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } @@ -194,167 +253,235 @@ Describe "SPSearchServiceApp - SharePoint Build $((Get-Item $SharePointCmdletMod } } - Context "When the default content access account does match" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When the default content access account does match" -Fixture { + $testParams = @{ + Name = "Search Service Application" + ApplicationPool = "SharePoint Search Services" + Ensure = "Present" + DefaultContentAccessAccount = $mockCredential + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Search Service Application" DisplayName = $testParams.Name - ApplicationPool = @{ Name = $testParams.ApplicationPool } + ApplicationPool = @{ + Name = $testParams.ApplicationPool + } Database = @{ Name = $testParams.DatabaseName - Server = @{ Name = $testParams.DatabaseServer } + Server = @{ + Name = $testParams.DatabaseServer + } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - Mock New-Object { + Mock -CommandName New-Object -MockWith { return @{ - DefaultGatheringAccount = "Domain\username" + DefaultGatheringAccount = "DOMAIN\username" } - } -ParameterFilter { $TypeName -eq "Microsoft.Office.Server.Search.Administration.Content" } + } -ParameterFilter { + $TypeName -eq "Microsoft.Office.Server.Search.Administration.Content" + } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - $testParams.Add("SearchCenterUrl", "http://search.sp.contoso.com") - $Global:SPDSCSearchURLUpdated = $false - Context "When the search center URL does not match" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When the search center URL does not match" -Fixture { + $testParams = @{ + Name = "Search Service Application" + ApplicationPool = "SharePoint Search Services" + Ensure = "Present" + SearchCenterUrl = "http://search.sp.contoso.com" + } + + $Global:SPDscSearchURLUpdated = $false + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Search Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool } + SearchCenterUrl = "http://wrong.url.here" Database = @{ Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - SearchCenterUrl = "http://wrong.url.here" - } | Add-Member ScriptMethod Update { - $Global:SPDSCSearchURLUpdated = $true - } -PassThru) - } - Mock Get-SPServiceApplicationPool { return @{ Name = $testParams.ApplicationPool } } - Mock Get-SPEnterpriseSearchServiceInstance { return @{} } - Mock New-SPBusinessDataCatalogServiceApplication { } - Mock Start-SPEnterpriseSearchServiceInstance { } - Mock New-SPEnterpriseSearchServiceApplication { return @{} } - Mock New-SPEnterpriseSearchServiceApplicationProxy { } - Mock Set-SPEnterpriseSearchServiceApplication { } + } + $spServiceApp = $spServiceApp | Add-Member ScriptMethod Update { + $Global:SPDscSearchURLUpdated = $true + } -PassThru + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return @{ + Name = $testParams.ApplicationPool + } + } - Mock Get-SPWebApplication { return @(@{ - Url = "http://centraladmin.contoso.com" - IsAdministrationWebApplication = $true - }) } - Mock Get-SPSite { @{} } + Mock -CommandName Get-SPWebapplication -MockWith { + return @(@{ + Url = "http://centraladmin.contoso.com" + IsAdministrationWebApplication = $true + }) + } + + Mock -CommandName Get-SPSite -MockWith { @{} } - Mock New-Object { + Mock -CommandName New-Object -MockWith { return @{ DefaultGatheringAccount = "Domain\username" } - } -ParameterFilter { $TypeName -eq "Microsoft.Office.Server.Search.Administration.Content" } + } -ParameterFilter { + $TypeName -eq "Microsoft.Office.Server.Search.Administration.Content" + } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should update the service app in the set method" { + It "Should update the service app in the set method" { Set-TargetResource @testParams - $Global:SPDSCSearchURLUpdated | Should Be $true + $Global:SPDscSearchURLUpdated | Should Be $true } } - Context "When the search center URL does match" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When the search center URL does match" -Fixture { + $testParams = @{ + Name = "Search Service Application" + ApplicationPool = "SharePoint Search Services" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return @{ + Name = $testParams.ApplicationPool + } + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Search Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool } + SearchCenterUrl = "http://search.sp.contoso.com" Database = @{ Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - SearchCenterUrl = "http://search.sp.contoso.com" - }) - } - Mock Get-SPServiceApplicationPool { return @{ Name = $testParams.ApplicationPool } } - Mock Get-SPEnterpriseSearchServiceInstance { return @{} } - Mock New-SPBusinessDataCatalogServiceApplication { } - Mock Start-SPEnterpriseSearchServiceInstance { } - Mock New-SPEnterpriseSearchServiceApplication { return @{} } - Mock New-SPEnterpriseSearchServiceApplicationProxy { } - Mock Set-SPEnterpriseSearchServiceApplication { } - - Mock Get-SPWebApplication { return @(@{ - Url = "http://centraladmin.contoso.com" - IsAdministrationWebApplication = $true - }) } - Mock Get-SPSite { @{} } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + + Mock -CommandName Get-SPWebapplication -MockWith { + return @(@{ + Url = "http://centraladmin.contoso.com" + IsAdministrationWebApplication = $true + }) + } + + Mock -CommandName Get-SPSite -MockWith { + return @{} + } - Mock New-Object { + Mock -CommandName New-Object { return @{ DefaultGatheringAccount = "Domain\username" } - } -ParameterFilter { $TypeName -eq "Microsoft.Office.Server.Search.Administration.Content" } + } -ParameterFilter { + $TypeName -eq "Microsoft.Office.Server.Search.Administration.Content" + } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - $testParams.Ensure = "Absent" - - Context "When the service app exists but it shouldn't" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When the service app exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "Search Service Application" + ApplicationPool = "SharePoint Search Services" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Search Service Application" DisplayName = $testParams.Name - ApplicationPool = @{ Name = $testParams.ApplicationPool } + ApplicationPool = @{ + Name = $testParams.ApplicationPool + } Database = @{ Name = $testParams.DatabaseName - Server = @{ Name = $testParams.DatabaseServer } + Server = @{ + Name = $testParams.DatabaseServer + } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns present from the Get method" { + It "Should return present from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the service application in the set method" { + It "Should remove the service application in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplication } } - Context "When the service app doesn't exist and shouldn't" { - Mock Get-SPServiceApplication { return $null } + Context -Name "When the service app doesn't exist and shouldn't" -Fixture { + $testParams = @{ + Name = "Search Service Application" + ApplicationPool = "SharePoint Search Services" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - $testParams = @{ - Name = "Search Service Application" - ApplicationPool = "SharePoint Search Services" - Ensure = "Present" - CloudIndex = $true - } - - Context "When the service app exists and is cloud enabled" { + Context -Name "When the service app exists and is cloud enabled" -Fixture { + $testParams = @{ + Name = "Search Service Application" + ApplicationPool = "SharePoint Search Services" + Ensure = "Present" + CloudIndex = $true + } - Mock Get-SPServiceApplication { - return @(@{ + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Search Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool } @@ -363,36 +490,71 @@ Describe "SPSearchServiceApp - SharePoint Build $((Get-Item $SharePointCmdletMod Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + + Mock -CommandName Get-SPDSCInstalledProductVersion -MockWith { + return @{ + FileMajorPart = 15 + FileBuildPart = 0 + } } - Mock Get-SPDSCInstalledProductVersion { return @{ FileMajorPart = 15; FileBuildPart = 0 } } - It "should return false if the version is too low" { + It "Should return false if the version is too low" { (Get-TargetResource @testParams).CloudIndex | Should Be $false } - Mock Get-SPDSCInstalledProductVersion { return @{ FileMajorPart = 15; FileBuildPart = 5000 } } + Mock -CommandName Get-SPDSCInstalledProductVersion -MockWith { + return @{ + FileMajorPart = 15 + FileBuildPart = 5000 + } + } - It "should return that the web app is hybrid enabled from the get method" { + It "Should return that the web app is hybrid enabled from the get method" { (Get-TargetResource @testParams).CloudIndex | Should Be $true } } - Context "When the service doesn't exist and it should be cloud enabled" { + Context -Name "When the service doesn't exist and it should be cloud enabled" -Fixture { + $testParams = @{ + Name = "Search Service Application" + ApplicationPool = "SharePoint Search Services" + Ensure = "Present" + CloudIndex = $true + } - Mock Get-SPServiceApplication { return $null } + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - Mock Get-SPDSCInstalledProductVersion { return @{ FileMajorPart = 15; FileBuildPart = 5000 } } + Mock -CommandName Get-SPDSCInstalledProductVersion -MockWith { + return @{ + FileMajorPart = 15 + FileBuildPart = 5000 + } + } - It "creates the service app in the set method" { + It "Should create the service app in the set method" { Set-TargetResource @testParams } - Mock Get-SPDSCInstalledProductVersion { return @{ FileMajorPart = 15; FileBuildPart = 0 } } + Mock -CommandName Get-SPDSCInstalledProductVersion -MockWith { + return @{ + FileMajorPart = 15 + FileBuildPart = 0 + } + } - It "throws an error in the set method if the version of SharePoint isn't high enough" { + It "Should throw an error in the set method if the version of SharePoint isn't high enough" { { Set-TargetResource @testParams } | Should Throw } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchTopology.Mocks.cs b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchTopology.Mocks.cs new file mode 100644 index 000000000..1afddc4a0 --- /dev/null +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchTopology.Mocks.cs @@ -0,0 +1,45 @@ +namespace Microsoft.Office.Server.Search.Administration.Topology +{ + public class AdminComponent + { + public string ServerName { get; set; } + public System.Guid ComponentId { get; set; } + public System.Guid ServerId { get; set; } + } + + public class CrawlComponent + { + public string ServerName { get; set; } + public System.Guid ComponentId { get; set; } + public System.Guid ServerId {get; set;} + } + + public class ContentProcessingComponent + { + public string ServerName { get; set; } + public System.Guid ComponentId { get; set; } + public System.Guid ServerId {get; set;} + } + + public class AnalyticsProcessingComponent + { + public string ServerName { get; set; } + public System.Guid ComponentId { get; set; } + public System.Guid ServerId {get; set;} + } + + public class QueryProcessingComponent + { + public string ServerName { get; set; } + public System.Guid ComponentId { get; set; } + public System.Guid ServerId {get; set;} + } + + public class IndexComponent + { + public string ServerName { get; set; } + public System.Guid ComponentId { get; set; } + public System.Int32 IndexPartitionOrdinal { get; set; } + public System.Guid ServerId { get; set; } + } +} diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchTopology.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchTopology.Tests.ps1 index ebf1928be..4d2613d67 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchTopology.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPSearchTopology.Tests.ps1 @@ -1,58 +1,27 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPSearchTopology" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPSearchTopology - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - ServiceAppName = "Search Service Application" - Admin = @($env:COMPUTERNAME) - Crawler = @($env:COMPUTERNAME) - ContentProcessing = @($env:COMPUTERNAME) - AnalyticsProcessing = @($env:COMPUTERNAME) - QueryProcessing = @($env:COMPUTERNAME) - IndexPartition = @($env:COMPUTERNAME) - FirstPartitionDirectory = "I:\SearchIndexes\0" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - Mock Start-Sleep {} - Mock New-Item { return @{} } - Mock Get-SPEnterpriseSearchServiceInstance { - return @{ - Server = @{ - Address = $env:COMPUTERNAME - } - Status = "Online" - } - } - Mock Get-SPEnterpriseSearchServiceApplication { - return @{ - ActiveTopology = @{} - } - } +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPSearchTopology" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope - Add-Type -TypeDefinition "namespace Microsoft.Office.Server.Search.Administration.Topology { public class AdminComponent { public string ServerName { get; set; } public System.Guid ComponentId {get; set;} public System.Guid ServerId {get; set;}}}" - Add-Type -TypeDefinition "namespace Microsoft.Office.Server.Search.Administration.Topology { public class CrawlComponent { public string ServerName { get; set; } public System.Guid ComponentId {get; set;} public System.Guid ServerId {get; set;}}}" - Add-Type -TypeDefinition "namespace Microsoft.Office.Server.Search.Administration.Topology { public class ContentProcessingComponent { public string ServerName { get; set; } public System.Guid ComponentId {get; set;} public System.Guid ServerId {get; set;}}}" - Add-Type -TypeDefinition "namespace Microsoft.Office.Server.Search.Administration.Topology { public class AnalyticsProcessingComponent { public string ServerName { get; set; } public System.Guid ComponentId {get; set;} public System.Guid ServerId {get; set;}}}" - Add-Type -TypeDefinition "namespace Microsoft.Office.Server.Search.Administration.Topology { public class QueryProcessingComponent { public string ServerName { get; set; } public System.Guid ComponentId {get; set;} public System.Guid ServerId {get; set;}}}" - Add-Type -TypeDefinition "namespace Microsoft.Office.Server.Search.Administration.Topology { public class IndexComponent { public string ServerName { get; set; } public System.Guid ComponentId {get; set;} public System.Int32 IndexPartitionOrdinal {get; set;} public System.Guid ServerId {get; set;}}}" + # Initialize tests + $mockPath = Join-Path -Path $Global:SPDscHelper.RepoRoot ` + -ChildPath "Tests/Unit/SharePointDsc/SharePointDsc.SPSearchTopology.Mocks.cs" + Add-Type -LiteralPath $mockPath $serverId = New-Guid @@ -86,18 +55,53 @@ Describe "SPSearchTopology - SharePoint Build $((Get-Item $SharePointCmdletModul $indexComponent.ServerId = $serverId $indexComponent.IndexPartitionOrdinal = 0 - Mock Start-SPEnterpriseSearchServiceInstance { return $null } - Mock New-SPEnterpriseSearchTopology { return @{} } - Mock New-SPEnterpriseSearchAdminComponent { return @{} } - Mock New-SPEnterpriseSearchCrawlComponent { return @{} } - Mock New-SPEnterpriseSearchContentProcessingComponent { return @{} } - Mock New-SPEnterpriseSearchAnalyticsProcessingComponent { return @{} } - Mock New-SPEnterpriseSearchQueryProcessingComponent { return @{} } - Mock New-SPEnterpriseSearchIndexComponent { return @{} } - Mock Set-SPEnterpriseSearchTopology { return @{} } - Mock Remove-SPEnterpriseSearchComponent { return $null } - - Mock Get-SPServer { + # Mocks for all contexts + Mock -CommandName Start-Sleep -MockWith {} + Mock -CommandName New-Item -MockWith { return @{} } + Mock -CommandName Get-SPEnterpriseSearchServiceInstance -MockWith { + return @{ + Server = @{ + Address = $env:COMPUTERNAME + } + Status = "Online" + } + } + Mock -CommandName Get-SPEnterpriseSearchServiceApplication -MockWith { + return @{ + ActiveTopology = @{} + } + } + Mock -CommandName Start-SPEnterpriseSearchServiceInstance -MockWith { + return $null + } + Mock -CommandName New-SPEnterpriseSearchTopology -MockWith { + return @{} + } + Mock -CommandName New-SPEnterpriseSearchAdminComponent -MockWith { + return @{} + } + Mock -CommandName New-SPEnterpriseSearchCrawlComponent -MockWith { + return @{} + } + Mock -CommandName New-SPEnterpriseSearchContentProcessingComponent -MockWith { + return @{} + } + Mock -CommandName New-SPEnterpriseSearchAnalyticsProcessingComponent -MockWith { + return @{} + } + Mock -CommandName New-SPEnterpriseSearchQueryProcessingComponent -MockWith { + return @{} + } + Mock -CommandName New-SPEnterpriseSearchIndexComponent -MockWith { + return @{} + } + Mock -CommandName Set-SPEnterpriseSearchTopology -MockWith { + return @{} + } + Mock -CommandName Remove-SPEnterpriseSearchComponent -MockWith { + return $null + } + Mock -CommandName Get-SPServer -MockWith { return @( @{ Name = $env:COMPUTERNAME @@ -106,12 +110,24 @@ Describe "SPSearchTopology - SharePoint Build $((Get-Item $SharePointCmdletModul ) } - Context "No search topology has been applied" { - Mock Get-SPEnterpriseSearchComponent { + # Test contexts + Context -Name "No search topology has been applied" -Fixture { + $testParams = @{ + ServiceAppName = "Search Service Application" + Admin = @($env:COMPUTERNAME) + Crawler = @($env:COMPUTERNAME) + ContentProcessing = @($env:COMPUTERNAME) + AnalyticsProcessing = @($env:COMPUTERNAME) + QueryProcessing = @($env:COMPUTERNAME) + IndexPartition = @($env:COMPUTERNAME) + FirstPartitionDirectory = "I:\SearchIndexes\0" + } + + Mock -CommandName Get-SPEnterpriseSearchComponent -MockWith { return @{} } - It "returns empty values from the get method" { + It "Should return empty values from the get method" { $result = Get-TargetResource @testParams $result.Admin | Should BeNullOrEmpty $result.Crawler | Should BeNullOrEmpty @@ -120,46 +136,64 @@ Describe "SPSearchTopology - SharePoint Build $((Get-Item $SharePointCmdletModul $result.QueryProcessing | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "sets the desired topology for the current server" { + It "Should set the desired topology for the current server" { Set-TargetResource @testParams } - } + } - - - Context "No search topology exist and the search service instance isnt running" { - Mock Get-SPEnterpriseSearchComponent { + Context -Name "No search topology exist and the search service instance isnt running" -Fixture { + $testParams = @{ + ServiceAppName = "Search Service Application" + Admin = @($env:COMPUTERNAME) + Crawler = @($env:COMPUTERNAME) + ContentProcessing = @($env:COMPUTERNAME) + AnalyticsProcessing = @($env:COMPUTERNAME) + QueryProcessing = @($env:COMPUTERNAME) + IndexPartition = @($env:COMPUTERNAME) + FirstPartitionDirectory = "I:\SearchIndexes\0" + } + + Mock -CommandName Get-SPEnterpriseSearchComponent -MockWith { return @{} } - $Global:SPDSCSearchRoleInstanceCalLCount = 0 - Mock Get-SPEnterpriseSearchServiceInstance { - if ($Global:SPDSCSearchRoleInstanceCalLCount -eq 2) { - $Global:SPDSCSearchRoleInstanceCalLCount = 0 + $Global:SPDscSearchRoleInstanceCalLCount = 0 + Mock -CommandName Get-SPEnterpriseSearchServiceInstance -MockWith { + if ($Global:SPDscSearchRoleInstanceCalLCount -eq 2) { + $Global:SPDscSearchRoleInstanceCalLCount = 0 return @{ Status = "Online" } } else { - $Global:SPDSCSearchRoleInstanceCalLCount++ + $Global:SPDscSearchRoleInstanceCalLCount++ return @{ Status = "Offline" } } } - It "sets the desired topology for the current server and starts the search service instance" { + It "Should set the desired topology for the current server and starts the search service instance" { Set-TargetResource @testParams Assert-MockCalled Start-SPEnterpriseSearchServiceInstance } - } - Context "A search topology has been applied but it is not correct" { - - Mock Get-SPEnterpriseSearchServiceInstance { + Context -Name "A search topology has been applied but it is not correct" -Fixture { + $testParams = @{ + ServiceAppName = "Search Service Application" + Admin = @($env:COMPUTERNAME) + Crawler = @($env:COMPUTERNAME) + ContentProcessing = @($env:COMPUTERNAME) + AnalyticsProcessing = @($env:COMPUTERNAME) + QueryProcessing = @($env:COMPUTERNAME) + IndexPartition = @($env:COMPUTERNAME) + FirstPartitionDirectory = "I:\SearchIndexes\0" + } + + Mock -CommandName Get-SPEnterpriseSearchServiceInstance -MockWith { return @{ Server = @{ Address = $env:COMPUTERNAME @@ -168,41 +202,61 @@ Describe "SPSearchTopology - SharePoint Build $((Get-Item $SharePointCmdletModul } } - It "adds a missing admin component" { - Mock Get-SPEnterpriseSearchComponent { - return @($crawlComponent, $contentProcessingComponent, $analyticsProcessingComponent, $queryProcessingComponent) + It "Should add a missing admin component" { + Mock -CommandName Get-SPEnterpriseSearchComponent -MockWith { + return @( + $crawlComponent, + $contentProcessingComponent, + $analyticsProcessingComponent, + $queryProcessingComponent) } Set-TargetResource @testParams Assert-MockCalled New-SPEnterpriseSearchAdminComponent } - It "adds a missing crawl component" { - Mock Get-SPEnterpriseSearchComponent { - return @($adminComponent, $contentProcessingComponent, $analyticsProcessingComponent, $queryProcessingComponent) + It "Should add a missing crawl component" { + Mock -CommandName Get-SPEnterpriseSearchComponent -MockWith { + return @( + $adminComponent, + $contentProcessingComponent, + $analyticsProcessingComponent, + $queryProcessingComponent) } Set-TargetResource @testParams Assert-MockCalled New-SPEnterpriseSearchCrawlComponent } - It "adds a missing content processing component" { - Mock Get-SPEnterpriseSearchComponent { - return @($adminComponent, $crawlComponent, $analyticsProcessingComponent, $queryProcessingComponent) + It "Should add a missing content processing component" { + Mock -CommandName Get-SPEnterpriseSearchComponent -MockWith { + return @( + $adminComponent, + $crawlComponent, + $analyticsProcessingComponent, + $queryProcessingComponent) } Set-TargetResource @testParams Assert-MockCalled New-SPEnterpriseSearchContentProcessingComponent } - It "adds a missing analytics processing component" { - Mock Get-SPEnterpriseSearchComponent { - return @($adminComponent, $crawlComponent, $contentProcessingComponent, $queryProcessingComponent) + It "Should add a missing analytics processing component" { + Mock -CommandName Get-SPEnterpriseSearchComponent -MockWith { + return @( + $adminComponent, + $crawlComponent, + $contentProcessingComponent, + $queryProcessingComponent) } Set-TargetResource @testParams Assert-MockCalled New-SPEnterpriseSearchAnalyticsProcessingComponent } - It "adds a missing query processing component" { - Mock Get-SPEnterpriseSearchComponent { - return @($adminComponent, $crawlComponent, $contentProcessingComponent, $analyticsProcessingComponent) + It "Should add a missing query processing component" { + Mock -CommandName Get-SPEnterpriseSearchComponent -MockWith { + return @( + $adminComponent, + $crawlComponent, + $contentProcessingComponent, + $analyticsProcessingComponent) } Set-TargetResource @testParams Assert-MockCalled New-SPEnterpriseSearchQueryProcessingComponent @@ -219,85 +273,44 @@ Describe "SPSearchTopology - SharePoint Build $((Get-Item $SharePointCmdletModul FirstPartitionDirectory = "I:\SearchIndexes\0" } - Mock Get-SPEnterpriseSearchComponent { - return @($adminComponent, $crawlComponent, $contentProcessingComponent, $analyticsProcessingComponent, $queryProcessingComponent) - } - Mock Get-SPEnterpriseSearchComponent { - $adminComponent = New-Object Microsoft.Office.Server.Search.Administration.Topology.AdminComponent - $adminComponent.ServerName = $env:COMPUTERNAME - $adminComponent.ServerId = $serverId - $adminComponent.ComponentId = [Guid]::NewGuid() - - $crawlComponent = New-Object Microsoft.Office.Server.Search.Administration.Topology.CrawlComponent - $crawlComponent.ServerName = $env:COMPUTERNAME - $crawlComponent.ServerId = $serverId - $crawlComponent.ComponentId = [Guid]::NewGuid() - - $contentProcessingComponent = New-Object Microsoft.Office.Server.Search.Administration.Topology.ContentProcessingComponent - $contentProcessingComponent.ServerName = $env:COMPUTERNAME - $contentProcessingComponent.ServerId = $serverId - $contentProcessingComponent.ComponentId = [Guid]::NewGuid() - - $analyticsProcessingComponent = New-Object Microsoft.Office.Server.Search.Administration.Topology.AnalyticsProcessingComponent - $analyticsProcessingComponent.ServerName = $env:COMPUTERNAME - $analyticsProcessingComponent.ServerId = $serverId - $analyticsProcessingComponent.ComponentId = [Guid]::NewGuid() - - $queryProcessingComponent = New-Object Microsoft.Office.Server.Search.Administration.Topology.QueryProcessingComponent - $queryProcessingComponent.ServerName = $env:COMPUTERNAME - $queryProcessingComponent.ServerId = $serverId - $queryProcessingComponent.ComponentId = [Guid]::NewGuid() - - return @($adminComponent, $crawlComponent, $contentProcessingComponent, $analyticsProcessingComponent, $queryProcessingComponent) + Mock -CommandName Get-SPEnterpriseSearchComponent -MockWith { + return @( + $adminComponent, + $crawlComponent, + $contentProcessingComponent, + $analyticsProcessingComponent, + $queryProcessingComponent) } - It "Removes components that shouldn't be on this server" { + It "Should remove components that shouldn't be on this server" { Set-TargetResource @testParams Assert-MockCalled Remove-SPEnterpriseSearchComponent -Times 5 } - - } - Context "The correct topology on this server exists" { - Mock Get-SPEnterpriseSearchComponent { - return @($adminComponent, $crawlComponent, $contentProcessingComponent, $analyticsProcessingComponent, $queryProcessingComponent, $indexComponent) + Context -Name "The correct topology on this server exists" -Fixture { + $testParams = @{ + ServiceAppName = "Search Service Application" + Admin = @($env:COMPUTERNAME) + Crawler = @($env:COMPUTERNAME) + ContentProcessing = @($env:COMPUTERNAME) + AnalyticsProcessing = @($env:COMPUTERNAME) + QueryProcessing = @($env:COMPUTERNAME) + IndexPartition = @($env:COMPUTERNAME) + FirstPartitionDirectory = "I:\SearchIndexes\0" } - Mock Get-SPEnterpriseSearchComponent { - $adminComponent = New-Object Microsoft.Office.Server.Search.Administration.Topology.AdminComponent - $adminComponent.ServerName = $env:COMPUTERNAME - $adminComponent.ServerId = $serverId - $adminComponent.ComponentId = [Guid]::NewGuid() - - $crawlComponent = New-Object Microsoft.Office.Server.Search.Administration.Topology.CrawlComponent - $crawlComponent.ServerName = $env:COMPUTERNAME - $crawlComponent.ServerId = $serverId - $crawlComponent.ComponentId = [Guid]::NewGuid() - - $contentProcessingComponent = New-Object Microsoft.Office.Server.Search.Administration.Topology.ContentProcessingComponent - $contentProcessingComponent.ServerName = $env:COMPUTERNAME - $contentProcessingComponent.ServerId = $serverId - $contentProcessingComponent.ComponentId = [Guid]::NewGuid() - - $analyticsProcessingComponent = New-Object Microsoft.Office.Server.Search.Administration.Topology.AnalyticsProcessingComponent - $analyticsProcessingComponent.ServerName = $env:COMPUTERNAME - $analyticsProcessingComponent.ServerId = $serverId - $analyticsProcessingComponent.ComponentId = [Guid]::NewGuid() - - $queryProcessingComponent = New-Object Microsoft.Office.Server.Search.Administration.Topology.QueryProcessingComponent - $queryProcessingComponent.ServerName = $env:COMPUTERNAME - $queryProcessingComponent.ServerId = $serverId - $queryProcessingComponent.ComponentId = [Guid]::NewGuid() - - $indexComponent = New-Object Microsoft.Office.Server.Search.Administration.Topology.IndexComponent - $indexComponent.ServerName = $env:COMPUTERNAME - $indexComponent.ServerId = $serverId - $indexComponent.IndexPartitionOrdinal = 0 - - return @($adminComponent, $crawlComponent, $contentProcessingComponent, $analyticsProcessingComponent, $queryProcessingComponent, $indexComponent) + + Mock -CommandName Get-SPEnterpriseSearchComponent -MockWith { + return @( + $adminComponent, + $crawlComponent, + $contentProcessingComponent, + $analyticsProcessingComponent, + $queryProcessingComponent, + $indexComponent) } - Mock Get-SPEnterpriseSearchServiceInstance { + Mock -CommandName Get-SPEnterpriseSearchServiceInstance { return @{ Server = @{ Address = $env:COMPUTERNAME @@ -306,6 +319,12 @@ Describe "SPSearchTopology - SharePoint Build $((Get-Item $SharePointCmdletModul } } + It "Should return true from the test method" { + Test-TargetResource @testParams | Should Be $true + } + } + + Context -Name "No search service application exists" -Fixture { $testParams = @{ ServiceAppName = "Search Service Application" Admin = @($env:COMPUTERNAME) @@ -317,28 +336,26 @@ Describe "SPSearchTopology - SharePoint Build $((Get-Item $SharePointCmdletModul FirstPartitionDirectory = "I:\SearchIndexes\0" } - It "returns true from the test method" { - Test-TargetResource @testParams | Should Be $true + Mock -CommandName Get-SPEnterpriseSearchServiceApplication -MockWith { + return $null } - } - - Context "No search service application exists" { - Mock Get-SPEnterpriseSearchServiceApplication { return $null } - Mock Get-SPEnterpriseSearchComponent { + Mock -CommandName Get-SPEnterpriseSearchComponent -MockWith { return @{} } - It "returns empty values from the get method" { + It "Should return empty values from the get method" { Get-TargetResource @testParams | Should Be $null } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "sets the desired topology for the current server" { + It "Should set the desired topology for the current server" { { Set-TargetResource @testParams } | Should Throw } } } -} \ No newline at end of file +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPSecureStoreServiceApp.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPSecureStoreServiceApp.Tests.ps1 index 09a9a8f8f..9053664b8 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPSecureStoreServiceApp.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPSecureStoreServiceApp.Tests.ps1 @@ -1,128 +1,175 @@ [CmdletBinding()] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPSecureStoreServiceApp" -$ModuleName = "MSFT_SPSecureStoreServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPSecureStoreServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Secure Store Service Application" - ApplicationPool = "SharePoint Search Services" - AuditingEnabled = $false - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - $versionBeingTested = (Get-Item $Global:CurrentSharePointStubModule).Directory.BaseName - $majorBuildNumber = $versionBeingTested.Substring(0, $versionBeingTested.IndexOf(".")) + # Initialize tests + $getTypeFullName = "Microsoft.Office.SecureStoreService.Server.SecureStoreServiceApplication" + $mockPassword = ConvertTo-SecureString -String "passwprd" -AsPlainText -Force + $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential ` + -ArgumentList @("SqlUser", $mockPassword) - Mock Get-SPDSCInstalledProductVersion { return @{ FileMajorPart = $majorBuildNumber } } - Mock Remove-SPServiceApplication {} + # Mocks for all contexts + Mock -CommandName Remove-SPServiceApplication -MockWith {} + Mock -CommandName New-SPSecureStoreServiceApplication -MockWith { } + Mock -CommandName New-SPSecureStoreServiceApplicationProxy -MockWith { } + Mock -CommandName Set-SPSecureStoreServiceApplication -MockWith { } - Context "When no service application exists in the current farm" { + # Test contexts + Context -Name "When no service application exists in the current farm" -Fixture { + $testParams = @{ + Name = "Secure Store Service Application" + ApplicationPool = "SharePoint Search Services" + AuditingEnabled = $false + Ensure = "Present" + } - Mock Get-SPServiceApplication { return $null } - Mock New-SPSecureStoreServiceApplication { } - Mock New-SPSecureStoreServiceApplicationProxy { } + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { - Set-TargetResource @testParams - Assert-MockCalled New-SPSecureStoreServiceApplication - } - - $testParams.Add("InstallAccount", (New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)))) - It "creates a new service application in the set method where InstallAccount is used" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPSecureStoreServiceApplication } - $testParams.Remove("InstallAccount") $testParams.Add("DatabaseName", "SP_SecureStore") - It "creates a new service application in the set method where parameters beyond the minimum required set" { + It "Should create a new service application in the set method where parameters beyond the minimum required set" { Set-TargetResource @testParams Assert-MockCalled New-SPSecureStoreServiceApplication } - $testParams.Remove("DatabaseName") } - Context "When service applications exist in the current farm but the specific search app does not" { - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Some other service app type" - }) } + Context -Name "When service applications exist in the current farm but the specific search app does not" -Fixture { + $testParams = @{ + Name = "Secure Store Service Application" + ApplicationPool = "SharePoint Search Services" + AuditingEnabled = $false + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = "Microsoft.Office.UnKnownWebServiceApplication" + } + } -PassThru -Force + return $spServiceApp + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } } - Context "When a service application exists and is configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When a service application exists and is configured correctly" -Fixture { + $testParams = @{ + Name = "Secure Store Service Application" + ApplicationPool = "SharePoint Search Services" + AuditingEnabled = $false + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Secure Store Service Application" DisplayName = $testParams.Name - ApplicationPool = @{ Name = $testParams.ApplicationPool } + ApplicationPool = @{ + Name = $testParams.ApplicationPool + } Database = @{ Name = $testParams.DatabaseName - Server = @{ Name = $testParams.DatabaseServer } + Server = @{ + Name = $testParams.DatabaseServer + } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } - Context "When a service application exists and the app pool is not configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When a service application exists and the app pool is not configured correctly" -Fixture { + $testParams = @{ + Name = "Secure Store Service Application" + ApplicationPool = "SharePoint Search Services" + AuditingEnabled = $false + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Secure Store Service Application" DisplayName = $testParams.Name - ApplicationPool = @{ Name = "Wrong App Pool Name" } + ApplicationPool = @{ + Name = "Wrong App Pool Name" + } Database = @{ Name = $testParams.DatabaseName - Server = @{ Name = $testParams.DatabaseServer } + Server = @{ + Name = $testParams.DatabaseServer + } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return @{ + Name = $testParams.ApplicationPool + } } - Mock Get-SPServiceApplicationPool { return @{ Name = $testParams.ApplicationPool } } - Mock Set-SPSecureStoreServiceApplication { } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "calls the update service app cmdlet from the set method" { + It "Should call the update service app cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Get-SPServiceApplicationPool @@ -130,114 +177,131 @@ Describe "SPSecureStoreServiceApp - SharePoint Build $((Get-Item $SharePointCmdl } } - Context "When specific windows credentials are to be used for the database" { + Context -Name "When specific windows credentials are to be used for the database" -Fixture { $testParams = @{ Name = "Secure Store Service Application" ApplicationPool = "SharePoint Search Services" AuditingEnabled = $false DatabaseName = "SP_ManagedMetadata" - DatabaseCredentials = New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)) + DatabaseCredentials = $mockCredential DatabaseAuthenticationType = "Windows" Ensure = "Present" } - Mock Get-SPServiceApplication { return $null } - Mock New-SPSecureStoreServiceApplication { } - Mock New-SPSecureStoreServiceApplicationProxy { } + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } It "allows valid Windows credentials can be passed" { Set-TargetResource @testParams Assert-MockCalled New-SPSecureStoreServiceApplication } - It "throws an exception if database authentication type is not specified" { + It "Should throw an exception if database authentication type is not specified" { $testParams.Remove("DatabaseAuthenticationType") { Set-TargetResource @testParams } | Should Throw } - It "throws an exception if the credentials aren't provided and the authentication type is set" { + It "Should throw an exception if the credentials aren't provided and the authentication type is set" { $testParams.Add("DatabaseAuthenticationType", "Windows") $testParams.Remove("DatabaseCredentials") { Set-TargetResource @testParams } | Should Throw } } - Context "When specific SQL credentials are to be used for the database" { + Context -Name "When specific SQL credentials are to be used for the database" -Fixture { $testParams = @{ Name = "Secure Store Service Application" ApplicationPool = "SharePoint Search Services" AuditingEnabled = $false DatabaseName = "SP_ManagedMetadata" - DatabaseCredentials = New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)) + DatabaseCredentials = $mockCredential DatabaseAuthenticationType = "SQL" Ensure = "Present" } - Mock Get-SPServiceApplication { return $null } - Mock New-SPSecureStoreServiceApplication { } - Mock New-SPSecureStoreServiceApplicationProxy { } + Mock -CommandName Get-SPServiceApplication -MockWith { return $null } It "allows valid SQL credentials can be passed" { Set-TargetResource @testParams Assert-MockCalled New-SPSecureStoreServiceApplication } - It "throws an exception if database authentication type is not specified" { + It "Should throw an exception if database authentication type is not specified" { $testParams.Remove("DatabaseAuthenticationType") { Set-TargetResource @testParams } | Should Throw } - It "throws an exception if the credentials aren't provided and the authentication type is set" { + It "Should throw an exception if the credentials aren't provided and the authentication type is set" { $testParams.Add("DatabaseAuthenticationType", "Windows") $testParams.Remove("DatabaseCredentials") { Set-TargetResource @testParams } | Should Throw } } - $testParams = @{ - Name = "Secure Store Service Application" - ApplicationPool = "-" - AuditingEnabled = $false - Ensure = "Absent" - } - - Context "When the service app exists but it shouldn't" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When the service app exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "Secure Store Service Application" + ApplicationPool = "-" + AuditingEnabled = $false + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Secure Store Service Application" DisplayName = $testParams.Name - ApplicationPool = @{ Name = $testParams.ApplicationPool } + ApplicationPool = @{ + Name = $testParams.ApplicationPool + } Database = @{ Name = $testParams.DatabaseName - Server = @{ Name = $testParams.DatabaseServer } + Server = @{ + Name = $testParams.DatabaseServer + } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns present from the Get method" { + It "Should return present from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the service application in the set method" { + It "Should remove the service application in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplication } } - Context "When the service app doesn't exist and shouldn't" { - Mock Get-SPServiceApplication { return $null } + Context -Name "When the service app doesn't exist and shouldn't" -Fixture { + $testParams = @{ + Name = "Secure Store Service Application" + ApplicationPool = "-" + AuditingEnabled = $false + Ensure = "Absent" + } - It "returns absent from the Get method" { + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } + + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceAppPool.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceAppPool.Tests.ps1 index 9d0e9d5ef..20928c556 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceAppPool.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceAppPool.Tests.ps1 @@ -1,122 +1,152 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPServiceAppPool" -$ModuleName = "MSFT_SPServiceAppPool" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPServiceAppPool - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Service pool" - ServiceAccount = "DEMO\svcSPServiceApps" - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Mock New-SPServiceApplicationPool { } - Mock Set-SPServiceApplicationPool { } - Mock Remove-SPServiceApplicationPool { } + # Initialize tests + + # Mocks for all contexts + Mock -CommandName New-SPServiceApplicationPool -MockWith { } + Mock -CommandName Set-SPServiceApplicationPool -MockWith { } + Mock -CommandName Remove-SPServiceApplicationPool -MockWith { } + + # Test contexts + Context -Name "A service account pool does not exist but should" -Fixture { + $testParams = @{ + Name = "Service pool" + ServiceAccount = "DEMO\svcSPServiceApps" + Ensure = "Present" + } - Context "A service account pool does not exist but should" { - Mock Get-SPServiceApplicationPool { return $null } + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return $null + } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "calls the set method to create a new service account pool" { + It "Should call the set method to create a new service account pool" { Set-TargetResource @testParams - Assert-MockCalled New-SPServiceApplicationPool } } - Context "A service account pool exists but has the wrong service account" { - Mock Get-SPServiceApplicationPool { return @{ - Name = $testParams.Name - ProcessAccountName = "WRONG\account" - }} + Context -Name "A service account pool exists but has the wrong service account" -Fixture { + $testParams = @{ + Name = "Service pool" + ServiceAccount = "DEMO\svcSPServiceApps" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return @{ + Name = $testParams.Name + ProcessAccountName = "WRONG\account" + } + } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "calls the set method to update the service account pool" { + It "Should call the set method to update the service account pool" { Set-TargetResource @testParams Assert-MockCalled Set-SPServiceApplicationPool } } - Context "A service account pool exists and uses the correct account" { - Mock Get-SPServiceApplicationPool { return @{ - Name = $testParams.Name - ProcessAccountName = $testParams.ServiceAccount - }} + Context -Name "A service account pool exists and uses the correct account" -Fixture { + $testParams = @{ + Name = "Service pool" + ServiceAccount = "DEMO\svcSPServiceApps" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return @{ + Name = $testParams.Name + ProcessAccountName = $testParams.ServiceAccount + } + } It "retrieves present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - $testParams = @{ - Name = "Service pool" - ServiceAccount = "DEMO\svcSPServiceApps" - Ensure = "Absent" - } - - Context "When the service app pool exists but it shouldn't" { - Mock Get-SPServiceApplicationPool { return @{ - Name = $testParams.Name - ProcessAccountName = $testParams.ServiceAccount - }} + Context -Name "When the service app pool exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "Service pool" + ServiceAccount = "DEMO\svcSPServiceApps" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return @{ + Name = $testParams.Name + ProcessAccountName = $testParams.ServiceAccount + } + } - It "returns present from the Get method" { + It "Should return present from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the service application in the set method" { + It "Should remove the service application in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplicationPool } } - Context "When the service app pool doesn't exist and shouldn't" { - Mock Get-SPServiceApplicationPool { return $null } + Context -Name "When the service app pool doesn't exist and shouldn't" -Fixture { + $testParams = @{ + Name = "Service pool" + ServiceAccount = "DEMO\svcSPServiceApps" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceAppProxyGroup.tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceAppProxyGroup.tests.ps1 index af12bc833..ce8a9bf09 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceAppProxyGroup.tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceAppProxyGroup.tests.ps1 @@ -1,50 +1,52 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPServiceAppProxyGroup" -$ModuleName = "MSFT_SPServiceAppProxyGroup" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDSC\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPServiceAppProxyGroup - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - $ListofAllServiceAppProxies = @( + # Initialize tests + $listofAllServiceAppProxies = @( "Web 1 User Profile Service Application", "Web 1 MMS Service Application", - "State Service Application" + "State Service Application", "Web 2 User Profile Service Application" ) - - - - Mock Add-SPServiceApplicationProxyGroupMember {} - Mock Remove-SPServiceApplicationProxyGroupMember {} - Mock Get-SPServiceApplicationProxy { $ProxiesToReturn = @() - foreach ($ServiceAppProxy in $ListofAllServiceAppProxies ){ - $ProxiesToReturn += @{ DisplayName = $ServiceAppProxy }} - return $ProxiesToReturn - } - - Mock New-SPServiceApplicationProxyGroup { return @{ Name = $TestParams.Name} } - Context "ServiceAppProxies and ServiceAppProxiesToInclude parameters used simultaniously" { + # Mocks for all contexts + Mock -CommandName Add-SPServiceApplicationProxyGroupMember -MockWith {} + Mock -CommandName Remove-SPServiceApplicationProxyGroupMember -MockWith {} + Mock -CommandName Get-SPServiceApplicationProxy -MockWith { + $proxiesToReturn = @() + foreach ($ServiceAppProxy in $listofAllServiceAppProxies) + { + $proxiesToReturn += @{ + DisplayName = $ServiceAppProxy + } + } + return $proxiesToReturn + } + Mock -CommandName New-SPServiceApplicationProxyGroup { + return @{ + Name = $TestParams.Name + } + } + + # Test contexts + Context -Name "ServiceAppProxies and ServiceAppProxiesToInclude parameters used simultaniously" -Fixture { $testParams = @{ Name = "Shared Services" Ensure = "Present" @@ -52,345 +54,380 @@ Describe "SPServiceAppProxyGroup - SharePoint Build $((Get-Item $SharePointCmdle ServiceAppProxiesToInclude = "Web 2 User Profile Service Application" } - It "return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Be $null } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "Cannot use the ServiceAppProxies parameter together with the ServiceAppProxiesToInclude or ServiceAppProxiesToExclude parameters" } } - Context "None of the ServiceAppProxies, ServiceAppProxiesToInclude and ServiceAppProxiesToExclude parameters are used" { + Context -Name "None of the ServiceAppProxies, ServiceAppProxiesToInclude and ServiceAppProxiesToExclude parameters are used" -Fixture { $testParams = @{ Name = "My Proxy Group" Ensure = "Present" } - It "return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Be $null } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "At least one of the following parameters must be specified: ServiceAppProxies, ServiceAppProxiesToInclude, ServiceAppProxiesToExclude" } } - Context "The Service Application Proxy Group does not exist and should" { + Context -Name "The Service Application Proxy Group does not exist and should" -Fixture { $testParams = @{ Name = "Shared Services" Ensure = "Present" ServiceAppProxies = @("State Service Application","Web 1 User Profile Service Application") } - Mock Get-SPServiceApplicationProxyGroup { return $null } + Mock -CommandName Get-SPServiceApplicationProxyGroup -MockWith { + return $null + } - It "returns ensure = absent from the get method" { + It "Should return ensure = absent from the get method" { (Get-TargetResource @testParams).Ensure | Should be 'Absent' } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "creates the Service Application Proxy Group with the set method" { + It "Should create the Service Application Proxy Group with the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPServiceApplicationProxyGroup } } - Context "The ServiceApplication Proxy Group does not exist, and should not" { + Context -Name "The ServiceApplication Proxy Group does not exist, and should not" -Fixture { $testParams = @{ Name = "Shared Services" Ensure = "Absent" } - Mock Get-SPServiceApplicationProxyGroup { return $null } + Mock -CommandName Get-SPServiceApplicationProxyGroup -MockWith { + return $null + } - It "returns ensure = absent from the get method" { + It "Should return ensure = absent from the get method" { (Get-TargetResource @testParams).Ensure | Should be 'Absent' } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } - } - Context "The Service Application Proxy Group exists and should, ServiceAppProxies match" { + Context -Name "The Service Application Proxy Group exists and should, ServiceAppProxies match" -Fixture { $testParams = @{ Name = "Shared Services" Ensure = "Present" ServiceAppProxies = @("State Service Application","Web 1 User Profile Service Application") } - Mock Get-SPServiceApplicationProxyGroup { - $ProxiesToReturn = @() - foreach ($ServiceAppProxy in $TestParams.ServiceAppProxies ){ - $ProxiesToReturn += @{ Name = $ServiceAppProxy } - } - return @{ - Name = $testParams.Name - Proxies = $ProxiesToReturn - } - } + Mock -CommandName Get-SPServiceApplicationProxyGroup -MockWith { + $proxiesToReturn = @() + foreach ($ServiceAppProxy in $TestParams.ServiceAppProxies) + { + $proxiesToReturn += @{ + Name = $ServiceAppProxy + } + } + return @{ + Name = $testParams.Name + Proxies = $proxiesToReturn + } + } - It "returns ensure = present from the get method" { + It "Should return ensure = present from the get method" { (Get-TargetResource @testParams).Ensure | Should be 'Present' } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The Service Application Proxy Group exists and should, ServiceAppProxies do not match" { + Context -Name "The Service Application Proxy Group exists and should, ServiceAppProxies do not match" -Fixture { $testParams = @{ Name = "Shared Services" Ensure = "Present" - ServiceAppProxies = @("State Service Application","Web 1 User Profile Service Application") - } - - $ServiceAppProxiesConfigured = @("State Service Application","Web 2 User Profile Service Application") - - Mock Get-SPServiceApplicationProxyGroup { - $ProxiesToReturn = @() - foreach ($ServiceAppProxy in $ServiceAppProxiesConfigured ){ - $ProxiesToReturn += @{ Name = $ServiceAppProxy } - } - return @{ - Name = $testParams.Name - Proxies = $ProxiesToReturn - } - } - - It "returns ensure = present from the get method" { + ServiceAppProxies = @( + "State Service Application", + "Web 1 User Profile Service Application") + } + + $serviceAppProxiesConfigured = @( + "State Service Application", + "Web 2 User Profile Service Application") + + Mock -CommandName Get-SPServiceApplicationProxyGroup -MockWith { + $proxiesToReturn = @() + foreach ($ServiceAppProxy in $serviceAppProxiesConfigured) + { + $proxiesToReturn += @{ + Name = $ServiceAppProxy + } + } + return @{ + Name = $testParams.Name + Proxies = $proxiesToReturn + } + } + + It "Should return ensure = present from the get method" { (Get-TargetResource @testParams).Ensure | Should be 'Present' } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "Set method Adds the missing Service Proxy" { + It "Should add the missing and remove the extra service proxy in the set method" { Set-TargetResource @testParams Assert-MockCalled Add-SPServiceApplicationProxyGroupMember -Exactly 1 - } - - It "Set method Removes the extra Service Proxy" { Assert-MockCalled Remove-SPServiceApplicationProxyGroupMember -Exactly 1 } } - Context "The Service Application Proxy Group exists and should, ServiceAppProxiesToInclude matches" { + Context -Name "The Service Application Proxy Group exists and should, ServiceAppProxiesToInclude matches" -Fixture { $testParams = @{ Name = "Shared Services" Ensure = "Present" - ServiceAppProxiesToInclude = @("State Service Application","Web 1 User Profile Service Application") - } - - $ServiceAppProxiesConfigured = @("State Service Application","Web 1 User Profile Service Application","Web 1 MMS Service Application") - - Mock Get-SPServiceApplicationProxyGroup { - $ProxiesToReturn = @() - foreach ($ServiceAppProxy in $ServiceAppProxiesConfigured ){ - $ProxiesToReturn += @{ Name = $ServiceAppProxy } - } - return @{ - Name = $testParams.Name - Proxies = $ProxiesToReturn - } - } - - It "returns ensure = present from the get method" { + ServiceAppProxiesToInclude = @( + "State Service Application", + "Web 1 User Profile Service Application") + } + + $serviceAppProxiesConfigured = @( + "State Service Application", + "Web 1 User Profile Service Application", + "Web 1 MMS Service Application") + + Mock -CommandName Get-SPServiceApplicationProxyGroup -MockWith { + $proxiesToReturn = @() + foreach ($ServiceAppProxy in $serviceAppProxiesConfigured) + { + $proxiesToReturn += @{ + Name = $ServiceAppProxy + } + } + return @{ + Name = $testParams.Name + Proxies = $proxiesToReturn + } + } + + It "Should return ensure = present from the get method" { (Get-TargetResource @testParams).Ensure | Should be 'Present' } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } - } - Context "The Service Application Proxy Group exists and should, ServiceAppProxiesToInclude does not match" { + Context -Name "The Service Application Proxy Group exists and should, ServiceAppProxiesToInclude does not match" -Fixture { $testParams = @{ Name = "Shared Services" Ensure = "Present" - ServiceAppProxiesToInclude = @("State Service Application","Web 1 User Profile Service Application") - } - - $ServiceAppProxiesConfigured = @("State Service Application","Web 1 MMS Service Application") - - Mock Get-SPServiceApplicationProxyGroup { - $ProxiesToReturn = @() - foreach ($ServiceAppProxy in $ServiceAppProxiesConfigured ){ - $ProxiesToReturn += @{ Name = $ServiceAppProxy } - } - return @{ - Name = $testParams.Name - Proxies = $ProxiesToReturn - } - } - - It "returns ensure = present from the get method" { + ServiceAppProxiesToInclude = @( + "State Service Application", + "Web 1 User Profile Service Application") + } + + $serviceAppProxiesConfigured = @( + "State Service Application", + "Web 1 MMS Service Application") + + Mock -CommandName Get-SPServiceApplicationProxyGroup -MockWith { + $proxiesToReturn = @() + foreach ($ServiceAppProxy in $serviceAppProxiesConfigured) + { + $proxiesToReturn += @{ + Name = $ServiceAppProxy + } + } + return @{ + Name = $testParams.Name + Proxies = $proxiesToReturn + } + } + + It "Should return ensure = present from the get method" { (Get-TargetResource @testParams).Ensure | Should be 'Present' } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "Set method Adds the missing Service Proxy" { + It "Should add the missing and then not remove the extra service proxy in the set method" { Set-TargetResource @testParams Assert-MockCalled Add-SPServiceApplicationProxyGroupMember -Exactly 1 - } - - It "Set method does not remove extra Service Proxies" { Assert-MockCalled Remove-SPServiceApplicationProxyGroupMember -Exactly 0 } - } - Context "The Service Application Proxy Group exists and should, ServiceAppProxiesToExclude matches" { + Context -Name "The Service Application Proxy Group exists and should, ServiceAppProxiesToExclude matches" -Fixture { $testParams = @{ Name = "Shared Services" Ensure = "Present" ServiceAppProxiesToExclude = @("Web 1 User Profile Service Application") } - $ServiceAppProxiesConfigured = @("State Service Application","Web 1 MMS Service Application") + $serviceAppProxiesConfigured = @( + "State Service Application", + "Web 1 MMS Service Application") - Mock Get-SPServiceApplicationProxyGroup { - $ProxiesToReturn = @() - foreach ($ServiceAppProxy in $ServiceAppProxiesConfigured ){ - $ProxiesToReturn += @{ Name = $ServiceAppProxy } - } - return @{ - Name = $testParams.Name - Proxies = $ProxiesToReturn - } - } + Mock -CommandName Get-SPServiceApplicationProxyGroup -MockWith { + $proxiesToReturn = @() + foreach ($ServiceAppProxy in $serviceAppProxiesConfigured) + { + $proxiesToReturn += @{ + Name = $ServiceAppProxy + } + } + return @{ + Name = $testParams.Name + Proxies = $proxiesToReturn + } + } - It "returns ensure = present from the get method" { + It "Should return ensure = present from the get method" { (Get-TargetResource @testParams).Ensure | Should be 'Present' } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } - } - Context "The Service Application Proxy Group exists and should, ServiceAppProxiesToExclude does not match" { + Context -Name "The Service Application Proxy Group exists and should, ServiceAppProxiesToExclude does not match" -Fixture { $testParams = @{ Name = "Shared Services" Ensure = "Present" ServiceAppProxiesToExclude = @("Web 1 User Profile Service Application","Web 2 User Profile Service Application") } - $ServiceAppProxiesConfigured = @("State Service Application","Web 1 MMS Service Application","Web 1 User Profile Service Application") + $serviceAppProxiesConfigured = @( + "State Service Application", + "Web 1 MMS Service Application", + "Web 1 User Profile Service Application") - Mock Get-SPServiceApplicationProxyGroup { - $ProxiesToReturn = @() - foreach ($ServiceAppProxy in $ServiceAppProxiesConfigured ){ - $ProxiesToReturn += @{ Name = $ServiceAppProxy } - } - return @{ - Name = $testParams.Name - Proxies = $ProxiesToReturn - } - } + Mock -CommandName Get-SPServiceApplicationProxyGroup -MockWith { + $proxiesToReturn = @() + foreach ($ServiceAppProxy in $serviceAppProxiesConfigured) + { + $proxiesToReturn += @{ + Name = $ServiceAppProxy + } + } + return @{ + Name = $testParams.Name + Proxies = $proxiesToReturn + } + } - It "returns ensure = present from the get method" { + It "Should return ensure = present from the get method" { (Get-TargetResource @testParams).Ensure | Should be 'Present' } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "Set method removes the Service Proxy" { + It "Should remove the extra but not add a new service proxy in the set mthod" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplicationProxyGroupMember -Exactly 1 - } - - It "Set method does not Add extra Service Proxies" { Assert-MockCalled Add-SPServiceApplicationProxyGroupMember -Exactly 0 } - } - Context "Specified service application does not exist, ServiceAppProxies specified" { + Context -Name "Specified service application does not exist, ServiceAppProxies specified" -Fixture { $testParams = @{ Name = "Shared Services" Ensure = "Present" - ServiceAppProxies = @("No Such Service Application","Web 1 User Profile Service Application") - } - - Mock Get-SPServiceApplicationProxyGroup { - $ProxiesToReturn = @() - foreach ($ServiceAppProxy in "Web 1 User Profile Service Application" ){ - $ProxiesToReturn += @{ Name = $ServiceAppProxy } - } - return @{ - Name = $testParams.Name - Proxies = $ProxiesToReturn - } - } - - It "returns ensure = present from the get method" { + ServiceAppProxies = @( + "No Such Service Application", + "Web 1 User Profile Service Application") + } + + Mock -CommandName Get-SPServiceApplicationProxyGroup -MockWith { + $proxiesToReturn = @() + foreach ($ServiceAppProxy in "Web 1 User Profile Service Application") + { + $proxiesToReturn += @{ + Name = $ServiceAppProxy + } + } + return @{ + Name = $testParams.Name + Proxies = $proxiesToReturn + } + } + + It "Should return ensure = present from the get method" { (Get-TargetResource @testParams).Ensure | Should be 'Present' } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws an error from the set method" { - { Set-TargetResource @testParams }| Should throw "Invalid Service Application Proxy No Such Service Application" + It "Should throw an error from the set method" { + { Set-TargetResource @testParams } | Should throw "Invalid Service Application Proxy No Such Service Application" } } - Context "Specified service application does not exist, ServiceAppProxiesToInclude specified" { + Context -Name "Specified service application does not exist, ServiceAppProxiesToInclude specified" -Fixture { $testParams = @{ Name = "Shared Services" Ensure = "Present" - ServiceAppProxiesToInclude = @("No Such Service Application","Web 1 User Profile Service Application") - } - - Mock Get-SPServiceApplicationProxyGroup { - $ProxiesToReturn = @() - foreach ($ServiceAppProxy in "Web 1 User Profile Service Application" ){ - $ProxiesToReturn += @{ Name = $ServiceAppProxy } - } - return @{ - Name = $testParams.Name - Proxies = $ProxiesToReturn - } - } - - It "returns ensure = present from the get method" { + ServiceAppProxiesToInclude = @( + "No Such Service Application", + "Web 1 User Profile Service Application") + } + + Mock -CommandName Get-SPServiceApplicationProxyGroup -MockWith { + $proxiesToReturn = @() + foreach ($ServiceAppProxy in "Web 1 User Profile Service Application") + { + $proxiesToReturn += @{ + Name = $ServiceAppProxy + } + } + return @{ + Name = $testParams.Name + Proxies = $proxiesToReturn + } + } + + It "Should return ensure = present from the get method" { (Get-TargetResource @testParams).Ensure | Should be 'Present' } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws an error from the set method" { + It "Should throw an error from the set method" { { Set-TargetResource @testParams }| Should throw "Invalid Service Application Proxy No Such Service Application" } } - - - } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceAppSecurity.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceAppSecurity.Tests.ps1 index dbfa1ecbd..af0f134bf 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceAppSecurity.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceAppSecurity.Tests.ps1 @@ -1,160 +1,178 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPServiceAppSecurity" -$ModuleName = "MSFT_SPServiceAppSecurity" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPServiceAppSecurity - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - ServiceAppName = "Example Service App" - SecurityType = "SharingPermissions" - Members = @( - (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" -ClientOnly -Property @{ - Username = "CONTOSO\user1" - AccessLevel = "Full Control" - }), - (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" -ClientOnly -Property @{ - Username = "CONTOSO\user2" - AccessLevel = "Full Control" - }) - ) - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Test-SPDSCIsADUser { return $true } + # Initialize tests + + # Mocks for all contexts + Mock -CommandName Test-SPDSCIsADUser -MockWith { return $true } - Mock Grant-SPObjectSecurity {} - Mock Revoke-SPObjectSecurity {} - Mock Set-SPServiceApplicationSecurity {} + Mock Grant-SPObjectSecurity -MockWith {} + Mock Revoke-SPObjectSecurity -MockWith {} + Mock -CommandName Set-SPServiceApplicationSecurity -MockWith {} - Mock New-SPClaimsPrincipal { + Mock -CommandName New-SPClaimsPrincipal -MockWith { return @{ Value = $Identity -replace "i:0#.w\|" } } -ParameterFilter { $IdentityType -eq "EncodedClaim" } - Mock New-SPClaimsPrincipal { - $Global:SPDSCClaimsPrincipalUser = $Identity + Mock -CommandName New-SPClaimsPrincipal -MockWith { + $Global:SPDscClaimsPrincipalUser = $Identity return ( - New-Object Object | Add-Member ScriptMethod ToEncodedString { - return "i:0#.w|$($Global:SPDSCClaimsPrincipalUser)" - } -PassThru + New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod ` + -Name ToEncodedString ` + -Value { + return "i:0#.w|$($Global:SPDscClaimsPrincipalUser)" + } -PassThru ) } -ParameterFilter { $IdentityType -eq "WindowsSamAccountName" } - - Context "The service app that security should be applied to does not exist" { + + # Test contexts + Context -Name "The service app that security should be applied to does not exist" -Fixture { + $testParams = @{ + ServiceAppName = "Example Service App" + SecurityType = "SharingPermissions" + Members = @( + (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" ` + -ClientOnly ` + -Property @{ + Username = "CONTOSO\user1" + AccessLevel = "Full Control" + }), + (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" ` + -ClientOnly ` + -Property @{ + Username = "CONTOSO\user2" + AccessLevel = "Full Control" + }) + ) + } - Mock Get-SPServiceApplication { return $null } + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "should return empty members list from the get method" { + It "Should return empty members list from the get method" { (Get-TargetResource @testParams).Members | Should BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should Throw } - } - - $testParams = @{ - ServiceAppName = "Example Service App" - SecurityType = "SharingPermissions" } - Context "None of the required members properties are provided" { + Context -Name "None of the required members properties are provided" -Fixture { + $testParams = @{ + ServiceAppName = "Example Service App" + SecurityType = "SharingPermissions" + } - It "should throw an exception from the test method" { + It "Should throw an exception from the test method" { { Test-TargetResource @testParams } | Should Throw } - It "should throw an exception from the set method" { + It "Should throw an exception from the set method" { { Set-TargetResource @testParams } | Should Throw } } - $testParams = @{ - ServiceAppName = "Example Service App" - SecurityType = "SharingPermissions" - Members = @( - (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" -ClientOnly -Property @{ - Username = "CONTOSO\user1" - AccessLevel = "Full Control" - }) - ) - MembersToInclude = @( - (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" -ClientOnly -Property @{ - Username = "CONTOSO\user1" - AccessLevel = "Full Control" - }) - ) - MembersToExclude = @("CONTOSO\user2") - } - - Context "All of the members properties are provided" { + Context -Name "All of the members properties are provided" -Fixture { + $testParams = @{ + ServiceAppName = "Example Service App" + SecurityType = "SharingPermissions" + Members = @( + (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" ` + -ClientOnly ` + -Property @{ + Username = "CONTOSO\user1" + AccessLevel = "Full Control" + }) + ) + MembersToInclude = @( + (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" ` + -ClientOnly ` + -Property @{ + Username = "CONTOSO\user1" + AccessLevel = "Full Control" + }) + ) + MembersToExclude = @("CONTOSO\user2") + } - It "should throw an exception from the test method" { + It "Should throw an exception from the test method" { { Test-TargetResource @testParams } | Should Throw } - It "should throw an exception from the set method" { + It "Should throw an exception from the set method" { { Set-TargetResource @testParams } | Should Throw } } - $testParams = @{ - ServiceAppName = "Example Service App" - SecurityType = "SharingPermissions" - Members = @( - (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" -ClientOnly -Property @{ - Username = "CONTOSO\user1" - AccessLevel = "Full Control" - }), - (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" -ClientOnly -Property @{ - Username = "CONTOSO\user2" - AccessLevel = "Full Control" - }) - ) - } - - Context "The service app exists and a fixed members list is provided that does not match the current settings" { - - Mock Get-SPServiceApplication { return @{} } - Mock Get-SPServiceApplicationSecurity { return @{ - AccessRules = @( - @{ - Name = "CONTOSO\user1" - AllowedRights = "Read" - } + Context -Name "The service app exists and a fixed members list is provided that does not match the current settings" -Fixture { + $testParams = @{ + ServiceAppName = "Example Service App" + SecurityType = "SharingPermissions" + Members = @( + (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" ` + -ClientOnly ` + -Property @{ + Username = "CONTOSO\user1" + AccessLevel = "Full Control" + }), + (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" ` + -ClientOnly ` + -Property @{ + Username = "CONTOSO\user2" + AccessLevel = "Full Control" + }) ) - }} + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return @{} + } + + Mock -CommandName Get-SPServiceApplicationSecurity { + return @{ + AccessRules = @( + @{ + Name = "CONTOSO\user1" + AllowedRights = "Read" + } + ) + } + } - It "should return a list of current members from the get method" { + It "Should return a list of current members from the get method" { (Get-TargetResource @testParams).Members | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should call the update cmdlet from the set method" { + It "Should call the update cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Grant-SPObjectSecurity Assert-MockCalled Revoke-SPObjectSecurity @@ -162,64 +180,93 @@ Describe "SPServiceAppSecurity - SharePoint Build $((Get-Item $SharePointCmdletM } } - Context "The service app exists and a fixed members list is provided that does match the current settings" { - - Mock Get-SPServiceApplication { return @{} } - Mock Get-SPServiceApplicationSecurity { return @{ - AccessRules = @( - @{ - Name = "CONTOSO\user1" - AllowedRights = "FullControl" - }, - @{ - Name = "CONTOSO\user2" - AllowedRights = "FullControl" - } + Context -Name "The service app exists and a fixed members list is provided that does match the current settings" -Fixture { + $testParams = @{ + ServiceAppName = "Example Service App" + SecurityType = "SharingPermissions" + Members = @( + (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" ` + -ClientOnly ` + -Property @{ + Username = "CONTOSO\user1" + AccessLevel = "Full Control" + }), + (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" ` + -ClientOnly ` + -Property @{ + Username = "CONTOSO\user2" + AccessLevel = "Full Control" + }) ) - }} + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return @{} + } - It "should return a list of current members from the get method" { + Mock -CommandName Get-SPServiceApplicationSecurity -MockWith { + return @{ + AccessRules = @( + @{ + Name = "CONTOSO\user1" + AllowedRights = "FullControl" + }, + @{ + Name = "CONTOSO\user2" + AllowedRights = "FullControl" + } + ) + } + } + + It "Should return a list of current members from the get method" { (Get-TargetResource @testParams).Members | Should Not BeNullOrEmpty } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - $testParams = @{ - ServiceAppName = "Example Service App" - SecurityType = "SharingPermissions" - MembersToInclude = @( - (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" -ClientOnly -Property @{ - Username = "CONTOSO\user1" - AccessLevel = "Full Control" - }) - ) - MembersToExclude = @("CONTOSO\user2") - } - - Context "The service app exists and a specific list of members to add and remove is provided, which does not match the desired state" { - - Mock Get-SPServiceApplication { return @{} } - Mock Get-SPServiceApplicationSecurity { return @{ - AccessRules = @( - @{ - Name = "CONTOSO\user2" - AllowedRights = "FullControl" - } + Context -Name "The service app exists and a specific list of members to add and remove is provided, which does not match the desired state" -Fixture { + $testParams = @{ + ServiceAppName = "Example Service App" + SecurityType = "SharingPermissions" + MembersToInclude = @( + (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" ` + -ClientOnly ` + -Property @{ + Username = "CONTOSO\user1" + AccessLevel = "Full Control" + }) ) - }} + MembersToExclude = @("CONTOSO\user2") + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return @{} + } + + Mock -CommandName Get-SPServiceApplicationSecurity -MockWith { + return @{ + AccessRules = @( + @{ + Name = "CONTOSO\user2" + AllowedRights = "FullControl" + } + ) + } + } - It "should return a list of current members from the get method" { + It "Should return a list of current members from the get method" { (Get-TargetResource @testParams).Members | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should call the update cmdlet from the set method" { + It "Should call the update cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Grant-SPObjectSecurity Assert-MockCalled Revoke-SPObjectSecurity @@ -227,49 +274,87 @@ Describe "SPServiceAppSecurity - SharePoint Build $((Get-Item $SharePointCmdletM } } - Context "The service app exists and a specific list of members to add and remove is provided, which does match the desired state" { - - Mock Get-SPServiceApplication { return @{} } - Mock Get-SPServiceApplicationSecurity { return @{ - AccessRules = @( - @{ - Name = "CONTOSO\user1" - AllowedRights = "FullControl" - } + Context -Name "The service app exists and a specific list of members to add and remove is provided, which does match the desired state" -Fixture { + $testParams = @{ + ServiceAppName = "Example Service App" + SecurityType = "SharingPermissions" + MembersToInclude = @( + (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" ` + -ClientOnly ` + -Property @{ + Username = "CONTOSO\user1" + AccessLevel = "Full Control" + }) ) - }} + MembersToExclude = @("CONTOSO\user2") + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return @{} + } + + Mock -CommandName Get-SPServiceApplicationSecurity -MockWith { + return @{ + AccessRules = @( + @{ + Name = "CONTOSO\user1" + AllowedRights = "FullControl" + } + ) + } + } - It "should return a list of current members from the get method" { + It "Should return a list of current members from the get method" { (Get-TargetResource @testParams).Members | Should Not BeNullOrEmpty } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The service app exists and a specific list of members to add and remove is provided, which does match the desired state and includes a claims based group" { - - Mock Get-SPServiceApplication { return @{} } - Mock Get-SPServiceApplicationSecurity { return @{ - AccessRules = @( - @{ - Name = "i:0#.w|s-1-5-21-2753725054-2932589700-2007370523-2138" - AllowedRights = "FullControl" - } + Context -Name "The service app exists and a specific list of members to add and remove is provided, which does match the desired state and includes a claims based group" -Fixture { + $testParams = @{ + ServiceAppName = "Example Service App" + SecurityType = "SharingPermissions" + MembersToInclude = @( + (New-CimInstance -ClassName "MSFT_SPServiceAppSecurityEntry" ` + -ClientOnly ` + -Property @{ + Username = "CONTOSO\user1" + AccessLevel = "Full Control" + }) ) - }} + MembersToExclude = @("CONTOSO\user2") + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return @{} + } + Mock -CommandName Get-SPServiceApplicationSecurity { + return @{ + AccessRules = @( + @{ + Name = "i:0#.w|s-1-5-21-2753725054-2932589700-2007370523-2138" + AllowedRights = "FullControl" + } + ) + } + } + Mock Resolve-SPDscSecurityIdentifier { return "CONTOSO\user1" } - It "should return a list of current members from the get method" { + It "Should return a list of current members from the get method" { (Get-TargetResource @testParams).Members | Should Not BeNullOrEmpty } - It "should return true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } } -} \ No newline at end of file +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceInstance.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceInstance.Tests.ps1 index e386f29df..4eb2c37bc 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceInstance.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPServiceInstance.Tests.ps1 @@ -1,142 +1,176 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPServiceInstance" -$ModuleName = "MSFT_SPServiceInstance" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPServiceInstance - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Service pool" - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Mock Start-SPServiceInstance { } - Mock Stop-SPServiceInstance { } + # Mocks for all contexts + Mock -CommandName Start-SPServiceInstance -MockWith { } + Mock -CommandName Stop-SPServiceInstance -MockWith { } + + # Test contexts + Context -Name "The service instance is not running but should be" -Fixture { + $testParams = @{ + Name = "Service pool" + Ensure = "Present" + } - Context "The service instance is not running but should be" { - Mock Get-SPServiceInstance { return @() } + Mock -CommandName Get-SPServiceInstance -MockWith { + return @() + } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the set method" { + It "Should return false from the set method" { Test-TargetResource @testParams | Should Be $false } } - Context "The service instance is not running but should be" { - Mock Get-SPServiceInstance { return @( - @{ + Context -Name "The service instance is not running but should be" -Fixture { + $testParams = @{ + Name = "Service pool" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceInstance -MockWith { + return @(@{ TypeName = $testParams.Name Status = "Disabled" }) } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the set method" { + It "Should return false from the set method" { Test-TargetResource @testParams | Should Be $false } - It "calls the start service call from the set method" { + It "Should call the start service call from the set method" { Set-TargetResource @testParams - Assert-MockCalled Start-SPServiceInstance } } - Context "The service instance is running and should be" { - Mock Get-SPServiceInstance { return @( - @{ + Context -Name "The service instance is running and should be" -Fixture { + $testParams = @{ + Name = "Service pool" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceInstance -MockWith { + return @(@{ TypeName = $testParams.Name Status = "Online" }) } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "An invalid service application is specified to start" { - Mock Get-SPServiceInstance { return $null } + Context -Name "An invalid service application is specified to start" -Fixture { + $testParams = @{ + Name = "Service pool" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceInstance { + return $null + } - It "throws when the set method is called" { + It "Should throw when the set method is called" { { Set-TargetResource @testParams } | Should Throw } } - $testParams.Ensure = "Absent" - - Context "The service instance is not running and should not be" { - Mock Get-SPServiceInstance { return @( - @{ + Context -Name "The service instance is not running and should not be" -Fixture { + $testParams = @{ + Name = "Service pool" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceInstance -MockWith { + return @(@{ TypeName = $testParams.Name Status = "Disabled" }) } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The service instance is running and should not be" { - Mock Get-SPServiceInstance { return @( - @{ + Context -Name "The service instance is running and should not be" -Fixture { + $testParams = @{ + Name = "Service pool" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceInstance -MockWith { + return @(@{ TypeName = $testParams.Name Status = "Online" }) } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false from the set method" { + It "Should return false from the set method" { Test-TargetResource @testParams | Should Be $false } - It "calls the stop service call from the set method" { + It "Should call the stop service call from the set method" { Set-TargetResource @testParams Assert-MockCalled Stop-SPServiceInstance } } - Context "An invalid service application is specified to stop" { - Mock Get-SPServiceInstance { return $null } + Context -Name "An invalid service application is specified to stop" -Fixture { + $testParams = @{ + Name = "Service pool" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceInstance { + return $null + } - It "throws when the set method is called" { + It "Should throw when the set method is called" { { Set-TargetResource @testParams } | Should Throw } } - } -} \ No newline at end of file + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPSessionStateService.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPSessionStateService.Tests.ps1 index b100d4f3a..0befb72d1 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPSessionStateService.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPSessionStateService.Tests.ps1 @@ -1,95 +1,142 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPSessionStateService" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPSessionStateService - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - DatabaseName = "SP_StateService" - DatabaseServer = "SQL.test.domain" - Ensure = "Present" - SessionTimeout = 60 - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Set-SPSessionStateService { return @{} } - Mock Enable-SPSessionStateService { return @{} } - Mock Disable-SPSessionStateService { return @{} } +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPSessionStateService" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Mocks for all contexts + Mock -CommandName Set-SPSessionStateService -MockWith { return @{} } + Mock -CommandName Enable-SPSessionStateService -MockWith { return @{} } + Mock -CommandName Disable-SPSessionStateService -MockWith { return @{} } + + # Test contexts + Context -Name "the service isn't enabled but should be" -Fixture { + $testParams = @{ + DatabaseName = "SP_StateService" + DatabaseServer = "SQL.test.domain" + Ensure = "Present" + SessionTimeout = 60 + } - Context "the service isn't enabled but should be" { - Mock Get-SPSessionStateService { return @{ SessionStateEnabled = $false; Timeout = @{TotalMinutes = 60}} } + Mock -CommandName Get-SPSessionStateService -MockWith { + return @{ + SessionStateEnabled = $false + Timeout = @{ + TotalMinutes = 60 + } + } + } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "enables the session service from the set method" { + It "Should enable the session service from the set method" { Set-TargetResource @testParams Assert-MockCalled Enable-SPSessionStateService } } - Context "the service is enabled and should be" { - Mock Get-SPSessionStateService { return @{ SessionStateEnabled = $true; Timeout = @{TotalMinutes = 60}} } - It "returns present from the get method" { + Context -Name "the service is enabled and should be" -Fixture { + $testParams = @{ + DatabaseName = "SP_StateService" + DatabaseServer = "SQL.test.domain" + Ensure = "Present" + SessionTimeout = 60 + } + + Mock -CommandName Get-SPSessionStateService -MockWith { + return @{ + SessionStateEnabled = $true + Timeout = @{ + TotalMinutes = 60 + } + } + } + + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "the timeout should be set to 90 seconds but is 60" { - Mock Get-SPSessionStateService { return @{ SessionStateEnabled = $true; Timeout = @{TotalMinutes = 60}} } - $testParams.SessionTimeout = 90 - It "returns present from the get method" { + Context -Name "the timeout should be set to 90 seconds but is 60" -Fixture { + $testParams = @{ + DatabaseName = "SP_StateService" + DatabaseServer = "SQL.test.domain" + Ensure = "Present" + SessionTimeout = 90 + } + + Mock -CommandName Get-SPSessionStateService -MockWith { + return @{ + SessionStateEnabled = $true + Timeout = @{ + TotalMinutes = 60 + } + } + } + + It "Should return present from the get method" { $result = Get-TargetResource @testParams $result.Ensure | Should Be "Present" $result.SessionTimeout | Should Be 60 } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $false } - It "updates session timeout to 90 seconds" { + It "Should update session timeout to 90 seconds" { Set-TargetResource @testParams Assert-MockCalled Set-SPSessionStateService } } - Context "the service is enabled but shouldn't be" { - Mock Get-SPSessionStateService { return @{ SessionStateEnabled = $true; Timeout = @{TotalMinutes = 60}} } - $testParams.Ensure = "Absent" - It "returns present from the get method" { + Context -Name "the service is enabled but shouldn't be" -Fixture { + $testParams = @{ + DatabaseName = "SP_StateService" + DatabaseServer = "SQL.test.domain" + Ensure = "Absent" + } + + Mock -CommandName Get-SPSessionStateService -MockWith { + return @{ + SessionStateEnabled = $true + Timeout = @{ + TotalMinutes = 60 + } + } + } + + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } @@ -99,16 +146,31 @@ Describe "SPSessionStateService - SharePoint Build $((Get-Item $SharePointCmdlet } } - Context "the service is disabled and should be" { - Mock Get-SPSessionStateService { return @{ SessionStateEnabled = $false; Timeout = @{TotalMinutes = 60}} } + Context -Name "the service is disabled and should be" -Fixture { + $testParams = @{ + DatabaseName = "SP_StateService" + DatabaseServer = "SQL.test.domain" + Ensure = "Absent" + } - It "returns enabled from the get method" { + Mock -CommandName Get-SPSessionStateService -MockWith { + return @{ + SessionStateEnabled = $false + Timeout = @{ + TotalMinutes = 60 + } + } + } + + It "Should return enabled from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPShellAdmins.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPShellAdmins.Tests.ps1 index 2a696cbf4..9f5dd65ae 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPShellAdmins.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPShellAdmins.Tests.ps1 @@ -1,90 +1,90 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPShellAdmins" -$ModuleName = "MSFT_SPShellAdmins" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "ShellAdmins" - Members = "contoso\user1", "contoso\user2" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") + # Mocks for all contexts + Mock -CommandName Add-SPShellAdmin -MockWith {} + Mock -CommandName Remove-SPShellAdmin -MockWith {} - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Import-Module {} -ParameterFilter { $_.Name -eq $ModuleName } + # Test contexts + Context -Name "The server is not part of SharePoint farm" -Fixture { + $testParams = @{ + Name = "ShellAdmins" + Members = "contoso\user1", "contoso\user2" + } - Context "The server is not part of SharePoint farm" { - Mock Get-SPFarm { throw "Unable to detect local farm" } + Mock -CommandName Get-SPFarm -MockWith { + throw "Unable to detect local farm" + } - It "return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Be $null } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws an exception in the set method to say there is no local farm" { + It "Should throw an exception in the set method to say there is no local farm" { { Set-TargetResource @testParams } | Should throw "No local SharePoint farm was detected" } } - Context "Members and MembersToInclude parameters used simultaniously - General permissions" { + Context -Name "Members and MembersToInclude parameters used simultaniously - General permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" Members = "contoso\user1", "contoso\user2" MembersToInclude = "contoso\user1", "contoso\user2" } - It "return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Be $null } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "Cannot use the Members parameter together with the MembersToInclude or MembersToExclude parameters" } } - Context "None of the Members, MembersToInclude and MembersToExclude parameters are used - General permissions" { + Context -Name "None of the Members, MembersToInclude and MembersToExclude parameters are used - General permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" } - It "return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Be $null } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "At least one of the following parameters must be specified: Members, MembersToInclude, MembersToExclude" } } - Context "Members and MembersToInclude parameters used simultaniously - ContentDatabase permissions" { + Context -Name "Members and MembersToInclude parameters used simultaniously - ContentDatabase permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" ContentDatabases = @( @@ -96,20 +96,20 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). ) } - It "return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Be $null } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "ContentDatabases: Cannot use the Members parameter together with the MembersToInclude or MembersToExclude parameters" } } - Context "None of the Members, MembersToInclude and MembersToExclude parameters are used - ContentDatabase permissions" { + Context -Name "None of the Members, MembersToInclude and MembersToExclude parameters are used - ContentDatabase permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" ContentDatabases = @( @@ -119,20 +119,20 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). ) } - It "return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Be $null } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "ContentDatabases: At least one of the following parameters must be specified: Members, MembersToInclude, MembersToExclude" } } - Context "Specified content database does not exist - ContentDatabase permissions" { + Context -Name "Specified content database does not exist - ContentDatabase permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" ContentDatabases = @( @@ -142,7 +142,8 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). } -ClientOnly) ) } - Mock Get-SPDSCContentDatabase { + + Mock -CommandName Get-SPContentDatabase -MockWith { return @( @{ Name = "SharePoint_Content_Contoso1" @@ -154,35 +155,45 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). } ) } - It "return null from the get method" { + + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { { Test-TargetResource @testParams } | Should throw "Specified database does not exist" } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "Specified database does not exist" } } - Context "AllContentDatabases parameter is used and permissions do not match" { + Context -Name "AllContentDatabases parameter is used and permissions do not match" -Fixture { $testParams = @{ Name = "ShellAdmins" Members = "contoso\user1", "contoso\user2" AllContentDatabases = $true } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions - return @{ UserName = "contoso\user3","contoso\user4" } - } else { + return @{ + UserName = "contoso\user3","contoso\user4" + } + } + else + { # Database parameter not used, return general permissions - return @{ UserName = "contoso\user1","contoso\user2" } + return @{ + UserName = "contoso\user1","contoso\user2" + } } } - Mock Get-SPDSCContentDatabase { + + Mock -CommandName Get-SPContentDatabase -MockWith { return @( @{ Name = "SharePoint_Content_Contoso1" @@ -194,40 +205,47 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). } ) } - Mock Add-SPShellAdmin {} - Mock Remove-SPShellAdmin {} - It "return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { Set-TargetResource @testParams Assert-MockCalled Add-SPShellAdmin Assert-MockCalled Remove-SPShellAdmin } } - Context "AllContentDatabases parameter is used and permissions do not match" { + Context -Name "AllContentDatabases parameter is used and permissions do not match" -Fixture { $testParams = @{ Name = "ShellAdmins" Members = "contoso\user1", "contoso\user2" AllContentDatabases = $true } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions - return @{ UserName = "contoso\user1","contoso\user2" } - } else { + return @{ + UserName = "contoso\user1","contoso\user2" + } + } + else + { # Database parameter not used, return general permissions - return @{ UserName = "contoso\user1","contoso\user2" } + return @{ + UserName = "contoso\user1","contoso\user2" + } } } - Mock Get-SPDSCContentDatabase { + + Mock -CommandName Get-SPContentDatabase -MockWith { return @( @{ Name = "SharePoint_Content_Contoso1" @@ -240,72 +258,80 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). ) } - It "return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Configured Members do not match the actual members - General permissions" { + Context -Name "Configured Members do not match the actual members - General permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" Members = "contoso\user1", "contoso\user2" } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions return @{} - } else { + } + else + { # Database parameter not used, return general permissions return @{ UserName = "contoso\user3","contoso\user4" } } } - Mock Add-SPShellAdmin {} - Mock Remove-SPShellAdmin {} - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { Set-TargetResource @testParams Assert-MockCalled Add-SPShellAdmin Assert-MockCalled Remove-SPShellAdmin } } - Context "Configured Members match the actual members - General permissions" { + Context -Name "Configured Members match the actual members - General permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" Members = "contoso\user1", "contoso\user2" } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions return @{} - } else { + } + else + { # Database parameter not used, return general permissions - return @{ UserName = "contoso\user1", "contoso\user2" } + return @{ + UserName = "contoso\user1", "contoso\user2" + } } } - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Configured Members do not match the actual members - ContentDatabase permissions" { + Context -Name "Configured Members do not match the actual members - ContentDatabase permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" ContentDatabases = @( @@ -319,16 +345,25 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). } -ClientOnly) ) } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions - return @{ UserName = "contoso\user3","contoso\user4" } - } else { + return @{ + UserName = "contoso\user3","contoso\user4" + } + } + else + { # Database parameter not used, return general permissions - return @{ UserName = "contoso\user1","contoso\user2" } + return @{ + UserName = "contoso\user1","contoso\user2" + } } } - Mock Get-SPDSCContentDatabase { + + Mock -CommandName Get-SPContentDatabase -MockWith { return @( @{ Name = "SharePoint_Content_Contoso1" @@ -340,25 +375,23 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). } ) } - Mock Add-SPShellAdmin {} - Mock Remove-SPShellAdmin {} - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { Set-TargetResource @testParams Assert-MockCalled Add-SPShellAdmin Assert-MockCalled Remove-SPShellAdmin } } - Context "Configured Members match the actual members - ContentDatabase permissions" { + Context -Name "Configured Members match the actual members - ContentDatabase permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" ContentDatabases = @( @@ -372,16 +405,25 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). } -ClientOnly) ) } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions - return @{ UserName = "contoso\user1","contoso\user2" } - } else { + return @{ + UserName = "contoso\user1","contoso\user2" + } + } + else + { # Database parameter not used, return general permissions - return @{ UserName = "contoso\user1","contoso\user2" } + return @{ + UserName = "contoso\user1","contoso\user2" + } } } - Mock Get-SPDSCContentDatabase { + + Mock -CommandName Get-SPContentDatabase -MockWith { return @( @{ Name = "SharePoint_Content_Contoso1" @@ -394,71 +436,81 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). ) } - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Configured MembersToInclude do not match the actual members - General permissions" { + Context -Name "Configured MembersToInclude do not match the actual members - General permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" MembersToInclude = "contoso\user1", "contoso\user2" } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions return @{} - } else { + } + else + { # Database parameter not used, return general permissions - return @{ UserName = "contoso\user3","contoso\user4" } + return @{ + UserName = "contoso\user3","contoso\user4" + } } } - Mock Add-SPShellAdmin {} - - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { Set-TargetResource @testParams Assert-MockCalled Add-SPShellAdmin } } - Context "Configured MembersToInclude match the actual members - General permissions" { + Context -Name "Configured MembersToInclude match the actual members - General permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" MembersToInclude = "contoso\user1", "contoso\user2" } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions return @{} - } else { + } + else + { # Database parameter not used, return general permissions - return @{ UserName = "contoso\user1", "contoso\user2", "contoso\user3" } + return @{ + UserName = "contoso\user1", "contoso\user2", "contoso\user3" + } } } - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Configured MembersToInclude do not match the actual members - ContentDatabase permissions" { + Context -Name "Configured MembersToInclude do not match the actual members - ContentDatabase permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" ContentDatabases = @( @@ -472,16 +524,25 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). } -ClientOnly) ) } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions - return @{ UserName = "contoso\user3","contoso\user4" } - } else { + return @{ + UserName = "contoso\user3","contoso\user4" + } + } + else + { # Database parameter not used, return general permissions - return @{ UserName = "contoso\user1","contoso\user2" } + return @{ + UserName = "contoso\user1","contoso\user2" + } } } - Mock Get-SPDSCContentDatabase { + + Mock -CommandName Get-SPContentDatabase -MockWith { return @( @{ Name = "SharePoint_Content_Contoso1" @@ -493,23 +554,22 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). } ) } - Mock Add-SPShellAdmin {} - - It "should return null from the get method" { + + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { Set-TargetResource @testParams Assert-MockCalled Add-SPShellAdmin } } - Context "Configured MembersToInclude match the actual members - ContentDatabase permissions" { + Context -Name "Configured MembersToInclude match the actual members - ContentDatabase permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" ContentDatabases = @( @@ -523,16 +583,25 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). } -ClientOnly) ) } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions - return @{ UserName = "contoso\user1","contoso\user2", "contoso\user3" } - } else { + return @{ + UserName = "contoso\user1","contoso\user2", "contoso\user3" + } + } + else + { # Database parameter not used, return general permissions - return @{ UserName = "contoso\user1","contoso\user2" } + return @{ + UserName = "contoso\user1","contoso\user2" + } } } - Mock Get-SPDSCContentDatabase { + + Mock -CommandName Get-SPContentDatabase -MockWith { return @( @{ Name = "SharePoint_Content_Contoso1" @@ -545,70 +614,81 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). ) } - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Configured MembersToExclude do not match the actual members - General permissions" { + Context -Name "Configured MembersToExclude do not match the actual members - General permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" MembersToExclude = "contoso\user1", "contoso\user2" } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions return @{} - } else { + } + else + { # Database parameter not used, return general permissions - return @{ UserName = "contoso\user1","contoso\user2" } + return @{ + UserName = "contoso\user1","contoso\user2" + } } } - Mock Remove-SPShellAdmin {} - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPShellAdmin } } - Context "Configured MembersToExclude match the actual members - General permissions" { + Context -Name "Configured MembersToExclude match the actual members - General permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" MembersToExclude = "contoso\user1", "contoso\user2" } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions return @{} - } else { + } + else + { # Database parameter not used, return general permissions - return @{ UserName = "contoso\user3", "contoso\user4" } + return @{ + UserName = "contoso\user3", "contoso\user4" + } } } - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "Configured MembersToExclude do not match the actual members - ContentDatabase permissions" { + Context -Name "Configured MembersToExclude do not match the actual members - ContentDatabase permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" ContentDatabases = @( @@ -622,16 +702,25 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). } -ClientOnly) ) } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions - return @{ UserName = "contoso\user1","contoso\user2" } - } else { + return @{ + UserName = "contoso\user1","contoso\user2" + } + } + else + { # Database parameter not used, return general permissions - return @{ UserName = "contoso\user1","contoso\user2" } + return @{ + UserName = "contoso\user1","contoso\user2" + } } } - Mock Get-SPDSCContentDatabase { + + Mock -CommandName Get-SPContentDatabase -MockWith { return @( @{ Name = "SharePoint_Content_Contoso1" @@ -643,23 +732,22 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). } ) } - Mock Remove-SPShellAdmin {} - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPShellAdmin } } - Context "Configured MembersToExclude match the actual members - ContentDatabase permissions" { + Context -Name "Configured MembersToExclude match the actual members - ContentDatabase permissions" -Fixture { $testParams = @{ Name = "ShellAdmins" ContentDatabases = @( @@ -673,16 +761,25 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). } -ClientOnly) ) } - Mock Get-SPShellAdmin { - if ($database) { + + Mock -CommandName Get-SPShellAdmin -MockWith { + if ($database) + { # Database parameter used, return database permissions - return @{ UserName = "contoso\user1","contoso\user2" } - } else { + return @{ + UserName = "contoso\user1","contoso\user2" + } + } + else + { # Database parameter not used, return general permissions - return @{ UserName = "contoso\user1","contoso\user2" } + return @{ + UserName = "contoso\user1","contoso\user2" + } } } - Mock Get-SPDSCContentDatabase { + + Mock -CommandName Get-SPContentDatabase -MockWith { return @( @{ Name = "SharePoint_Content_Contoso1" @@ -695,13 +792,15 @@ Describe "SPShellAdmins - SharePoint Build $((Get-Item $SharePointCmdletModule). ) } - It "should return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPSite.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPSite.Tests.ps1 index 9daa17e7c..bf27afd2a 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPSite.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPSite.Tests.ps1 @@ -1,155 +1,187 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPSite" -$ModuleName = "MSFT_SPSite" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPSite - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Url = "http://site.sharepoint.com" - OwnerAlias = "DEMO\User" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue + # Mocks for all contexts + Mock -CommandName New-SPSite -MockWith { } - Mock New-SPSite { } + # Test contexts + Context -Name "The site doesn't exist yet and should" -Fixture { + $testParams = @{ + Url = "http://site.sharepoint.com" + OwnerAlias = "DEMO\User" + } - Context "The site doesn't exist yet and should" { - Mock Get-SPSite { return $null } + Mock -CommandName Get-SPSite -MockWith { return $null } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "creates a new site from the set method" { + It "Should create a new site from the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPSite } } - Context "The site exists and is a host named site collection" { - Mock Get-SPSite { return @{ - HostHeaderIsSiteName = $true - WebApplication = @{ - Url = $testParams.Url - UseClaimsAuthentication = $false + Context -Name "The site exists and is a host named site collection" -Fixture { + $testParams = @{ + Url = "http://site.sharepoint.com" + OwnerAlias = "DEMO\User" + } + + Mock -CommandName Get-SPSite -MockWith { + return @{ + HostHeaderIsSiteName = $true + WebApplication = @{ + Url = $testParams.Url + UseClaimsAuthentication = $false + } + Url = $testParams.Url + Owner = @{ UserLogin = "DEMO\owner" } } - Url = $testParams.Url - Owner = @{ UserLogin = "DEMO\owner" } - }} + } - It "returns the site data from the get method" { + It "Should return the site data from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The site exists and uses claims authentication" { - Mock Get-SPSite { return @{ - HostHeaderIsSiteName = $false - WebApplication = @{ - Url = $testParams.Url - UseClaimsAuthentication = $true + Context -Name "The site exists and uses claims authentication" -Fixture { + $testParams = @{ + Url = "http://site.sharepoint.com" + OwnerAlias = "DEMO\User" + } + + Mock -CommandName Get-SPSite -MockWith { + return @{ + HostHeaderIsSiteName = $false + WebApplication = @{ + Url = $testParams.Url + UseClaimsAuthentication = $true + } + Url = $testParams.Url + Owner = @{ UserLogin = "DEMO\owner" } } - Url = $testParams.Url - Owner = @{ UserLogin = "DEMO\owner" } - }} - Mock New-SPClaimsPrincipal { return @{ Value = $testParams.OwnerAlias }} + } - It "returns the site data from the get method" { + Mock -CommandName New-SPClaimsPrincipal -MockWith { + return @{ + Value = $testParams.OwnerAlias + } + } + + It "Should return the site data from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } - Mock Get-SPSite { return @{ - HostHeaderIsSiteName = $false - WebApplication = @{ - Url = $testParams.Url - UseClaimsAuthentication = $true + Mock -CommandName Get-SPSite -MockWith { + return @{ + HostHeaderIsSiteName = $false + WebApplication = @{ + Url = $testParams.Url + UseClaimsAuthentication = $true + } + Url = $testParams.Url + Owner = $null } - Url = $testParams.Url - Owner = $null - }} + } - It "returns the site data from the get method where a valid site collection admin does not exist" { + It "Should return the site data from the get method where a valid site collection admin does not exist" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - Mock Get-SPSite { return @{ - HostHeaderIsSiteName = $false - WebApplication = @{ - Url = $testParams.Url - UseClaimsAuthentication = $true + Mock -CommandName Get-SPSite -MockWith { + return @{ + HostHeaderIsSiteName = $false + WebApplication = @{ + Url = $testParams.Url + UseClaimsAuthentication = $true + } + Url = $testParams.Url + Owner = @{ UserLogin = "DEMO\owner" } + SecondaryContact = @{ UserLogin = "DEMO\secondary" } } - Url = $testParams.Url - Owner = @{ UserLogin = "DEMO\owner" } - SecondaryContact = @{ UserLogin = "DEMO\secondary" } - }} + } - It "returns the site data from the get method where a secondary site contact exists" { + It "Should return the site data from the get method where a secondary site contact exists" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } } - Context "The site exists and uses classic authentication" { - Mock Get-SPSite { return @{ - HostHeaderIsSiteName = $false - WebApplication = @{ - Url = $testParams.Url - UseClaimsAuthentication = $false + Context -Name "The site exists and uses classic authentication" -Fixture { + $testParams = @{ + Url = "http://site.sharepoint.com" + OwnerAlias = "DEMO\User" + } + + Mock -CommandName Get-SPSite -MockWith { + return @{ + HostHeaderIsSiteName = $false + WebApplication = @{ + Url = $testParams.Url + UseClaimsAuthentication = $false + } + Url = $testParams.Url + Owner = @{ UserLogin = "DEMO\owner" } } - Url = $testParams.Url - Owner = @{ UserLogin = "DEMO\owner" } - }} + } - It "returns the site data from the get method" { + It "Should return the site data from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } - Mock Get-SPSite { return @{ - HostHeaderIsSiteName = $false - WebApplication = @{ - Url = $testParams.Url - UseClaimsAuthentication = $false + Mock -CommandName Get-SPSite -MockWith { + return @{ + HostHeaderIsSiteName = $false + WebApplication = @{ + Url = $testParams.Url + UseClaimsAuthentication = $false + } + Url = $testParams.Url + Owner = @{ UserLogin = "DEMO\owner" } + SecondaryContact = @{ UserLogin = "DEMO\secondary" } } - Url = $testParams.Url - Owner = @{ UserLogin = "DEMO\owner" } - SecondaryContact = @{ UserLogin = "DEMO\secondary" } - }} + } - It "returns the site data from the get method where a secondary site contact exists" { + It "Should return the site data from the get method where a secondary site contact exists" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } } - } -} \ No newline at end of file + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPStateServiceApp.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPStateServiceApp.Tests.ps1 index b94d50502..ecd42e142 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPStateServiceApp.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPStateServiceApp.Tests.ps1 @@ -1,99 +1,135 @@ [CmdletBinding()] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPStateServiceApp" -$ModuleName = "MSFT_SPStateServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPStateServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "State Service App" - DatabaseName = "SP_StateService" - DatabaseServer = "SQL.test.domain" - DatabaseCredentials = New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)) - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock New-SPStateServiceDatabase { return @{} } - Mock New-SPStateServiceApplication { return @{} } - Mock New-SPStateServiceApplicationProxy { return @{} } - Mock Remove-SPServiceApplication { } + # Initialize tests + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential ` + -ArgumentList @("username", $mockPassword) - Context "the service app doesn't exist and should" { - Mock Get-SPStateServiceApplication { return $null } + # Mocks for all contexts + Mock -CommandName New-SPStateServiceDatabase -MockWith { return @{} } + Mock -CommandName New-SPStateServiceApplication -MockWith { return @{} } + Mock -CommandName New-SPStateServiceApplicationProxy -MockWith { return @{} } + Mock -CommandName Remove-SPServiceApplication -MockWith { } - It "returns absent from the get method" { + # Test contexts + Context -Name "the service app doesn't exist and should" -Fixture { + $testParams = @{ + Name = "State Service App" + DatabaseName = "SP_StateService" + DatabaseServer = "SQL.test.domain" + DatabaseCredentials = $mockCredential + Ensure = "Present" + } + + Mock -CommandName Get-SPStateServiceApplication -MockWith { + return $null + } + + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the get method" { + It "Should return false from the get method" { Test-TargetResource @testParams | Should Be $false } - It "creates a state service app from the set method" { + It "Should create a state service app from the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPStateServiceApplication } } - Context "the service app exists and should" { - Mock Get-SPStateServiceApplication { return @{ DisplayName = $testParams.Name } } + Context -Name "the service app exists and should" -Fixture { + $testParams = @{ + Name = "State Service App" + DatabaseName = "SP_StateService" + DatabaseServer = "SQL.test.domain" + DatabaseCredentials = $mockCredential + Ensure = "Present" + } + + Mock -CommandName Get-SPStateServiceApplication -MockWith { + return @{ + DisplayName = $testParams.Name + } + } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - $testParams.Ensure = "Absent" - - Context "When the service app exists but it shouldn't" { - Mock Get-SPStateServiceApplication { return @{ DisplayName = $testParams.Name } } + Context -Name "When the service app exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "State Service App" + DatabaseName = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPStateServiceApplication -MockWith { + return @{ + DisplayName = $testParams.Name + } + } - It "returns present from the Get method" { + It "Should return present from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the service application in the set method" { + It "Should remove the service application in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplication } } - Context "When the service app doesn't exist and shouldn't" { - Mock Get-SPServiceApplication { return $null } + Context -Name "When the service app doesn't exist and shouldn't" -Fixture { + $testParams = @{ + Name = "State Service App" + DatabaseName = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPSubscriptionSettings.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPSubscriptionSettings.Tests.ps1 index 86e99442e..751704573 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPSubscriptionSettings.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPSubscriptionSettings.Tests.ps1 @@ -1,94 +1,148 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPSubscriptionSettingsServiceApp" -$ModuleName = "MSFT_SPSubscriptionSettingsServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPSubscriptionSettingsServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Test App" - ApplicationPool = "Test App Pool" - DatabaseName = "Test_DB" - DatabaseServer = "TestServer\Instance" - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") + # Initialize tests + $getTypeFullName = "Microsoft.SharePoint.SPSubscriptionSettingsServiceApplication" - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + # Mocks for all contexts + Mock -CommandName New-SPSubscriptionSettingsServiceApplication -MockWith { + return @{} } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Mock Remove-SPServiceApplication {} + Mock -CommandName New-SPSubscriptionSettingsServiceApplicationProxy -MockWith { + return @{} + } + Mock -CommandName Set-SPSubscriptionSettingsServiceApplication -MockWith { } + Mock -CommandName Remove-SPServiceApplication -MockWith { } - Context "When no service applications exist in the current farm" { + # Test contexts + Context -Name "When no service applications exist in the current farm" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "Test App Pool" + DatabaseName = "Test_DB" + DatabaseServer = "TestServer\Instance" + Ensure = "Present" + } - Mock Get-SPServiceApplication { return $null } - Mock New-SPSubscriptionSettingsServiceApplication { return @{}} - Mock New-SPSubscriptionSettingsServiceApplicationProxy { return @{}} - It "returns absent from the Get method" { + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } + + Mock -CommandName New-SPSubscriptionSettingsServiceApplication -MockWith { + return @{} + } + + Mock -CommandName New-SPSubscriptionSettingsServiceApplicationProxy -MockWith { + return @{} + } + + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPSubscriptionSettingsServiceApplication Assert-MockCalled New-SPSubscriptionSettingsServiceApplicationProxy } } - Context "When service applications exist in the current farm but the specific subscription settings service app does not" { + Context -Name "When service applications exist in the current farm but the specific subscription settings service app does not" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "Test App Pool" + DatabaseName = "Test_DB" + DatabaseServer = "TestServer\Instance" + Ensure = "Present" + } - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Some other service app type" - }) } + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = "Microsoft.Office.UnKnownWebServiceApplication" + } + } -PassThru -Force + return $spServiceApp + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - } - Context "When a service application exists and is configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When a service application exists and is configured correctly" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "Test App Pool" + DatabaseName = "Test_DB" + DatabaseServer = "TestServer\Instance" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Microsoft SharePoint Foundation Subscription Settings Service Application" DisplayName = $testParams.Name - ApplicationPool = @{ Name = $testParams.ApplicationPool } + ApplicationPool = @{ + Name = $testParams.ApplicationPool + } Database = @{ Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } - Context "When a service application exists and the app pool is not configured correctly" { - Mock Get-SPServiceApplication { - $service = @(@{ + Context -Name "When a service application exists and the app pool is not configured correctly" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "Test App Pool" + DatabaseName = "Test_DB" + DatabaseServer = "TestServer\Instance" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [pscustomobject]@{ TypeName = "Microsoft SharePoint Foundation Subscription Settings Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = "Wrong App Pool Name" } @@ -96,95 +150,119 @@ Describe "SPSubscriptionSettingsServiceApp - SharePoint Build $((Get-Item $Share Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } } - }) - - $service = $service | Add-Member ScriptMethod Update { - $Global:SPSubscriptionServiceUpdateCalled = $true - } -PassThru - return $service - + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value { + $Global:SPDscSubscriptionServiceUpdateCalled = $true + } -PassThru + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name FullName ` + -Value $getTypeFullName ` + -PassThru + } -PassThru -Force + return $spServiceApp + } + Mock -CommandName Get-SPServiceApplicationPool { + return @{ + Name = $testParams.ApplicationPool + } } - Mock Get-SPServiceApplicationPool { return @{ Name = $testParams.ApplicationPool } } - Mock Set-SPSubscriptionSettingsServiceApplication { } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - $Global:SPSubscriptionServiceUpdateCalled = $false - It "calls the update service app cmdlet from the set method" { + It "Should call the update service app cmdlet from the set method" { + $Global:SPDscSubscriptionServiceUpdateCalled = $false Set-TargetResource @testParams - Assert-MockCalled Get-SPServiceApplicationPool - $Global:SPSubscriptionServiceUpdateCalled | Should Be $true + $Global:SPDscSubscriptionServiceUpdateCalled | Should Be $true } } - Context "When a service app needs to be created and no database parameters are provided" { + Context -Name "When a service app needs to be created and no database parameters are provided" -Fixture { $testParams = @{ Name = "Test App" ApplicationPool = "Test App Pool" Ensure = "Present" } - Mock Get-SPServiceApplication { return $null } - Mock New-SPSubscriptionSettingsServiceApplication {return @{} } - Mock New-SPSubscriptionSettingsServiceApplicationProxy { return @{}} + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - it "should not throw an exception in the set method" { + It "should not throw an exception in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPSubscriptionSettingsServiceApplication Assert-MockCalled New-SPSubscriptionSettingsServiceApplicationProxy } } - $testParams = @{ - Name = "Test App" - ApplicationPool = "-" - Ensure = "Absent" - } - - Context "When the service app exists but it shouldn't" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When the service app exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Microsoft SharePoint Foundation Subscription Settings Service Application" DisplayName = $testParams.Name - ApplicationPool = @{ Name = $testParams.ApplicationPool } + ApplicationPool = @{ + Name = $testParams.ApplicationPool + } Database = @{ - Name = "Database" - Server = @{ Name = "Server" } + Name = $testParams.DatabaseName + Server = @{ Name = $testParams.DatabaseServer } } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns present from the Get method" { + It "Should return present from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the service application in the set method" { + It "Should remove the service application in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplication } } - Context "When the service app doesn't exist and shouldn't" { - Mock Get-SPServiceApplication { return $null } + Context -Name "When the service app doesn't exist and shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } } } - - +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPTimerJobState.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPTimerJobState.Tests.ps1 index 8bc15063b..31bfcf3fa 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPTimerJobState.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPTimerJobState.Tests.ps1 @@ -1,51 +1,66 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPTimerJobState" -$ModuleName = "MSFT_SPTimerJobState" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPTimerJobState - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "job-spapp-statequery" - Enabled = $true - Schedule = "hourly between 0 and 59" + # Initialize tests + + # Mocks for all contexts + Mock -CommandName Set-SPTimerJob -MockWith { + return $null } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + Mock -CommandName Get-SPFarm -MockWith { + return @{} } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Context "The server is not part of SharePoint farm" { - Mock Get-SPFarm { throw "Unable to detect local farm" } + # Test contexts + Context -Name "The server is not part of SharePoint farm" -Fixture { + $testParams = @{ + Name = "job-spapp-statequery" + Enabled = $true + Schedule = "hourly between 0 and 59" + } + + Mock -CommandName Get-SPFarm -MockWith { + throw "Unable to detect local farm" + } - It "return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Be $null } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws an exception in the set method to say there is no local farm" { + It "Should throw an exception in the set method to say there is no local farm" { { Set-TargetResource @testParams } | Should throw "No local SharePoint farm was detected" } } - Context "The server is in a farm and the incorrect enabled settings have been applied" { - Mock Get-SPTimerJob { + Context -Name "The server is in a farm and the incorrect enabled settings have been applied" -Fixture { + $testParams = @{ + Name = "job-spapp-statequery" + Enabled = $true + Schedule = "hourly between 0 and 59" + } + + Mock -CommandName Get-SPTimerJob -MockWith { $returnVal = @{ Name = "job-spapp-statequery" IsDisabled = $true @@ -53,25 +68,29 @@ Describe "SPTimerJobState - SharePoint Build $((Get-Item $SharePointCmdletModule } return @($returnVal) } - Mock Set-SPTimerJob { return $null } - Mock Get-SPFarm { return @{} } - It "return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "updates the timerjob settings" { + It "Should update the timerjob settings" { Set-TargetResource @testParams Assert-MockCalled Set-SPTimerJob } } - Context "The server is in a farm and the incorrect schedule settings have been applied" { - Mock Get-SPTimerJob { + Context -Name "The server is in a farm and the incorrect schedule settings have been applied" -Fixture { + $testParams = @{ + Name = "job-spapp-statequery" + Enabled = $true + Schedule = "hourly between 0 and 59" + } + + Mock -CommandName Get-SPTimerJob -MockWith { $returnVal = @{ Name = "job-spapp-statequery" IsDisabled = $false @@ -79,25 +98,29 @@ Describe "SPTimerJobState - SharePoint Build $((Get-Item $SharePointCmdletModule } return @($returnVal) } - Mock Set-SPTimerJob { return $null } - Mock Get-SPFarm { return @{} } - It "return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "updates the timer job settings" { + It "Should update the timer job settings" { Set-TargetResource @testParams Assert-MockCalled Set-SPTimerJob } } - Context "The server is in a farm and the incorrect schedule format has been used" { - Mock Get-SPTimerJob { + Context -Name "The server is in a farm and the incorrect schedule format has been used" -Fixture { + $testParams = @{ + Name = "job-spapp-statequery" + Enabled = $true + Schedule = "hourly between 0 and 59" + } + + Mock -CommandName Get-SPTimerJob -MockWith { $returnVal = @{ Name = "job-spapp-statequery" IsDisabled = $false @@ -105,24 +128,32 @@ Describe "SPTimerJobState - SharePoint Build $((Get-Item $SharePointCmdletModule } return @($returnVal) } - Mock Set-SPTimerJob { throw "Invalid Time: `"The time given was not given in the proper format. See: Get-Help Set-SPTimerJob -detailed`"" } - Mock Get-SPFarm { return @{} } - It "return values from the get method" { + Mock -CommandName Set-SPTimerJob -MockWith { + throw "Invalid Time: `"The time given was not given in the proper format. See: Get-Help Set-SPTimerJob -detailed`"" + } + + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws an exception because the incorrect schedule format is used" { + It "Should throw an exception because the incorrect schedule format is used" { { Set-TargetResource @testParams } | Should throw "Incorrect schedule format used. New schedule will not be applied." } } - Context "The server is in a farm and the correct settings have been applied" { - Mock Get-SPTimerJob { + Context -Name "The server is in a farm and the correct settings have been applied" -Fixture { + $testParams = @{ + Name = "job-spapp-statequery" + Enabled = $true + Schedule = "hourly between 0 and 59" + } + + Mock -CommandName Get-SPTimerJob -MockWith { $returnVal = @{ Name = "job-spapp-statequery" IsDisabled = $false @@ -130,15 +161,16 @@ Describe "SPTimerJobState - SharePoint Build $((Get-Item $SharePointCmdletModule } return @($returnVal) } - Mock Get-SPFarm { return @{} } - It "return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPTrustedIdentityTokenIssuer.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPTrustedIdentityTokenIssuer.Tests.ps1 index 2339aa2c5..2e437331f 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPTrustedIdentityTokenIssuer.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPTrustedIdentityTokenIssuer.Tests.ps1 @@ -1,50 +1,25 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPTrustedIdentityTokenIssuer" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPTrustedIdentityTokenIssuer - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Contoso" - Description = "Contoso" - Realm = "https://sharepoint.contoso.com" - SignInUrl = "https://adfs.contoso.com/adfs/ls/" - IdentifierClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" - ClaimsMappings = @( - (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ - Name = "Email" - IncomingClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" - } -ClientOnly) - (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ - Name = "Role" - IncomingClaimType = "http://schemas.xmlsoap.org/ExternalSTSGroupType" - LocalClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" - } -ClientOnly) - ) - SigningCertificateThumbPrint = "Mock Thumbrpint" - ClaimProviderName = "LDAPCP" - ProviderSignOutUri = "https://adfs.contoso.com/adfs/ls/" - Ensure = "Present" - Verbose = $true - } +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Mock Get-ChildItem { +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPTrustedIdentityTokenIssuer" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Mocks for all contexts + Mock -CommandName Get-ChildItem -MockWith { return @( @{ Thumbprint = "Mock Thumbrpint" @@ -52,50 +27,93 @@ Describe "SPTrustedIdentityTokenIssuer - SharePoint Build $((Get-Item $SharePoin ) } - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue + # Test contexts + Context -Name "The SPTrustedIdentityTokenIssuer does not exist, but it should be present" -Fixture { + $testParams = @{ + Name = "Contoso" + Description = "Contoso" + Realm = "https://sharepoint.contoso.com" + SignInUrl = "https://adfs.contoso.com/adfs/ls/" + IdentifierClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" + ClaimsMappings = @( + (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ + Name = "Email" + IncomingClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" + } -ClientOnly) + (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ + Name = "Role" + IncomingClaimType = "http://schemas.xmlsoap.org/ExternalSTSGroupType" + LocalClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" + } -ClientOnly) + ) + SigningCertificateThumbPrint = "Mock Thumbrpint" + ClaimProviderName = "LDAPCP" + ProviderSignOutUri = "https://adfs.contoso.com/adfs/ls/" + Ensure = "Present" + } - Context "The SPTrustedIdentityTokenIssuer does not exist, but it should be present" { - Mock New-SPTrustedIdentityTokenIssuer { + Mock -CommandName New-SPTrustedIdentityTokenIssuer -MockWith { $sptrust = [pscustomobject]@{ Name = $testParams.Name ClaimProviderName = "" ProviderSignOutUri = "" } - $sptrust| Add-Member -Name Update -MemberType ScriptMethod -Value { } + $sptrust | Add-Member -Name Update -MemberType ScriptMethod -Value { } return $sptrust } - Mock New-SPClaimTypeMapping { + Mock -CommandName New-SPClaimTypeMapping -MockWith { return [pscustomobject]@{ MappedClaimType = $testParams.IdentifierClaim } } - $getResults = Get-TargetResource @testParams - - It "returns absent from the get method" { + It "Should return absent from the get method" { + $getResults = Get-TargetResource @testParams $getResults.Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "creates the SPTrustedIdentityTokenIssuer" { + It "Should create the SPTrustedIdentityTokenIssuer" { Set-TargetResource @testParams Assert-MockCalled New-SPTrustedIdentityTokenIssuer } } - Context "The SPTrustedIdentityTokenIssuer does not exist, but it should be present and claims provider specified exists on the farm" { - Mock Get-SPClaimProvider { + Context -Name "The SPTrustedIdentityTokenIssuer does not exist, but it should be present and claims provider specified exists on the farm" -Fixture { + $testParams = @{ + Name = "Contoso" + Description = "Contoso" + Realm = "https://sharepoint.contoso.com" + SignInUrl = "https://adfs.contoso.com/adfs/ls/" + IdentifierClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" + ClaimsMappings = @( + (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ + Name = "Email" + IncomingClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" + } -ClientOnly) + (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ + Name = "Role" + IncomingClaimType = "http://schemas.xmlsoap.org/ExternalSTSGroupType" + LocalClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" + } -ClientOnly) + ) + SigningCertificateThumbPrint = "Mock Thumbrpint" + ClaimProviderName = "LDAPCP" + ProviderSignOutUri = "https://adfs.contoso.com/adfs/ls/" + Ensure = "Present" + } + + Mock -CommandName Get-SPClaimProvider -MockWith { return [pscustomobject]@(@{ DisplayName = $testParams.ClaimProviderName }) } - Mock New-SPTrustedIdentityTokenIssuer { + Mock -CommandName New-SPTrustedIdentityTokenIssuer -MockWith { $sptrust = [pscustomobject]@{ Name = $testParams.Name ClaimProviderName = "" @@ -105,32 +123,52 @@ Describe "SPTrustedIdentityTokenIssuer - SharePoint Build $((Get-Item $SharePoin return $sptrust } - Mock Get-SPTrustedIdentityTokenIssuer { + Mock -CommandName Get-SPTrustedIdentityTokenIssuer -MockWith { $sptrust = [pscustomobject]@{ Name = $testParams.Name ClaimProviderName = $testParams.ClaimProviderName ProviderSignOutUri = "" } - $sptrust| Add-Member -Name Update -MemberType ScriptMethod -Value { } + $sptrust| Add-Member -Name Update -MemberType ScriptMethod -Value { } return $sptrust } - Mock New-SPClaimTypeMapping { + Mock -CommandName New-SPClaimTypeMapping -MockWith { return [pscustomobject]@{ MappedClaimType = $testParams.IdentifierClaim } } - - Set-TargetResource @testParams - $getResults = Get-TargetResource @testParams - - It "creates the SPTrustedIdentityTokenIssuer and sets claims provider" { - $getResults.ClaimProviderName | Should Be $testParams.ClaimProviderName + + It "Should create the SPTrustedIdentityTokenIssuer and sets claims provider" { + Set-TargetResource @testParams } } - Context "The SPTrustedIdentityTokenIssuer already exists, and it should be present" { - Mock Get-SPTrustedIdentityTokenIssuer { + Context -Name "The SPTrustedIdentityTokenIssuer already exists, and it should be present" -Fixture { + $testParams = @{ + Name = "Contoso" + Description = "Contoso" + Realm = "https://sharepoint.contoso.com" + SignInUrl = "https://adfs.contoso.com/adfs/ls/" + IdentifierClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" + ClaimsMappings = @( + (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ + Name = "Email" + IncomingClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" + } -ClientOnly) + (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ + Name = "Role" + IncomingClaimType = "http://schemas.xmlsoap.org/ExternalSTSGroupType" + LocalClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" + } -ClientOnly) + ) + SigningCertificateThumbPrint = "Mock Thumbrpint" + ClaimProviderName = "LDAPCP" + ProviderSignOutUri = "https://adfs.contoso.com/adfs/ls/" + Ensure = "Present" + } + + Mock -CommandName Get-SPTrustedIdentityTokenIssuer -MockWith { $sptrust = [pscustomobject]@{ Name = $testParams.Name ClaimProviderName = "" @@ -139,56 +177,91 @@ Describe "SPTrustedIdentityTokenIssuer - SharePoint Build $((Get-Item $SharePoin return $sptrust } - $getResults = Get-TargetResource @testParams - - It "returns present from the get method" { + It "Should return present from the get method" { + $getResults = Get-TargetResource @testParams $getResults.Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } - - It "doe not create the SPTrustedIdentityTokenIssuer" { - Set-TargetResource @testParams - } } - $testParams.Ensure = "Absent" + Context -Name "The SPTrustedIdentityTokenIssuer exists, but it should be absent" -Fixture { + $testParams = @{ + Name = "Contoso" + Description = "Contoso" + Realm = "https://sharepoint.contoso.com" + SignInUrl = "https://adfs.contoso.com/adfs/ls/" + IdentifierClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" + ClaimsMappings = @( + (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ + Name = "Email" + IncomingClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" + } -ClientOnly) + (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ + Name = "Role" + IncomingClaimType = "http://schemas.xmlsoap.org/ExternalSTSGroupType" + LocalClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" + } -ClientOnly) + ) + SigningCertificateThumbPrint = "Mock Thumbrpint" + ClaimProviderName = "LDAPCP" + ProviderSignOutUri = "https://adfs.contoso.com/adfs/ls/" + Ensure = "Absent" + } - Context "The SPTrustedIdentityTokenIssuer exists, but it should be absent" { - Mock Get-SPTrustedIdentityTokenIssuer { + Mock -CommandName Get-SPTrustedIdentityTokenIssuer -MockWith { $sptrust = [pscustomobject]@{ Name = $testParams.Name } - $sptrust| Add-Member -Name Update -MemberType ScriptMethod -Value { } + $sptrust | Add-Member -Name Update -MemberType ScriptMethod -Value { } return $sptrust } - Mock Remove-SPTrustedIdentityTokenIssuer { } -Verifiable + Mock -CommandName Remove-SPTrustedIdentityTokenIssuer -MockWith { } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $false } - It "removes the SPTrustedIdentityTokenIssuer" { + It "Should remove the SPTrustedIdentityTokenIssuer" { Set-TargetResource @testParams Assert-MockCalled Remove-SPTrustedIdentityTokenIssuer } } - $testParams.Ensure = "Present" - $originalIdentifierClaim = $testParams.IdentifierClaim - $testParams.IdentifierClaim = "UnknownClaimType" + Context -Name "The IdentifierClaim does not match one of the claim types in ClaimsMappings" -Fixture { + $testParams = @{ + Name = "Contoso" + Description = "Contoso" + Realm = "https://sharepoint.contoso.com" + SignInUrl = "https://adfs.contoso.com/adfs/ls/" + IdentifierClaim = "UnknownClaimType" + ClaimsMappings = @( + (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ + Name = "Email" + IncomingClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" + } -ClientOnly) + (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ + Name = "Role" + IncomingClaimType = "http://schemas.xmlsoap.org/ExternalSTSGroupType" + LocalClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" + } -ClientOnly) + ) + SigningCertificateThumbPrint = "Mock Thumbrpint" + ClaimProviderName = "LDAPCP" + ProviderSignOutUri = "https://adfs.contoso.com/adfs/ls/" + Ensure = "Present" + } - Context "The IdentifierClaim does not match one of the claim types in ClaimsMappings" { - Mock New-SPClaimTypeMapping { + Mock -CommandName New-SPClaimTypeMapping -MockWith { return [pscustomobject]@{ - MappedClaimType = $originalIdentifierClaim + MappedClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" } } @@ -197,14 +270,35 @@ Describe "SPTrustedIdentityTokenIssuer - SharePoint Build $((Get-Item $SharePoin } } - $testParams.IdentifierClaim = $originalIdentifierClaim - $testParams.SigningCertificateThumbPrint = "UnknownSigningCertificateThumbPrint" + Context -Name "The certificate thumbprint does not match a certificate in certificate store LocalMachine\My" -Fixture { + $testParams = @{ + Name = "Contoso" + Description = "Contoso" + Realm = "https://sharepoint.contoso.com" + SignInUrl = "https://adfs.contoso.com/adfs/ls/" + IdentifierClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" + ClaimsMappings = @( + (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ + Name = "Email" + IncomingClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" + } -ClientOnly) + (New-CimInstance -ClassName MSFT_SPClaimTypeMapping -Property @{ + Name = "Role" + IncomingClaimType = "http://schemas.xmlsoap.org/ExternalSTSGroupType" + LocalClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" + } -ClientOnly) + ) + SigningCertificateThumbPrint = "UnknownSigningCertificateThumbPrint" + ClaimProviderName = "LDAPCP" + ProviderSignOutUri = "https://adfs.contoso.com/adfs/ls/" + Ensure = "Present" + } - Context "The certificate thumbprint does not match a certificate in certificate store LocalMachine\My" { - It "validation of SigningCertificateThumbPrint fails in the set method" { + It "Should fail validation of SigningCertificateThumbPrint in the set method" { { Set-TargetResource @testParams } | Should Throw "The certificate thumbprint does not match a certificate in certificate store LocalMachine\My." } } } } +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPUsageApplication.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPUsageApplication.Tests.ps1 new file mode 100644 index 000000000..848207766 --- /dev/null +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPUsageApplication.Tests.ps1 @@ -0,0 +1,374 @@ +[CmdletBinding()] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] +param( + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) +) + +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPUsageApplication" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Initialize tests + $getTypeFullName = "Microsoft.SharePoint.Administration.SPUsageApplication" + $getTypeFullNameProxy = "Microsoft.SharePoint.Administration.SPUsageApplicationProxy" + + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential ` + -ArgumentList @("DOMAIN\username", $mockPassword) + + # Mocks for all contexts + Mock -CommandName New-SPUsageApplication -MockWith { } + Mock -CommandName Set-SPUsageService -MockWith { } + Mock -CommandName Get-SPUsageService -MockWith { + return @{ + UsageLogCutTime = $testParams.UsageLogCutTime + UsageLogDir = $testParams.UsageLogLocation + UsageLogMaxFileSize = ($testParams.UsageLogMaxFileSizeKB * 1024) + UsageLogMaxSpaceGB = $testParams.UsageLogMaxSpaceGB + } + } + Mock -CommandName Remove-SPServiceApplication -MockWith {} + Mock -CommandName Get-SPServiceApplicationProxy -MockWith { + return (New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name Provision ` + -Value {} ` + -PassThru | + Add-Member -NotePropertyName Status ` + -NotePropertyValue "Online" ` + -PassThru | + Add-Member -NotePropertyName TypeName ` + -NotePropertyValue "Usage and Health Data Collection Proxy" ` + -PassThru) + } + + # Test contexts + Context -Name "When no service applications exist in the current farm" -Fixture { + $testParams = @{ + Name = "Usage Service App" + UsageLogCutTime = 60 + UsageLogLocation = "L:\UsageLogs" + UsageLogMaxFileSizeKB = 1024 + UsageLogMaxSpaceGB = 10 + DatabaseName = "SP_Usage" + DatabaseServer = "sql.test.domain" + FailoverDatabaseServer = "anothersql.test.domain" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { return $null } + + It "Should return null from the Get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Absent" + } + + It "Should return false when the Test method is called" { + Test-TargetResource @testParams | Should Be $false + } + + It "Should create a new service application in the set method" { + Set-TargetResource @testParams + Assert-MockCalled New-SPUsageApplication + } + + It "Should create a new service application with custom database credentials" { + $testParams.Add("DatabaseCredentials", $mockCredential) + Set-TargetResource @testParams + Assert-MockCalled New-SPUsageApplication + } + } + + Context -Name "When service applications exist in the current farm but not the specific usage service app" -Fixture { + $testParams = @{ + Name = "Usage Service App" + UsageLogCutTime = 60 + UsageLogLocation = "L:\UsageLogs" + UsageLogMaxFileSizeKB = 1024 + UsageLogMaxSpaceGB = 10 + DatabaseName = "SP_Usage" + DatabaseServer = "sql.test.domain" + FailoverDatabaseServer = "anothersql.test.domain" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = "Microsoft.Office.UnKnownWebServiceApplication" + } + } -PassThru -Force + return $spServiceApp + } + + It "Should return absent from the Get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Absent" + } + + It "Should return false when the Test method is called" { + Test-TargetResource @testParams | Should Be $false + } + } + + Context -Name "When a service application exists and is configured correctly" -Fixture { + $testParams = @{ + Name = "Usage Service App" + UsageLogCutTime = 60 + UsageLogLocation = "L:\UsageLogs" + UsageLogMaxFileSizeKB = 1024 + UsageLogMaxSpaceGB = 10 + DatabaseName = "SP_Usage" + DatabaseServer = "sql.test.domain" + FailoverDatabaseServer = "anothersql.test.domain" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + TypeName = "Usage and Health Data Collection Service Application" + DisplayName = $testParams.Name + UsageDatabase = @{ + Name = $testParams.DatabaseName + Server = @{ Name = $testParams.DatabaseServer } + } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + + It "Should return values from the get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Present" + } + + It "Should return true when the Test method is called" { + Test-TargetResource @testParams | Should Be $true + } + } + + Context -Name "When a service application exists and log path are not configured correctly" -Fixture { + $testParams = @{ + Name = "Usage Service App" + UsageLogCutTime = 60 + UsageLogLocation = "L:\UsageLogs" + UsageLogMaxFileSizeKB = 1024 + UsageLogMaxSpaceGB = 10 + DatabaseName = "SP_Usage" + DatabaseServer = "sql.test.domain" + FailoverDatabaseServer = "anothersql.test.domain" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + TypeName = "Usage and Health Data Collection Service Application" + DisplayName = $testParams.Name + UsageDatabase = @{ + Name = $testParams.DatabaseName + Server = @{ Name = $testParams.DatabaseServer } + } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + + Mock -CommandName Get-SPUsageService -MockWith { + return @{ + UsageLogCutTime = $testParams.UsageLogCutTime + UsageLogDir = "C:\Wrong\Location" + UsageLogMaxFileSize = ($testParams.UsageLogMaxFileSizeKB * 1024) + UsageLogMaxSpaceGB = $testParams.UsageLogMaxSpaceGB + } + } + + It "Should return false when the Test method is called" { + Test-TargetResource @testParams | Should Be $false + } + + It "Should call the update service app cmdlet from the set method" { + Set-TargetResource @testParams + Assert-MockCalled Set-SPUsageService + } + } + + Context -Name "When a service application exists and log size is not configured correctly" -Fixture { + $testParams = @{ + Name = "Usage Service App" + UsageLogCutTime = 60 + UsageLogLocation = "L:\UsageLogs" + UsageLogMaxFileSizeKB = 1024 + UsageLogMaxSpaceGB = 10 + DatabaseName = "SP_Usage" + DatabaseServer = "sql.test.domain" + FailoverDatabaseServer = "anothersql.test.domain" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + TypeName = "Usage and Health Data Collection Service Application" + DisplayName = $testParams.Name + UsageDatabase = @{ + Name = $testParams.DatabaseName + Server = @{ Name = $testParams.DatabaseServer } + } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + + Mock -CommandName Get-SPUsageService -MockWith { + return @{ + UsageLogCutTime = $testParams.UsageLogCutTime + UsageLogDir = $testParams.UsageLogLocation + UsageLogMaxFileSize = ($testParams.UsageLogMaxFileSizeKB * 1024) + UsageLogMaxSpaceGB = 1 + } + } + + It "Should return false when the Test method is called" { + Test-TargetResource @testParams | Should Be $false + } + + It "Should call the update service app cmdlet from the set method" { + Set-TargetResource @testParams + Assert-MockCalled Set-SPUsageService + } + } + + Context -Name "When the service app exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + TypeName = "Usage and Health Data Collection Service Application" + DisplayName = $testParams.Name + UsageDatabase = @{ + Name = "db" + Server = @{ + Name = "server" + } + } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + + 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 remove the service application in the set method" { + Set-TargetResource @testParams + Assert-MockCalled Remove-SPServiceApplication + } + } + + Context -Name "When the service app doesn't exist and shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } + + 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 $true + } + } + + Context -Name "The proxy for the service app is offline when it should be running" -Fixture { + $testParams = @{ + Name = "Test App" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + TypeName = "Usage and Health Data Collection Service Application" + DisplayName = $testParams.Name + UsageDatabase = @{ + Name = "db" + Server = @{ + Name = "server" + } + } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + + Mock -CommandName Get-SPServiceApplicationProxy -MockWith { + $proxy = (New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod ` + -Name Provision ` + -Value { + $Global:SPDscUSageAppProxyStarted = $true + } -PassThru | + Add-Member -NotePropertyName Status ` + -NotePropertyValue "Disabled" ` + -PassThru | + Add-Member -NotePropertyName TypeName ` + -NotePropertyValue "Usage and Health Data Collection Proxy" ` + -PassThru) + $proxy = $proxy | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullNameProxy } + } -PassThru -Force + return $proxy + } + + 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 start the proxy in the set method" { + $Global:SPDscUSageAppProxyStarted = $false + Set-TargetResource @testParams + $Global:SPDscUSageAppProxyStarted | Should Be $true + } + } + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileProperty.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileProperty.Tests.ps1 index 79ce7394f..26bce7698 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileProperty.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileProperty.Tests.ps1 @@ -1,19 +1,33 @@ [CmdletBinding()] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPUserProfileProperty" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPUserProfileProperty" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + + # Pester seems to have an issue with the mocks of New-Object when this sits inside the ModuleName + # scope. I have no idea why and it drives me nuts that this is here because it breaks the simple + # test template I had, but I didnt wanna hold things up on the rest of the test refactoring, so + # here it is. Will resolve later when I can understand what is going on here. - Brian + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $farmAccount = New-Object -TypeName "System.Management.Automation.PSCredential" ` + -ArgumentList @("username", $mockPassword) + + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { $testParamsNewProperty = @{ Name = "WorkEmailNew" UserProfileService = "User Profile Service Application" @@ -38,9 +52,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet TermSet = "Department" UserOverridePrivacy = $false } - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - $farmAccount = New-Object System.Management.Automation.PSCredential ("domain\username", (ConvertTo-SecureString "password" -AsPlainText -Force)) + $testParamsUpdateProperty = @{ Name = "WorkEmailUpdate" UserProfileService = "User Profile Service Application" @@ -76,8 +88,6 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet } "@ -ErrorAction SilentlyContinue } - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") $corePropertyUpdate = @{ DisplayName = "WorkEmailUpdate" @@ -203,7 +213,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet return $subTypePropertyUpdate } -PassThru #$userProfileSubTypePropertiesValidProperty.Add($subTypeProperty); - mock Get-SPDSCUserProfileSubTypeManager -MockWith { + Mock -CommandName Get-SPDSCUserProfileSubTypeManager -MockWith { $result = @{}| Add-Member ScriptMethod GetProfileSubtype { $Global:SPUPGetProfileSubtypeCalled = $true return @{ @@ -215,7 +225,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet } - Mock Get-SPWebApplication -MockWith { + Mock -CommandName Get-SPWebApplication -MockWith { return @( @{ IsAdministrationWebApplication=$true @@ -238,13 +248,13 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet }} - Mock New-Object -MockWith { + Mock -CommandName New-Object -MockWith { return (@{ TermStores = $TermStoresList }) } -ParameterFilter { $TypeName -eq "Microsoft.SharePoint.Taxonomy.TaxonomySession" } - Mock New-Object -MockWith { + Mock -CommandName New-Object -MockWith { return (@{ Properties = @{} | Add-Member ScriptMethod SetDisplayOrderByPropertyName { $Global:UpsSetDisplayOrderByPropertyNameCalled=$true; @@ -259,7 +269,6 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet } - Mock New-PSSession { return $null } -ModuleName "SharePointDsc.Util" $propertyMappingItem = @{ DataSourcePropertyName="mail" IsImport=$true @@ -303,7 +312,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet $forest, ` $useSSL, ` $userName, ` - $securePassword, ` + $pwd, ` $namingContext, ` $p1, $p2 ` ) @@ -312,7 +321,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet } -PassThru - Mock New-Object -MockWith { + Mock -CommandName New-Object -MockWith { $ProfilePropertyManager = @{"Contoso" = $connection} | Add-Member ScriptMethod GetCoreProperties { $Global:UpsConfigManagerGetCorePropertiesCalled=$true; @@ -336,15 +345,15 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet ApplicationPool = "SharePoint Service Applications" FarmAccount = $farmAccount ServiceApplicationProxyGroup = "Proxy Group" - ConnectionManager= @($connection) #New-Object System.Collections.ArrayList + ConnectionManager= @($connection) } - Mock Get-SPServiceApplication { return $userProfileServiceValidConnection } + Mock -CommandName Get-SPServiceApplication { return $userProfileServiceValidConnection } - Context "When property doesn't exist" { + Context -Name "When property doesn't exist" { - It "returns null from the Get method" { + It "Should return null from the Get method" { $Global:SPUPGetProfileSubtypeCalled = $false $Global:SPUPGetPropertyByNameCalled = $false $Global:SPUPSMappingItemCalled = $false @@ -355,7 +364,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet $Global:SPUPSMappingItemCalled | Should be $false } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { $Global:SPUPGetPropertyByNameCalled = $false Test-TargetResource @testParamsNewProperty | Should Be $false $Global:SPUPGetPropertyByNameCalled | Should be $true @@ -374,8 +383,8 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet } - Context "When property doesn't exist, connection doesn't exist" { - Mock New-Object -MockWith { + Context -Name "When property doesn't exist, connection doesn't exist" { + Mock -CommandName New-Object -MockWith { $ProfilePropertyManager = @{"Contoso" = $connection} | Add-Member ScriptMethod GetCoreProperties { $Global:UpsConfigManagerGetCorePropertiesCalled=$true; @@ -393,7 +402,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet } -PassThru ) } -ParameterFilter { $TypeName -eq "Microsoft.Office.Server.UserProfiles.UserProfileConfigManager" } - It "returns null from the Get method" { + It "Should return null from the Get method" { $Global:SPUPGetProfileSubtypeCalled = $false $Global:SPUPGetPropertyByNameCalled = $false $Global:SPUPSMappingItemCalled = $false @@ -404,7 +413,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet $Global:SPUPSMappingItemCalled | Should be $false } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { $Global:SPUPGetPropertyByNameCalled = $false Test-TargetResource @testParamsNewProperty | Should Be $false $Global:SPUPGetPropertyByNameCalled | Should be $true @@ -428,11 +437,11 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet } - Context "When property doesn't exist, term set doesn't exist" { + Context -Name "When property doesn't exist, term set doesn't exist" { $termSet = $testParamsNewProperty.TermSet $testParamsNewProperty.TermSet = "Invalid" - It "returns null from the Get method" { + It "Should return null from the Get method" { $Global:SPUPGetPropertyByNameCalled = $false $Global:SPUPGetPropertyByNameCalled = $false $Global:SPUPSMappingItemCalled = $false @@ -443,7 +452,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet $Global:SPUPSMappingItemCalled | Should be $false } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { $Global:SPUPGetPropertyByNameCalled = $false Test-TargetResource @testParamsNewProperty | Should Be $false $Global:SPUPGetPropertyByNameCalled | Should be $true @@ -463,11 +472,11 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet } - Context "When property doesn't exist, term group doesn't exist" { + Context -Name "When property doesn't exist, term group doesn't exist" { $termGroup = $testParamsNewProperty.TermGroup $testParamsNewProperty.TermGroup = "InvalidGroup" - It "returns null from the Get method" { + It "Should return null from the Get method" { $Global:SPUPGetPropertyByNameCalled = $false $Global:SPUPGetPropertyByNameCalled = $false $Global:SPUPSMappingItemCalled = $false @@ -478,7 +487,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet $Global:SPUPSMappingItemCalled | Should be $false } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { $Global:SPUPGetPropertyByNameCalled = $false Test-TargetResource @testParamsNewProperty | Should Be $false $Global:SPUPGetPropertyByNameCalled | Should be $true @@ -498,11 +507,11 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet } - Context "When property doesn't exist, term store doesn't exist" { + Context -Name "When property doesn't exist, term store doesn't exist" { $termStore = $testParamsNewProperty.TermStore $testParamsNewProperty.TermStore = "InvalidStore" - It "returns null from the Get method" { + It "Should return null from the Get method" { $Global:SPUPGetPropertyByNameCalled = $false $Global:SPUPGetPropertyByNameCalled = $false $Global:SPUPSMappingItemCalled = $false @@ -513,7 +522,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet $Global:SPUPSMappingItemCalled | Should be $false } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { $Global:SPUPGetPropertyByNameCalled = $false Test-TargetResource @testParamsNewProperty | Should Be $false $Global:SPUPGetPropertyByNameCalled | Should be $true @@ -535,8 +544,8 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet } - Context "When property exists and all properties match" { - mock Get-SPDSCUserProfileSubTypeManager -MockWith { + Context -Name "When property exists and all properties match" { + Mock -CommandName Get-SPDSCUserProfileSubTypeManager -MockWith { $result = @{}| Add-Member ScriptMethod GetProfileSubtype { $Global:SPUPGetProfileSubtypeCalled = $true return @{ @@ -547,7 +556,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet return $result } - It "returns valid value from the Get method" { + It "Should return valid value from the Get method" { $Global:SPUPGetProfileSubtypeCalled = $false $Global:SPUPGetPropertyByNameCalled = $false $Global:SPUPSMappingItemCalled = $false @@ -558,7 +567,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet $Global:SPUPSMappingItemCalled | Should be $true } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { $Global:SPUPGetPropertyByNameCalled = $false Test-TargetResource @testParamsUpdateProperty | Should Be $true $Global:SPUPGetPropertyByNameCalled | Should be $true @@ -576,10 +585,10 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet } - Context "When property exists and type is different - throws exception" { + Context -Name "When property exists and type is different - throws exception" { $currentType = $testParamsUpdateProperty.Type $testParamsUpdateProperty.Type = "StringMultiValue" - mock Get-SPDSCUserProfileSubTypeManager -MockWith { + Mock -CommandName Get-SPDSCUserProfileSubTypeManager -MockWith { $result = @{}| Add-Member ScriptMethod GetProfileSubtype { $Global:SPUPGetProfileSubtypeCalled = $true return @{ @@ -590,7 +599,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet return $result } - It "returns valid value from the Get method" { + It "Should return valid value from the Get method" { $Global:SPUPGetProfileSubtypeCalled = $false $Global:SPUPGetPropertyByNameCalled = $false $Global:SPUPSMappingItemCalled = $false @@ -601,7 +610,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet $Global:SPUPSMappingItemCalled | Should be $true } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { $Global:SPUPGetPropertyByNameCalled = $false Test-TargetResource @testParamsUpdateProperty | Should Be $false $Global:SPUPGetPropertyByNameCalled | Should be $true @@ -622,11 +631,11 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet } - Context "When property exists and mapping exists, mapping config does not match" { + Context -Name "When property exists and mapping exists, mapping config does not match" { $propertyMappingItem.DataSourcePropertyName = "property" - mock Get-SPDSCUserProfileSubTypeManager -MockWith { + Mock -CommandName Get-SPDSCUserProfileSubTypeManager -MockWith { $result = @{}| Add-Member ScriptMethod GetProfileSubtype { $Global:SPUPGetProfileSubtypeCalled = $true return @{ @@ -637,7 +646,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet return $result } - It "returns valid value from the Get method" { + It "Should return valid value from the Get method" { $Global:SPUPGetProfileSubtypeCalled = $false $Global:SPUPGetPropertyByNameCalled = $false $Global:SPUPSMappingItemCalled = $false @@ -648,7 +657,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet $Global:SPUPSMappingItemCalled | Should be $true } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { $Global:SPUPGetPropertyByNameCalled = $false Test-TargetResource @testParamsUpdateProperty | Should Be $false $Global:SPUPGetPropertyByNameCalled | Should be $true @@ -666,9 +675,9 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet $Global:SPUPSMappingItemCalled | Should be $true } } - Context "When property exists and mapping does not " { + Context -Name "When property exists and mapping does not " { $propertyMappingItem=$null - mock Get-SPDSCUserProfileSubTypeManager -MockWith { + Mock -CommandName Get-SPDSCUserProfileSubTypeManager -MockWith { $result = @{}| Add-Member ScriptMethod GetProfileSubtype { $Global:SPUPGetProfileSubtypeCalled = $true return @{ @@ -679,7 +688,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet return $result } - It "returns valid value from the Get method" { + It "Should return valid value from the Get method" { $Global:SPUPGetProfileSubtypeCalled = $false $Global:SPUPGetPropertyByNameCalled = $false $Global:SPUPSMappingItemCalled = $false @@ -690,7 +699,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet $Global:SPUPSMappingItemCalled | Should be $true } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { $Global:SPUPGetPropertyByNameCalled = $false Test-TargetResource @testParamsUpdateProperty | Should Be $false $Global:SPUPGetPropertyByNameCalled | Should be $true @@ -709,8 +718,8 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet } } - Context "When property exists and ensure equals Absent" { - mock Get-SPDSCUserProfileSubTypeManager -MockWith { + Context -Name "When property exists and ensure equals Absent" { + Mock -CommandName Get-SPDSCUserProfileSubTypeManager -MockWith { $result = @{}| Add-Member ScriptMethod GetProfileSubtype { $Global:SPUPGetProfileSubtypeCalled = $true return @{ @@ -735,5 +744,7 @@ Describe "SPUserProfileProperty - SharePoint Build $((Get-Item $SharePointCmdlet $Global:SPUPCoreRemovePropertyByNameCalled | Should be $true } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileSection.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileSection.Tests.ps1 index 5d05a6463..231902939 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileSection.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileSection.Tests.ps1 @@ -1,32 +1,33 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPUserProfileSection" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPUserProfileSection" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPUserProfileSection - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { $testParams= @{ Name = "PersonalInformation" UserProfileService = "User Profile Service Application" DisplayName = "Personal Information" DisplayOrder = 5000 } - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - try { [Microsoft.Office.Server.UserProfiles] } catch { - Add-Type @" + Add-Type -TypeDefinition @" namespace Microsoft.Office.Server.UserProfiles { public enum ConnectionType { ActiveDirectory, BusinessDataCatalog }; public enum ProfileType { User}; @@ -34,14 +35,13 @@ Describe "SPUserProfileSection - SharePoint Build $((Get-Item $SharePointCmdletM "@ -ErrorAction SilentlyContinue } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") $coreProperty = @{ DisplayName = $testParams.DisplayName Name = $testParams.Name - } | Add-Member ScriptMethod Commit { + } | Add-Member -MemberType ScriptMethod Commit { $Global:SPUPSPropertyCommitCalled = $true - } -PassThru | Add-Member ScriptMethod Delete { + } -PassThru | Add-Member -MemberType ScriptMethod Delete { $Global:SPUPSPropertyDeleteCalled = $true } -PassThru $subTypeProperty = @{ @@ -49,30 +49,30 @@ Describe "SPUserProfileSection - SharePoint Build $((Get-Item $SharePointCmdletM DisplayName= $testParams.DisplayName DisplayOrder =$testParams.DisplayOrder CoreProperty = $coreProperty - }| Add-Member ScriptMethod Commit { + }| Add-Member -MemberType ScriptMethod Commit { $Global:SPUPSPropertyCommitCalled = $true } -PassThru - $userProfileSubTypePropertiesNoProperty = @{} | Add-Member ScriptMethod Create { + $userProfileSubTypePropertiesNoProperty = @{} | Add-Member -MemberType ScriptMethod Create { param($section) $Global:SPUPSubTypeCreateCalled = $true - } -PassThru | Add-Member ScriptMethod GetSectionByName { + } -PassThru | Add-Member -MemberType ScriptMethod GetSectionByName { $result = $null if($Global:SPUPGetSectionByNameCalled -eq $TRUE){ $result = $subTypeProperty } $Global:SPUPGetSectionByNameCalled = $true return $result - } -PassThru| Add-Member ScriptMethod Add { + } -PassThru| Add-Member -MemberType ScriptMethod -Name Add -Value { $Global:SPUPSubTypeAddCalled = $true } -PassThru -Force $coreProperties = @{ProfileInformation = $coreProperty} - $userProfileSubTypePropertiesProperty = @{"ProfileInformation" = $subTypeProperty } | Add-Member ScriptMethod Create { + $userProfileSubTypePropertiesProperty = @{"ProfileInformation" = $subTypeProperty } | Add-Member -MemberType ScriptMethod Create { $Global:SPUPSubTypeCreateCalled = $true - } -PassThru | Add-Member ScriptMethod Add { + } -PassThru | Add-Member -MemberType ScriptMethod -Name Add -Value { $Global:SPUPSubTypeAddCalled = $true } -PassThru -Force - mock Get-SPDSCUserProfileSubTypeManager -MockWith { - $result = @{}| Add-Member ScriptMethod GetProfileSubtype { + Mock -CommandName Get-SPDSCUserProfileSubTypeManager -MockWith { + $result = @{}| Add-Member -MemberType ScriptMethod GetProfileSubtype { $Global:SPUPGetProfileSubtypeCalled = $true return @{ Properties = $userProfileSubTypePropertiesNoProperty @@ -82,42 +82,34 @@ Describe "SPUserProfileSection - SharePoint Build $((Get-Item $SharePointCmdletM return $result } - Mock Set-SPDscObjectPropertyIfValuePresent -MockWith {return ;} - Mock Get-SPWebApplication -MockWith { + Mock -CommandName Set-SPDscObjectPropertyIfValuePresent -MockWith {return ;} + Mock -CommandName Get-SPWebApplication -MockWith { return @( @{ IsAdministrationWebApplication=$true Url ="caURL" }) - } - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - - Mock New-PSSession { return $null } -ModuleName "SharePointDsc.Util" + } - - Mock New-Object -MockWith { + Mock -CommandName New-Object -MockWith { $ProfilePropertyManager = @{"Contoso" = $connection} return (@{ ProfilePropertyManager = $ProfilePropertyManager ConnectionManager = $ConnnectionManager - } | Add-Member ScriptMethod GetPropertiesWithSection { + } | Add-Member -MemberType ScriptMethod GetPropertiesWithSection { $Global:UpsConfigManagerGetPropertiesWithSectionCalled=$true; - $result = (@{}|Add-Member ScriptMethod Create { + $result = (@{}|Add-Member -MemberType ScriptMethod Create { param ($section) $result = @{Name = "" DisplayName="" - DisplayOrder=0}|Add-Member ScriptMethod Commit { + DisplayOrder=0}|Add-Member -MemberType ScriptMethod Commit { $Global:UpsConfigManagerCommitCalled=$true; } -PassThru return $result - } -PassThru -Force | Add-Member ScriptMethod GetSectionByName { + } -PassThru -Force | Add-Member -MemberType ScriptMethod GetSectionByName { $result = $null if($Global:UpsConfigManagerGetSectionByNameCalled -eq $TRUE){ $result = $subTypeProperty @@ -125,13 +117,13 @@ Describe "SPUserProfileSection - SharePoint Build $((Get-Item $SharePointCmdletM $Global:UpsConfigManagerGetSectionByNameCalled=$true return $result return $userProfileSubTypePropertiesUpdateProperty; - } -PassThru | Add-Member ScriptMethod SetDisplayOrderBySectionName { + } -PassThru | Add-Member -MemberType ScriptMethod SetDisplayOrderBySectionName { $Global:UpsConfigManagerSetDisplayOrderBySectionNameCalled=$true; return $userProfileSubTypePropertiesUpdateProperty; - } -PassThru | Add-Member ScriptMethod CommitDisplayOrder { + } -PassThru | Add-Member -MemberType ScriptMethod CommitDisplayOrder { $Global:UpsConfigManagerCommitDisplayOrderCalled=$true; return $userProfileSubTypePropertiesUpdateProperty; - } -PassThru| Add-Member ScriptMethod RemoveSectionByName { + } -PassThru| Add-Member -MemberType ScriptMethod RemoveSectionByName { $Global:UpsConfigManagerRemoveSectionByNameCalled=$true; return ($coreProperties); } -PassThru @@ -149,25 +141,25 @@ Describe "SPUserProfileSection - SharePoint Build $((Get-Item $SharePointCmdletM ServiceApplicationProxyGroup = "Proxy Group" } - Mock Get-SPServiceApplication { return $userProfileService } + Mock -CommandName Get-SPServiceApplication -MockWith { return $userProfileService } - Context "When section doesn't exist" { + Context -Name "When section doesn't exist" { - It "returns null from the Get method" { + It "Should return null from the Get method" { $Global:UpsConfigManagerGetSectionByNameCalled = $false (Get-TargetResource @testParams).Ensure | Should Be "Absent" Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.UserProfileService } $Global:UpsConfigManagerGetSectionByNameCalled | Should be $true } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { $Global:UpsConfigManagerGetSectionByNameCalled = $false Test-TargetResource @testParams | Should Be $false $Global:UpsConfigManagerGetSectionByNameCalled | Should be $true } - It "creates a new user profile section in the set method" { + It "Should create a new user profile section in the set method" { $Global:SPUPSubTypeCreateCalled = $false $Global:UpsConfigManagerSetDisplayOrderBySectionNameCalled = $false $Global:SPUPSPropertyCommitCalled=$false; @@ -179,18 +171,18 @@ Describe "SPUserProfileSection - SharePoint Build $((Get-Item $SharePointCmdletM } } - Context "When section exists and all properties match" { - It "returns valid value from the Get method" { + Context -Name "When section exists and all properties match" { + It "Should return valid value from the Get method" { $Global:UpsConfigManagerGetSectionByNameCalled = $true (Get-TargetResource @testParams).Ensure | Should Be "Present" $Global:UpsConfigManagerGetSectionByNameCalled | Should be $true } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } - It "updates an user profile property in the set method" { + It "Should update an user profile property in the set method" { $Global:UpsConfigManagerCommitCalled = $false $Global:UpsConfigManagerSetDisplayOrderBySectionNameCalled = $false Set-TargetResource @testParams @@ -199,9 +191,9 @@ Describe "SPUserProfileSection - SharePoint Build $((Get-Item $SharePointCmdletM } } - Context "When section exists and ensure equals Absent" { - mock Get-SPDSCUserProfileSubTypeManager -MockWith { - $result = @{}| Add-Member ScriptMethod GetProfileSubtype { + Context -Name "When section exists and ensure equals Absent" { + Mock -CommandName Get-SPDSCUserProfileSubTypeManager -MockWith { + $result = @{}| Add-Member -MemberType ScriptMethod GetProfileSubtype { $Global:SPUPGetProfileSubtypeCalled = $true return @{ Properties = $userProfileSubTypePropertiesProperty @@ -212,7 +204,7 @@ Describe "SPUserProfileSection - SharePoint Build $((Get-Item $SharePointCmdletM } $testParams.Ensure = "Absent" - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { $Global:SPUPGetSectionByNameCalled = $true Test-TargetResource @testParams | Should Be $false @@ -228,9 +220,9 @@ Describe "SPUserProfileSection - SharePoint Build $((Get-Item $SharePointCmdletM } - Context "When section exists and display name and display order are different" { - mock Get-SPDSCUserProfileSubTypeManager -MockWith { - $result = @{}| Add-Member ScriptMethod GetProfileSubtype { + Context -Name "When section exists and display name and display order are different" { + Mock -CommandName Get-SPDSCUserProfileSubTypeManager -MockWith { + $result = @{}| Add-Member -MemberType ScriptMethod GetProfileSubtype { $Global:SPUPGetProfileSubtypeCalled = $true return @{ Properties = $userProfileSubTypePropertiesProperty @@ -242,18 +234,18 @@ Describe "SPUserProfileSection - SharePoint Build $((Get-Item $SharePointCmdletM $testParams.DisplayOrder = 5401 $testParams.DisplayName = "ProfileInformationUpdate" - It "returns valid value from the Get method" { + It "Should return valid value from the Get method" { $Global:SPUPGetSectionByNameCalled = $true $currentValues = Get-TargetResource @testParams $currentValues.Ensure | Should Be "Present" Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.UserProfileService } } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { $Global:SPUPGetSectionByNameCalled = $true Test-TargetResource @testParams | Should Be $false } - It "updates an user profile property in the set method" { + It "Should update an user profile property in the set method" { $Global:SPUPSubTypeCreateCalled = $false $Global:UpsConfigManagerSetDisplayOrderBySectionNameCalled = $false $Global:SPUPGetSectionByNameCalled=$true @@ -263,6 +255,8 @@ Describe "SPUserProfileSection - SharePoint Build $((Get-Item $SharePointCmdletM $Global:UpsConfigManagerSetDisplayOrderBySectionNameCalled | Should be $true } } - } + } } +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope + diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileServiceApp.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileServiceApp.Tests.ps1 index 8a92f11e9..d18145b4b 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileServiceApp.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileServiceApp.Tests.ps1 @@ -1,307 +1,481 @@ [CmdletBinding()] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPUserProfileServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPUserProfileServiceApp" -Describe "SPUserProfileServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "User Profile Service App" - ApplicationPool = "SharePoint Service Applications" - FarmAccount = New-Object System.Management.Automation.PSCredential ("domain\username", (ConvertTo-SecureString "password" -AsPlainText -Force)) - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Get-SPFarm { return @{ - DefaultServiceAccount = @{ Name = $testParams.FarmAccount.Username } - }} - Mock New-SPProfileServiceApplication { return (@{ - NetBIOSDomainNamesEnabled = $false}) +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + # Initialize tests + $getTypeFullName = "Microsoft.Office.Server.Administration.UserProfileApplication" + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential ` + -ArgumentList @("DOMAIN\username", $mockPassword) - } - Mock New-SPProfileServiceApplicationProxy { } - Mock Add-SPDSCUserToLocalAdmin { } - Mock Test-SPDSCUserIsLocalAdmin { return $false } - Mock Remove-SPDSCUserToLocalAdmin { } - Mock New-PSSession { return $null } -ModuleName "SharePointDsc.Util" - Mock Remove-SPServiceApplication { } + # Mocks for all contexts + Mock -CommandName Get-SPFarm -MockWith { + return @{ + DefaultServiceAccount = @{ + Name = $mockCredential.Username + } + } + } + Mock -CommandName New-SPProfileServiceApplication -MockWith { + return (@{ + NetBIOSDomainNamesEnabled = $false} + ) + } + Mock -CommandName New-SPProfileServiceApplicationProxy -MockWith { } + Mock -CommandName Add-SPDSCUserToLocalAdmin -MockWith { } + Mock -CommandName Test-SPDSCUserIsLocalAdmin -MockWith { return $false } + Mock -CommandName Remove-SPDSCUserToLocalAdmin -MockWith { } + Mock -CommandName Remove-SPServiceApplication -MockWith { } - Context "When no service applications exist in the current farm" { + # Test contexts + Context -Name "When no service applications exist in the current farm" -Fixture { + $testParams = @{ + Name = "User Profile Service App" + ApplicationPool = "SharePoint Service Applications" + FarmAccount = $mockCredential + Ensure = "Present" + } - Mock Get-SPServiceApplication { return $null } + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPProfileServiceApplication } - - $testParams.Add("InstallAccount", (New-Object System.Management.Automation.PSCredential ("domain\username", (ConvertTo-SecureString "password" -AsPlainText -Force)))) - It "creates a new service application in the set method when InstallAccount is used" { - Set-TargetResource @testParams - Assert-MockCalled New-SPProfileServiceApplication - } - $testParams.Remove("InstallAccount") } - Context "When service applications exist in the current farm but not the specific user profile service app" { + Context -Name "When service applications exist in the current farm but not the specific user profile service app" -Fixture { + $testParams = @{ + Name = "User Profile Service App" + ApplicationPool = "SharePoint Service Applications" + FarmAccount = $mockCredential + Ensure = "Present" + } - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Some other service app type" - }) } + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = "Microsoft.Office.UnKnownWebServiceApplication" + } + } -PassThru -Force + return $spServiceApp + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } } - Context "When service applications exist in the current farm and NetBios isn't enabled but it needs to be" { - $testParamsEnableNetBIOS = @{ - Name = "User Profile Service App" - ApplicationPool = "SharePoint Service Applications" - EnableNetBIOS=$true - FarmAccount = New-Object System.Management.Automation.PSCredential ("domain\username", (ConvertTo-SecureString "password" -AsPlainText -Force)) - Ensure = "Present" - } - Mock Get-SPServiceApplication { + Context -Name "When service applications exist in the current farm and NetBios isn't enabled but it needs to be" -Fixture { + $testParams = @{ + Name = "User Profile Service App" + ApplicationPool = "SharePoint Service Applications" + EnableNetBIOS = $true + FarmAccount = $mockCredential + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { return @( - New-Object Object | - Add-Member NoteProperty TypeName "User Profile Service Application" -PassThru | - Add-Member NoteProperty DisplayName $testParamsEnableNetBIOS.Name -PassThru | - Add-Member NoteProperty "NetBIOSDomainNamesEnabled" $false -PassThru | - Add-Member ScriptMethod Update {$Global:SPUPSAUpdateCalled = $true} -PassThru | - Add-Member NoteProperty ApplicationPool @{ Name = $testParamsEnableNetBIOS.ApplicationPool } -PassThru | - Add-Member ScriptMethod GetType { - New-Object Object | - Add-Member ScriptMethod GetProperties { - param($x) - return @( - (New-Object Object | - Add-Member NoteProperty Name "SocialDatabase" -PassThru | - Add-Member ScriptMethod GetValue { - param($x) - return @{ - Name = "SP_SocialDB" - Server = @{ Name = "SQL.domain.local" } - } - } -PassThru - ), - (New-Object Object | - Add-Member NoteProperty Name "ProfileDatabase" -PassThru | - Add-Member ScriptMethod GetValue { - return @{ - Name = "SP_ProfileDB" - Server = @{ Name = "SQL.domain.local" } - } - } -PassThru - ), - (New-Object Object | - Add-Member NoteProperty Name "SynchronizationDatabase" -PassThru | - Add-Member ScriptMethod GetValue { - return @{ - Name = "SP_ProfileSyncDB" - Server = @{ Name = "SQL.domain.local" } - } - } -PassThru - ) - ) - } -PassThru - } -PassThru -Force + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name TypeName ` + -Value "User Profile Service Application" ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name DisplayName ` + -Value $testParams.Name ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name "NetBIOSDomainNamesEnabled" ` + -Value $false ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value { + $Global:SPDscUPSAUpdateCalled = $true + } -PassThru | + Add-Member -MemberType NoteProperty ` + -Name ApplicationPool ` + -Value @{ + Name = $testParams.ApplicationPool + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name FullName ` + -Value $getTypeFullName ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetProperties ` + -Value { + param($x) + return @( + (New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "SocialDatabase" ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetValue ` + -Value { + param($x) + return @{ + Name = "SP_SocialDB" + Server = @{ + Name = "SQL.domain.local" + } + } + } -PassThru + ), + (New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "ProfileDatabase" ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetValue ` + -Value { + return @{ + Name = "SP_ProfileDB" + Server = @{ + Name = "SQL.domain.local" + } + } + } -PassThru + ), + (New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "SynchronizationDatabase" ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetValue ` + -Value { + return @{ + Name = "SP_ProfileSyncDB" + Server = @{ + Name = "SQL.domain.local" + } + } + } -PassThru + ) + ) + } -PassThru + } -PassThru -Force ) } - - It "returns false from the Get method" { - (Get-TargetResource @testParamsEnableNetBIOS).EnableNetBIOS | Should Be $false + It "Should return false from the Get method" { + (Get-TargetResource @testParams).EnableNetBIOS | Should Be $false } - It "calls Update method on Service Application before finishing set method" { - $Global:SPUPSAUpdateCalled= $false - - Set-TargetResource @testParamsEnableNetBIOS - $Global:SPUPSAUpdateCalled | Should Be $true + It "Should call Update method on Service Application before finishing set method" { + $Global:SPDscUPSAUpdateCalled = $false + Set-TargetResource @testParams + $Global:SPDscUPSAUpdateCalled | Should Be $true } - It "returns false when the Test method is called" { - Test-TargetResource @testParamsEnableNetBIOS | Should Be $false + It "Should return false when the Test method is called" { + Test-TargetResource @testParams | Should Be $false } - It "returns true when the Test method is called" { - $testParamsEnableNetBIOS.EnableNetBIOS = $false - Test-TargetResource @testParamsEnableNetBIOS | Should Be $true + It "Should return true when the Test method is called" { + $testParams.EnableNetBIOS = $false + Test-TargetResource @testParams | Should Be $true } } - Context "When a service application exists and is configured correctly" { - Mock Get-SPServiceApplication { + Context -Name "When a service application exists and is configured correctly" -Fixture { + $testParams = @{ + Name = "User Profile Service App" + ApplicationPool = "SharePoint Service Applications" + FarmAccount = $mockCredential + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { return @( - New-Object Object | - Add-Member NoteProperty TypeName "User Profile Service Application" -PassThru | - Add-Member NoteProperty DisplayName $testParams.Name -PassThru | - Add-Member NoteProperty "NetBIOSDomainNamesEnabled" $false -PassThru | - Add-Member NoteProperty ApplicationPool @{ Name = $testParams.ApplicationPool } -PassThru | - Add-Member ScriptMethod GetType { - New-Object Object | - Add-Member ScriptMethod GetProperties { - param($x) - return @( - (New-Object Object | - Add-Member NoteProperty Name "SocialDatabase" -PassThru | - Add-Member ScriptMethod GetValue { - param($x) - return @{ - Name = "SP_SocialDB" - Server = @{ Name = "SQL.domain.local" } - } - } -PassThru - ), - (New-Object Object | - Add-Member NoteProperty Name "ProfileDatabase" -PassThru | - Add-Member ScriptMethod GetValue { - return @{ - Name = "SP_ProfileDB" - Server = @{ Name = "SQL.domain.local" } - } - } -PassThru - ), - (New-Object Object | - Add-Member NoteProperty Name "SynchronizationDatabase" -PassThru | - Add-Member ScriptMethod GetValue { - return @{ - Name = "SP_ProfileSyncDB" - Server = @{ Name = "SQL.domain.local" } - } - } -PassThru - ) - ) - } -PassThru - } -PassThru -Force + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name TypeName ` + -Value "User Profile Service Application" ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name DisplayName ` + -Value $testParams.Name ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name "NetBIOSDomainNamesEnabled" ` + -Value $false ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value { + $Global:SPDscUPSAUpdateCalled = $true + } -PassThru | + Add-Member -MemberType NoteProperty ` + -Name ApplicationPool ` + -Value @{ + Name = $testParams.ApplicationPool + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name FullName ` + -Value $getTypeFullName ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetProperties ` + -Value { + param($x) + return @( + (New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "SocialDatabase" ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetValue ` + -Value { + param($x) + return @{ + Name = "SP_SocialDB" + Server = @{ + Name = "SQL.domain.local" + } + } + } -PassThru + ), + (New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "ProfileDatabase" ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetValue ` + -Value { + return @{ + Name = "SP_ProfileDB" + Server = @{ + Name = "SQL.domain.local" + } + } + } -PassThru + ), + (New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "SynchronizationDatabase" ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetValue ` + -Value { + return @{ + Name = "SP_ProfileSyncDB" + Server = @{ + Name = "SQL.domain.local" + } + } + } -PassThru + ) + ) + } -PassThru + } -PassThru -Force ) } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } - Mock Get-SPFarm { return @{ + Mock -CommandName Get-SPFarm -MockWith { return @{ DefaultServiceAccount = @{ Name = "WRONG\account" } }} - It "returns present from the get method where the farm account doesn't match" { + It "Should return present from the get method where the farm account doesn't match" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } } - $testParams = @{ - Name = "Test App" - ApplicationPool = "-" - Ensure = "Absent" - } - - Context "When the service app exists but it shouldn't" { - Mock Get-SPServiceApplication { + Context -Name "When the service app exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { return @( - New-Object Object | - Add-Member NoteProperty TypeName "User Profile Service Application" -PassThru | - Add-Member NoteProperty DisplayName $testParams.Name -PassThru | - Add-Member NoteProperty "NetBIOSDomainNamesEnabled" -value $false -PassThru | - Add-Member NoteProperty ApplicationPool @{ Name = $testParams.ApplicationPool } -PassThru | - Add-Member ScriptMethod GetType { - New-Object Object | - Add-Member ScriptMethod GetProperties { - param($x) - return @( - (New-Object Object | - Add-Member NoteProperty Name "SocialDatabase" -PassThru | - Add-Member ScriptMethod GetValue { - param($x) - return @{ - Name = "SP_SocialDB" - Server = @{ Name = "SQL.domain.local" } - } - } -PassThru - ), - (New-Object Object | - Add-Member NoteProperty Name "ProfileDatabase" -PassThru | - Add-Member ScriptMethod GetValue { - return @{ - Name = "SP_ProfileDB" - Server = @{ Name = "SQL.domain.local" } - } - } -PassThru - ), - (New-Object Object | - Add-Member NoteProperty Name "SynchronizationDatabase" -PassThru | - Add-Member ScriptMethod GetValue { - return @{ - Name = "SP_ProfileSyncDB" - Server = @{ Name = "SQL.domain.local" } - } - } -PassThru - ) - ) - } -PassThru - } -PassThru -Force + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name TypeName ` + -Value "User Profile Service Application" ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name DisplayName ` + -Value $testParams.Name ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name "NetBIOSDomainNamesEnabled" ` + -Value $false ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value { + $Global:SPDscUPSAUpdateCalled = $true + } -PassThru | + Add-Member -MemberType NoteProperty ` + -Name ApplicationPool ` + -Value @{ + Name = $testParams.ApplicationPool + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name FullName ` + -Value $getTypeFullName ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetProperties ` + -Value { + param($x) + return @( + (New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "SocialDatabase" ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetValue ` + -Value { + param($x) + return @{ + Name = "SP_SocialDB" + Server = @{ + Name = "SQL.domain.local" + } + } + } -PassThru + ), + (New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "ProfileDatabase" ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetValue ` + -Value { + return @{ + Name = "SP_ProfileDB" + Server = @{ + Name = "SQL.domain.local" + } + } + } -PassThru + ), + (New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "SynchronizationDatabase" ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetValue ` + -Value { + return @{ + Name = "SP_ProfileSyncDB" + Server = @{ + Name = "SQL.domain.local" + } + } + } -PassThru + ) + ) + } -PassThru + } -PassThru -Force ) } - It "returns present from the Get method" { + It "Should return present from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the service application in the set method" { + It "Should remove the service application in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplication } } - Context "When the service app doesn't exist and shouldn't" { - Mock Get-SPServiceApplication { return $null } + Context -Name "When the service app doesn't exist and shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - } -} \ No newline at end of file + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileServiceAppPermissions.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileServiceAppPermissions.Tests.ps1 index c54a7d8ba..82cf95415 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileServiceAppPermissions.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileServiceAppPermissions.Tests.ps1 @@ -1,62 +1,69 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPUserProfileServiceAppPermissions" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPUserProfileServiceAppPermissions- SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - ProxyName = "User Profile Service App Proxy" - CreatePersonalSite = @("DEMO\User2", "DEMO\User1") - FollowAndEditProfile = @("Everyone") - UseTagsAndNotes = @("None") - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock New-SPClaimsPrincipal { +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPUserProfileServiceAppPermissions" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Initialize tests + + # Mocks for all contexts + Mock -CommandName New-SPClaimsPrincipal -MockWith { return @{ Value = $Identity -replace "i:0#.w\|" } } -ParameterFilter { $IdentityType -eq "EncodedClaim" } - Mock New-SPClaimsPrincipal { - $Global:SPDSCClaimsPrincipalUser = $Identity + Mock -CommandName New-SPClaimsPrincipal -MockWith { + $Global:SPDscClaimsPrincipalUser = $Identity return ( - New-Object Object | Add-Member ScriptMethod ToEncodedString { - return "i:0#.w|$($Global:SPDSCClaimsPrincipalUser)" + New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod ToEncodedString { + return "i:0#.w|$($Global:SPDscClaimsPrincipalUser)" } -PassThru ) } -ParameterFilter { $IdentityType -eq "WindowsSamAccountName" } - Mock Grant-SPObjectSecurity { } - Mock Revoke-SPObjectSecurity { } - Mock Set-SPProfileServiceApplicationSecurity { } + Mock Grant-SPObjectSecurity -MockWith { } + Mock Revoke-SPObjectSecurity -MockWith { } + Mock -CommandName Set-SPProfileServiceApplicationSecurity -MockWith { } - Mock Start-Sleep { } - Mock Test-SPDSCIsADUser { return $true } - Mock Write-Warning { } + Mock -CommandName Start-Sleep -MockWith { } + Mock -CommandName Test-SPDSCIsADUser -MockWith { return $true } + Mock -CommandName Write-Warning -MockWith { } - Mock Get-SPServiceApplicationProxy { - return @() + Mock -CommandName Get-SPServiceApplicationProxy -MockWith { + return @( + @{ + DisplayName = $testParams.ProxyName + } + ) } - - Context "The proxy does not exist" { + + # Test contexts + Context -Name "The proxy does not exist" -Fixture { + $testParams = @{ + ProxyName = "User Profile Service App Proxy" + CreatePersonalSite = @("DEMO\User2", "DEMO\User1") + FollowAndEditProfile = @("Everyone") + UseTagsAndNotes = @("None") + } + + Mock -CommandName Get-SPServiceApplicationProxy -MockWith { + return @() + } It "Should return null values from the get method" { $results = Get-TargetResource @testParams @@ -74,16 +81,15 @@ Describe "SPUserProfileServiceAppPermissions- SharePoint Build $((Get-Item $Shar } } - Mock Get-SPServiceApplicationProxy { - return @( - @{ - DisplayName = $testParams.ProxyName - } - ) - } + Context -Name "Users who should have access do not have access" -Fixture { + $testParams = @{ + ProxyName = "User Profile Service App Proxy" + CreatePersonalSite = @("DEMO\User2", "DEMO\User1") + FollowAndEditProfile = @("Everyone") + UseTagsAndNotes = @("None") + } - Context "Users who should have access do not have access" { - Mock Get-SPProfileServiceApplicationSecurity { + Mock -CommandName Get-SPProfileServiceApplicationSecurity -MockWith { return @{ AccessRules = @() } @@ -103,8 +109,15 @@ Describe "SPUserProfileServiceAppPermissions- SharePoint Build $((Get-Item $Shar } } - Context "Users who should have access have incorrect permissions" { - Mock Get-SPProfileServiceApplicationSecurity { + Context -Name "Users who should have access have incorrect permissions" -Fixture { + $testParams = @{ + ProxyName = "User Profile Service App Proxy" + CreatePersonalSite = @("DEMO\User2", "DEMO\User1") + FollowAndEditProfile = @("Everyone") + UseTagsAndNotes = @("None") + } + + Mock -CommandName Get-SPProfileServiceApplicationSecurity -MockWith { return @{ AccessRules = @( @{ @@ -137,8 +150,15 @@ Describe "SPUserProfileServiceAppPermissions- SharePoint Build $((Get-Item $Shar } } - Context "Users who should have permissions have the correct permissions" { - Mock Get-SPProfileServiceApplicationSecurity { + Context -Name "Users who should have permissions have the correct permissions" -Fixture { + $testParams = @{ + ProxyName = "User Profile Service App Proxy" + CreatePersonalSite = @("DEMO\User2", "DEMO\User1") + FollowAndEditProfile = @("Everyone") + UseTagsAndNotes = @("None") + } + + Mock -CommandName Get-SPProfileServiceApplicationSecurity -MockWith { return @{ AccessRules = @( @{ @@ -166,8 +186,15 @@ Describe "SPUserProfileServiceAppPermissions- SharePoint Build $((Get-Item $Shar } } - Context "Users who should not have access have permissions assigned" { - Mock Get-SPProfileServiceApplicationSecurity { + Context -Name "Users who should not have access have permissions assigned" -Fixture { + $testParams = @{ + ProxyName = "User Profile Service App Proxy" + CreatePersonalSite = @("DEMO\User2", "DEMO\User1") + FollowAndEditProfile = @("Everyone") + UseTagsAndNotes = @("None") + } + + Mock -CommandName Get-SPProfileServiceApplicationSecurity -MockWith { return @{ AccessRules = @( @{ @@ -204,8 +231,15 @@ Describe "SPUserProfileServiceAppPermissions- SharePoint Build $((Get-Item $Shar } } - Context "The old non-claims 'Authenticated Users' entry exists in the permissions" { - Mock Get-SPProfileServiceApplicationSecurity { + Context -Name "The old non-claims 'Authenticated Users' entry exists in the permissions" -Fixture { + $testParams = @{ + ProxyName = "User Profile Service App Proxy" + CreatePersonalSite = @("DEMO\User2", "DEMO\User1") + FollowAndEditProfile = @("Everyone") + UseTagsAndNotes = @("None") + } + + Mock -CommandName Get-SPProfileServiceApplicationSecurity -MockWith { return @{ AccessRules = @( @{ @@ -241,5 +275,7 @@ Describe "SPUserProfileServiceAppPermissions- SharePoint Build $((Get-Item $Shar Assert-MockCalled Set-SPProfileServiceApplicationSecurity } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileSyncConnection.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileSyncConnection.Tests.ps1 index 62c65e139..ebc0e5b09 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileSyncConnection.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileSyncConnection.Tests.ps1 @@ -1,207 +1,262 @@ [CmdletBinding()] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPUserProfileSyncConnection" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPUserProfileSyncConnection" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Initialize tests + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential ` + -ArgumentList @("DOMAIN\username", $mockPassword) -Describe "SPUserProfileSyncConnection - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - UserProfileService = "User Profile Service Application" - Forest = "contoso.com" - Name = "Contoso" - ConnectionCredentials = New-Object System.Management.Automation.PSCredential ("domain\username", (ConvertTo-SecureString "password" -AsPlainText -Force)) - Server = "server.contoso.com" - UseSSL = $false - IncludedOUs = @("OU=SharePoint Users,DC=Contoso,DC=com") - ConnectionType = "ActiveDirectory" - } - try { [Microsoft.Office.Server.UserProfiles] } catch { - Add-Type @" + Add-Type -TypeDefinition @" namespace Microsoft.Office.Server.UserProfiles { public enum ConnectionType { ActiveDirectory, BusinessDataCatalog }; public enum ProfileType { User}; } "@ -ErrorAction SilentlyContinue } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Get-SPDSCServiceContext {return @{}} - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + # Mocks for all contexts + Mock -CommandName Get-SPDSCServiceContext -MockWith { + return @{} } + Mock -CommandName Start-Sleep -MockWith { } - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Start-Sleep { } - Mock New-PSSession { return $null } -ModuleName "SharePointDsc.Util" - Mock Get-SPWebApplication { - return @{ - Url="http://ca" - IsAdministrationWebApplication=$true - } + Mock -CommandName Get-SPWebapplication -MockWith { + return @{ + Url = "http://ca" + IsAdministrationWebApplication = $true + } } $connection = @{ DisplayName = "Contoso" Server = "contoso.com" - NamingContexts= New-Object System.Collections.ArrayList + NamingContexts = New-Object -TypeName System.Collections.ArrayList AccountDomain = "Contoso" AccountUsername = "TestAccount" - Type= "ActiveDirectory" + Type = "ActiveDirectory" } - $connection = $connection | Add-Member ScriptMethod RefreshSchema { - $Global:SPUPSSyncConnectionRefreshSchemaCalled = $true - } -PassThru | Add-Member ScriptMethod Update { - $Global:SPUPSSyncConnectionUpdateCalled = $true - } -PassThru | Add-Member ScriptMethod SetCredentials { - param($userAccount,$securePassword ) - $Global:SPUPSSyncConnectionSetCredentialsCalled = $true - } -PassThru | Add-Member ScriptMethod Delete { - $Global:SPUPSSyncConnectionDeleteCalled = $true - } -PassThru + $connection = $connection | Add-Member -MemberType ScriptMethod ` + -Name RefreshSchema ` + -Value { + $Global:SPDscUPSSyncConnectionRefreshSchemaCalled = $true + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Update ` + -Value { + $Global:SPDscUPSSyncConnectionUpdateCalled = $true + } -PassThru | ` + Add-Member -MemberType ScriptMethod ` + -Name SetCredentials ` + -Value { + param($userAccount,$securePassword) + $Global:SPDscUPSSyncConnectionSetCredentialsCalled = $true + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name Delete ` + -Value { + $Global:SPDscUPSSyncConnectionDeleteCalled = $true + } -PassThru $namingContext =@{ - ContainersIncluded = New-Object System.Collections.ArrayList - ContainersExcluded = New-Object System.Collections.ArrayList - DisplayName="Contoso" - PreferredDomainControllers=$null; + ContainersIncluded = New-Object -TypeName System.Collections.ArrayList + ContainersExcluded = New-Object -TypeName System.Collections.ArrayList + DisplayName = "Contoso" + PreferredDomainControllers = $null } $namingContext.ContainersIncluded.Add("OU=com, OU=Contoso, OU=Included") $namingContext.ContainersExcluded.Add("OU=com, OU=Contoso, OU=Excluded") $connection.NamingContexts.Add($namingContext); - $ConnnectionManager = New-Object System.Collections.ArrayList | Add-Member ScriptMethod AddActiveDirectoryConnection{ ` - param([Microsoft.Office.Server.UserProfiles.ConnectionType] $connectionType, ` - $name, ` - $forest, ` - $useSSL, ` - $userName, ` - $securePassword, ` - $namingContext, ` - $p1, $p2 ` + $ConnnectionManager = New-Object -TypeName System.Collections.ArrayList | + Add-Member -MemberType ScriptMethod ` + -Name AddActiveDirectoryConnection ` + -Value { + param( + [Microsoft.Office.Server.UserProfiles.ConnectionType] + $connectionType, + $name, + $forest, + $useSSL, + $userName, + $securePassword, + $namingContext, + $p1, + $p2 ) - - $Global:SPUPSAddActiveDirectoryConnectionCalled =$true - } -PassThru + $Global:SPDscUPSAddActiveDirectoryConnectionCalled = $true + } -PassThru - Mock New-Object -MockWith { + Mock -CommandName New-Object -MockWith { return (@{ - ConnectionManager = $ConnnectionManager - } | Add-Member ScriptMethod IsSynchronizationRunning { - $Global:UpsSyncIsSynchronizationRunning=$true; - return $false; - } -PassThru ) - } -ParameterFilter { $TypeName -eq "Microsoft.Office.Server.UserProfiles.UserProfileConfigManager" } + ConnectionManager = $ConnnectionManager + } | Add-Member -MemberType ScriptMethod ` + -Name IsSynchronizationRunning ` + -Value { + $Global:SPDscUpsSyncIsSynchronizationRunning = $true + return $false + } -PassThru + )} -ParameterFilter { + $TypeName -eq "Microsoft.Office.Server.UserProfiles.UserProfileConfigManager" + } $userProfileServiceValidConnection = @{ Name = "User Profile Service Application" TypeName = "User Profile Service Application" ApplicationPool = "SharePoint Service Applications" - FarmAccount = New-Object System.Management.Automation.PSCredential ("domain\username", (ConvertTo-SecureString "password" -AsPlainText -Force)) + FarmAccount = $mockCredential ServiceApplicationProxyGroup = "Proxy Group" - ConnectionManager= New-Object System.Collections.ArrayList + ConnectionManager= New-Object -TypeName System.Collections.ArrayList } - $userProfileServiceValidConnection.ConnectionManager.Add($connection); + $userProfileServiceValidConnection.ConnectionManager.Add($connection) - Mock Get-SPDSCADSIObject { + Mock -CommandName Get-SPDSCADSIObject -MockWith { return @{ distinguishedName = "DC=Contoso,DC=Com" objectGUID = (New-Guid).ToString() } } - Mock New-SPDSCDirectoryServiceNamingContextList -MockWith { - return New-Object System.Collections.Generic.List[[Object]] + Mock -CommandName New-SPDSCDirectoryServiceNamingContextList -MockWith { + return New-Object -TypeName System.Collections.Generic.List[[Object]] } - Mock Import-Module {} -ParameterFilter { $_.Name -eq $ModuleName } - - Context "When connection doesn't exist" { - $userProfileServiceNoConnections = @{ + Mock -CommandName Import-Module {} -ParameterFilter { + $_.Name -eq $ModuleName + } + + # Test contexts + Context -Name "When connection doesn't exist" -Fixture { + $testParams = @{ + UserProfileService = "User Profile Service Application" + Forest = "contoso.com" + Name = "Contoso" + ConnectionCredentials = $mockCredential + Server = "server.contoso.com" + UseSSL = $false + IncludedOUs = @("OU=SharePoint Users,DC=Contoso,DC=com") + ConnectionType = "ActiveDirectory" + } + + $userProfileServiceNoConnections = @{ Name = "User Profile Service Application" ApplicationPool = "SharePoint Service Applications" - FarmAccount = New-Object System.Management.Automation.PSCredential ("domain\username", (ConvertTo-SecureString "password" -AsPlainText -Force)) + FarmAccount = $mockCredential ServiceApplicationProxyGroup = "Proxy Group" ConnnectionManager = @() } - Mock Get-SPServiceApplication { return $userProfileServiceNoConnections } - Mock New-SPDSCDirectoryServiceNamingContext -MockWith {return @{} } + Mock -CommandName Get-SPServiceApplication -MockWith { return $userProfileServiceNoConnections } + Mock -CommandName New-SPDSCDirectoryServiceNamingContext -MockWith {return @{} } - It "returns null from the Get method" { + It "Should return null from the Get method" { Get-TargetResource @testParams | Should BeNullOrEmpty Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.UserProfileService } } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { - $Global:SPUPSAddActiveDirectoryConnectionCalled =$false + It "Should create a new service application in the set method" { + $Global:SPDscUPSAddActiveDirectoryConnectionCalled =$false Set-TargetResource @testParams - $Global:SPUPSAddActiveDirectoryConnectionCalled | Should be $true + $Global:SPDscUPSAddActiveDirectoryConnectionCalled | Should be $true } } - Context "When connection exists and account is different" { - Mock Get-SPServiceApplication { return $userProfileServiceValidConnection } + Context -Name "When connection exists and account is different" -Fixture { + $testParams = @{ + UserProfileService = "User Profile Service Application" + Forest = "contoso.com" + Name = "Contoso" + ConnectionCredentials = $mockCredential + Server = "server.contoso.com" + UseSSL = $false + IncludedOUs = @("OU=SharePoint Users,DC=Contoso,DC=com") + ConnectionType = "ActiveDirectory" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return $userProfileServiceValidConnection + } $ConnnectionManager.Add($connection) - It "returns service instance from the Get method" { + It "Should return service instance from the Get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.UserProfileService } } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } It "execute update credentials" { - $Global:SPUPSSyncConnectionSetCredentialsCalled=$false - $Global:SPUPSSyncConnectionRefreshSchemaCalled=$false + $Global:SPDscUPSSyncConnectionSetCredentialsCalled=$false + $Global:SPDscUPSSyncConnectionRefreshSchemaCalled=$false Set-TargetResource @testParams - $Global:SPUPSSyncConnectionSetCredentialsCalled | Should be $true - $Global:SPUPSSyncConnectionRefreshSchemaCalled | Should be $true + $Global:SPDscUPSSyncConnectionSetCredentialsCalled | Should be $true + $Global:SPDscUPSSyncConnectionRefreshSchemaCalled | Should be $true } } - Context "When connection exists and forest is different" { + Context -Name "When connection exists and forest is different" -Fixture { + $testParams = @{ + UserProfileService = "User Profile Service Application" + Forest = "contoso.com" + Name = "Contoso" + ConnectionCredentials = $mockCredential + Server = "server.contoso.com" + UseSSL = $false + IncludedOUs = @("OU=SharePoint Users,DC=Contoso,DC=com") + ConnectionType = "ActiveDirectory" + } + $litWareconnection = @{ DisplayName = "Contoso" Server = "litware.net" - NamingContexts= New-Object System.Collections.ArrayList + NamingContexts= New-Object -TypeName System.Collections.ArrayList AccountDomain = "Contoso" AccountUsername = "TestAccount" Type= "ActiveDirectory" } $litWareconnection.NamingContexts.Add($namingContext); - $litWareconnection = $litWareconnection | Add-Member ScriptMethod Delete { - $Global:SPUPSSyncConnectionDeleteCalled = $true - } -PassThru + $litWareconnection = $litWareconnection | Add-Member -MemberType ScriptMethod ` + -Name Delete ` + -Value { + $Global:SPDscUPSSyncConnectionDeleteCalled = $true + } -PassThru $userProfileServiceValidConnection = @{ Name = "User Profile Service Application" TypeName = "User Profile Service Application" ApplicationPool = "SharePoint Service Applications" - FarmAccount = New-Object System.Management.Automation.PSCredential ("domain\username", (ConvertTo-SecureString "password" -AsPlainText -Force)) + FarmAccount = $mockCredential ServiceApplicationProxyGroup = "Proxy Group" - ConnectionManager= New-Object System.Collections.ArrayList + ConnectionManager= New-Object -TypeName System.Collections.ArrayList } $userProfileServiceValidConnection.ConnectionManager.Add($litWareconnection); - Mock Get-SPServiceApplication { return $userProfileServiceValidConnection } - $litwareConnnectionManager = New-Object System.Collections.ArrayList | Add-Member ScriptMethod AddActiveDirectoryConnection{ ` + Mock -CommandName Get-SPServiceApplication -MockWith { + return $userProfileServiceValidConnection + } + $litwareConnnectionManager = New-Object -TypeName System.Collections.ArrayList | Add-Member -MemberType ScriptMethod AddActiveDirectoryConnection{ ` param([Microsoft.Office.Server.UserProfiles.ConnectionType] $connectionType, ` $name, ` $forest, ` @@ -212,40 +267,40 @@ Describe "SPUserProfileSyncConnection - SharePoint Build $((Get-Item $SharePoint $p1, $p2 ` ) - $Global:SPUPSAddActiveDirectoryConnectionCalled =$true + $Global:SPDscUPSAddActiveDirectoryConnectionCalled =$true } -PassThru $litwareConnnectionManager.Add($litWareconnection) - Mock New-Object -MockWith { - return (@{} | Add-Member ScriptMethod IsSynchronizationRunning { - $Global:UpsSyncIsSynchronizationRunning=$true; + Mock -CommandName New-Object -MockWith { + return (@{} | Add-Member -MemberType ScriptMethod IsSynchronizationRunning { + $Global:SPDscUpsSyncIsSynchronizationRunning=$true; return $false; } -PassThru | Add-Member ConnectionManager $litwareConnnectionManager -PassThru ) } -ParameterFilter { $TypeName -eq "Microsoft.Office.Server.UserProfiles.UserProfileConfigManager" } - Mock New-Object -MockWith {return @{} + Mock -CommandName New-Object -MockWith {return @{} } -ParameterFilter { $TypeName -eq "Microsoft.Office.Server.UserProfiles.DirectoryServiceNamingContext"} - It "returns service instance from the Get method" { + It "Should return service instance from the Get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.UserProfileService } } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "throws exception as force isn't specified" { - $Global:SPUPSSyncConnectionDeleteCalled=$false + It "Should throw exception as force isn't specified" { + $Global:SPDscUPSSyncConnectionDeleteCalled=$false {Set-TargetResource @testParams} | should throw - $Global:SPUPSSyncConnectionDeleteCalled | Should be $false + $Global:SPDscUPSSyncConnectionDeleteCalled | Should be $false } $forceTestParams = @{ UserProfileService = "User Profile Service Application" Forest = "contoso.com" Name = "Contoso" - ConnectionCredentials = New-Object System.Management.Automation.PSCredential ("domain\username", (ConvertTo-SecureString "password" -AsPlainText -Force)) + ConnectionCredentials = $mockCredential Server = "server.contoso.com" UseSSL = $false Force = $true @@ -254,57 +309,87 @@ Describe "SPUserProfileSyncConnection - SharePoint Build $((Get-Item $SharePoint } It "delete and create as force is specified" { - $Global:SPUPSSyncConnectionDeleteCalled=$false - $Global:SPUPSAddActiveDirectoryConnectionCalled =$false + $Global:SPDscUPSSyncConnectionDeleteCalled=$false + $Global:SPDscUPSAddActiveDirectoryConnectionCalled =$false Set-TargetResource @forceTestParams - $Global:SPUPSSyncConnectionDeleteCalled | Should be $true - $Global:SPUPSAddActiveDirectoryConnectionCalled | Should be $true + $Global:SPDscUPSSyncConnectionDeleteCalled | Should be $true + $Global:SPDscUPSAddActiveDirectoryConnectionCalled | Should be $true } } - Context "When synchronization is running" { - Mock Get-SPServiceApplication { + Context -Name "When synchronization is running" -Fixture { + $testParams = @{ + UserProfileService = "User Profile Service Application" + Forest = "contoso.com" + Name = "Contoso" + ConnectionCredentials = $mockCredential + Server = "server.contoso.com" + UseSSL = $false + IncludedOUs = @("OU=SharePoint Users,DC=Contoso,DC=com") + ConnectionType = "ActiveDirectory" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { return @( - New-Object Object|Add-Member NoteProperty ServiceApplicationProxyGroup "Proxy Group" -PassThru + New-Object -TypeName "Object" | Add-Member -MemberType NoteProperty ` + -Name ServiceApplicationProxyGroup ` + -Value "Proxy Group" ` + -PassThru ) } - Mock New-Object -MockWith { - return (@{} | Add-Member ScriptMethod IsSynchronizationRunning { - $Global:UpsSyncIsSynchronizationRunning=$true; - return $true; - } -PassThru) - } -ParameterFilter { $TypeName -eq "Microsoft.Office.Server.UserProfiles.UserProfileConfigManager" } + Mock -CommandName New-Object -MockWith { + return (@{} | Add-Member -MemberType ScriptMethod ` + -Name IsSynchronizationRunning ` + -Value { + $Global:SPDscUpsSyncIsSynchronizationRunning=$true; + return $true + } -PassThru) + } -ParameterFilter { + $TypeName -eq "Microsoft.Office.Server.UserProfiles.UserProfileConfigManager" + } It "attempts to execute method but synchronization is running" { - $Global:UpsSyncIsSynchronizationRunning=$false - $Global:SPUPSAddActiveDirectoryConnectionCalled =$false - {Set-TargetResource @testParams }| Should throw + $Global:SPDscUpsSyncIsSynchronizationRunning=$false + $Global:SPDscUPSAddActiveDirectoryConnectionCalled =$false + { Set-TargetResource @testParams }| Should throw Assert-MockCalled Get-SPServiceApplication Assert-MockCalled New-Object -ParameterFilter { $TypeName -eq "Microsoft.Office.Server.UserProfiles.UserProfileConfigManager" } - $Global:UpsSyncIsSynchronizationRunning| Should be $true; - $Global:SPUPSAddActiveDirectoryConnectionCalled | Should be $false; + $Global:SPDscUpsSyncIsSynchronizationRunning| Should be $true; + $Global:SPDscUPSAddActiveDirectoryConnectionCalled | Should be $false; } - } - Context "When connection exists and Excluded and Included OUs are different. force parameter provided" { + Context -Name "When connection exists and Excluded and Included OUs are different. force parameter provided" -Fixture { + $testParams = @{ + UserProfileService = "User Profile Service Application" + Forest = "contoso.com" + Name = "Contoso" + ConnectionCredentials = $mockCredential + Server = "server.contoso.com" + UseSSL = $false + IncludedOUs = @("OU=SharePoint Users,DC=Contoso,DC=com") + ConnectionType = "ActiveDirectory" + } + $userProfileServiceValidConnection = @{ Name = "User Profile Service Application" TypeName = "User Profile Service Application" ApplicationPool = "SharePoint Service Applications" - FarmAccount = New-Object System.Management.Automation.PSCredential ("domain\username", (ConvertTo-SecureString "password" -AsPlainText -Force)) + FarmAccount = $mockCredential ServiceApplicationProxyGroup = "Proxy Group" - ConnectionManager= New-Object System.Collections.ArrayList + ConnectionManager= New-Object -TypeName System.Collections.ArrayList } $userProfileServiceValidConnection.ConnectionManager.Add($connection); - Mock Get-SPServiceApplication { return $userProfileServiceValidConnection } + Mock -CommandName Get-SPServiceApplication -MockWith { + return $userProfileServiceValidConnection + } $difOUsTestParams = @{ UserProfileService = "User Profile Service Application" Forest = "contoso.com" Name = "Contoso" - ConnectionCredentials = New-Object System.Management.Automation.PSCredential ("domain\username", (ConvertTo-SecureString "password" -AsPlainText -Force)) + ConnectionCredentials = $mockCredential Server = "server.contoso.com" UseSSL = $false Force = $false @@ -313,25 +398,27 @@ Describe "SPUserProfileSyncConnection - SharePoint Build $((Get-Item $SharePoint ConnectionType = "ActiveDirectory" } - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @difOUsTestParams | Should Not BeNullOrEmpty Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.UserProfileService } } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @difOUsTestParams | Should Be $false } - It "updates OU lists" { - $Global:SPUPSSyncConnectionUpdateCalled= $false - $Global:SPUPSSyncConnectionSetCredentialsCalled = $false - $Global:SPUPSSyncConnectionRefreshSchemaCalled =$false + It "Should update OU lists" { + $Global:SPDscUPSSyncConnectionUpdateCalled= $false + $Global:SPDscUPSSyncConnectionSetCredentialsCalled = $false + $Global:SPDscUPSSyncConnectionRefreshSchemaCalled =$false Set-TargetResource @difOUsTestParams - $Global:SPUPSSyncConnectionUpdateCalled | Should be $true - $Global:SPUPSSyncConnectionSetCredentialsCalled | Should be $true - $Global:SPUPSSyncConnectionRefreshSchemaCalled | Should be $true + $Global:SPDscUPSSyncConnectionUpdateCalled | Should be $true + $Global:SPDscUPSSyncConnectionSetCredentialsCalled | Should be $true + $Global:SPDscUPSSyncConnectionRefreshSchemaCalled | Should be $true } } - } + } } +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope + diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileSyncService.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileSyncService.Tests.ps1 index a588a38c8..da23e4efc 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileSyncService.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPUserProfileSyncService.Tests.ps1 @@ -1,253 +1,368 @@ [CmdletBinding()] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPUserProfileSyncService" -$ModuleName = "MSFT_SPUserProfileSyncService" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPUserProfileSyncService - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - UserProfileServiceAppName = "User Profile Service Service App" - FarmAccount = New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)) - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - $versionBeingTested = (Get-Item $Global:CurrentSharePointStubModule).Directory.BaseName - $majorBuildNumber = $versionBeingTested.Substring(0, $versionBeingTested.IndexOf(".")) - Mock Get-SPDSCInstalledProductVersion { return @{ FileMajorPart = $majorBuildNumber } } + # Initialize tests + $getTypeFullName = "Microsoft.Office.Server.Administration.UserProfileApplication" + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential ` + -ArgumentList @("DOMAIN\username", $mockPassword) - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Get-SPFarm { return @{ - DefaultServiceAccount = @{ Name = $testParams.FarmAccount.Username } + # Mocks for all contexts + Mock -CommandName Get-SPFarm -MockWith { return @{ + DefaultServiceAccount = @{ + Name = $mockCredential.UserName + } }} - Mock Start-SPServiceInstance { } - Mock Stop-SPServiceInstance { } - Mock Restart-Service { } - Mock Add-SPDSCUserToLocalAdmin { } - Mock Test-SPDSCUserIsLocalAdmin { return $false } - Mock Remove-SPDSCUserToLocalAdmin { } - Mock New-PSSession { return $null } -ModuleName "SharePointDsc.Util" - Mock Start-Sleep { } - Mock Get-SPServiceApplication { + Mock -CommandName Start-SPServiceInstance -MockWith { } + Mock -CommandName Stop-SPServiceInstance -MockWith { } + Mock -CommandName Restart-Service -MockWith { } + Mock -CommandName Add-SPDSCUserToLocalAdmin -MockWith { } + Mock -CommandName Test-SPDSCUserIsLocalAdmin -MockWith { + return $false + } + Mock -CommandName Remove-SPDSCUserToLocalAdmin -MockWith { } + Mock -CommandName Start-Sleep -MockWith { } + Mock -CommandName Get-SPServiceApplication -MockWith { return @( - New-Object Object | - Add-Member NoteProperty TypeName "User Profile Service Application" -PassThru | - Add-Member NoteProperty DisplayName $testParams.Name -PassThru | - Add-Member NoteProperty ApplicationPool @{ Name = $testParams.ApplicationPool } -PassThru | - Add-Member ScriptMethod GetType { - New-Object Object | - Add-Member ScriptMethod GetProperties { - param($x) - return @( - (New-Object Object | - Add-Member NoteProperty Name "SocialDatabase" -PassThru | - Add-Member ScriptMethod GetValue { - param($x) - return @{ - Name = "SP_SocialDB" - Server = @{ Name = "SQL.domain.local" } - } - } -PassThru - ), - (New-Object Object | - Add-Member NoteProperty Name "ProfileDatabase" -PassThru | - Add-Member ScriptMethod GetValue { - return @{ - Name = "SP_ProfileDB" - Server = @{ Name = "SQL.domain.local" } - } - } -PassThru - ), - (New-Object Object | - Add-Member NoteProperty Name "SynchronizationDatabase" -PassThru | - Add-Member ScriptMethod GetValue { - return @{ - Name = "SP_ProfileSyncDB" - Server = @{ Name = "SQL.domain.local" } - } - } -PassThru - ) - ) - } -PassThru - } -PassThru -Force + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name TypeName ` + -Value "User Profile Service Application" ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name DisplayName ` + -Value "User Profile Service Service App" ` + -PassThru | + Add-Member -MemberType NoteProperty ` + -Name ApplicationPool ` + -Value @{ + Name = "Service Pool" + } -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name FullName ` + -Value $getTypeFullName ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetProperties ` + -Value { + param($x) + return @( + (New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "SocialDatabase" ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetValue ` + -Value { + param($x) + return @{ + Name = "SP_SocialDB" + Server = @{ + Name = "SQL.domain.local" + } + } + } -PassThru + ), + (New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "ProfileDatabase" ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetValue ` + -Value { + return @{ + Name = "SP_ProfileDB" + Server = @{ + Name = "SQL.domain.local" + } + } + } -PassThru + ), + (New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name Name ` + -Value "SynchronizationDatabase" ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetValue ` + -Value { + return @{ + Name = "SP_ProfileSyncDB" + Server = @{ + Name = "SQL.domain.local" + } + } + } -PassThru + ) + ) + } -PassThru + } -PassThru -Force ) } - switch ($majorBuildNumber) { + # Test contexts + switch ($Global:SPDscHelper.CurrentStubBuildNumber.Major) + { 15 { - Context "User profile sync service is not found locally" { - Mock Get-SPServiceInstance { return $null } + Context -Name "User profile sync service is not found locally" -Fixture { + $testParams = @{ + UserProfileServiceAppName = "User Profile Service Service App" + FarmAccount = $mockCredential + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceInstance -MockWith { + return $null + } - It "returns absent from the get method" { - $Global:SPDSCUPACheck = $false + It "Should return absent from the get method" { + $Global:SPDscUPACheck = $false (Get-TargetResource @testParams).Ensure | Should Be "Absent" } } - Context "User profile sync service is not running and should be" { - Mock Get-SPServiceInstance { if ($Global:SPDSCUPACheck -eq $false) { + Context -Name "User profile sync service is not running and should be" -Fixture { + $testParams = @{ + UserProfileServiceAppName = "User Profile Service Service App" + FarmAccount = $mockCredential + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceInstance -MockWith { + $spSvcInstance = [pscustomobject]@{ + ID = [Guid]::Parse("21946987-5163-418f-b781-2beb83aa191f") + } + $spSvcInstance = $spSvcInstance | Add-Member ScriptMethod GetType { + return @{ Name = "UserProfileServiceInstance" } + } -PassThru -Force + if ($Global:SPDSCUPACheck -eq $false) + { $Global:SPDSCUPACheck = $true - return @( @{ - Status = "Disabled" - ID = [Guid]::Parse("21946987-5163-418f-b781-2beb83aa191f") - UserProfileApplicationGuid = [Guid]::Empty - TypeName = "User Profile Synchronization Service" - }) - } else { - return @( @{ - Status = "Online" - ID = [Guid]::Parse("21946987-5163-418f-b781-2beb83aa191f") - UserProfileApplicationGuid = [Guid]::NewGuid() - TypeName = "User Profile Synchronization Service" - }) + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty Status "Disabled" -PassThru + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty UserProfileApplicationGuid [Guid]::Empty -PassThru + } + else + { + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty Status "Online" -PassThru + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty UserProfileApplicationGuid ([Guid]::NewGuid()) -PassThru } + return $spSvcInstance } - Mock Get-SPServiceApplication { return @( - New-Object Object | - Add-Member NoteProperty ID ([Guid]::Parse("21946987-5163-418f-b781-2beb83aa191f")) -PassThru | - Add-Member NoteProperty TypeName "User Profile Service Application" -PassThru | - Add-Member ScriptMethod SetSynchronizationMachine { - param($computerName, $syncServiceID, $FarmUserName, $FarmPassword) - } -PassThru - )} - - It "returns absent from the get method" { - $Global:SPDSCUPACheck = $false + + Mock -CommandName Get-SPServiceApplication -MockWith { + return @( + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name ID ` + -Value ([Guid]::Parse("21946987-5163-418f-b781-2beb83aa191f")) ` + -PassThru | + Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + New-Object -TypeName "Object" | + Add-Member -MemberType NoteProperty ` + -Name FullName ` + -Value $getTypeFullName ` + -PassThru + } ` + -PassThru -Force | + Add-Member -MemberType ScriptMethod ` + -Name SetSynchronizationMachine ` + -Value { + param( + $computerName, + $syncServiceID, + $FarmUserName, + $FarmPassword + ) + } -PassThru + ) + } + + It "Should return absent from the get method" { + $Global:SPDscUPACheck = $false (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { - $Global:SPDSCUPACheck = $false + It "Should return false from the test method" { + $Global:SPDscUPACheck = $false Test-TargetResource @testParams | Should Be $false } - It "calls the start service cmdlet from the set method" { - $Global:SPDSCUPACheck = $false + It "Should call the start service cmdlet from the set method" { + $Global:SPDscUPACheck = $false Set-TargetResource @testParams Assert-MockCalled Start-SPServiceInstance } - Mock Get-SPFarm { return @{ - DefaultServiceAccount = @{ Name = "WRONG\account" } - }} + Mock -CommandName Get-SPFarm -MockWith { + return @{ + DefaultServiceAccount = @{ Name = "WRONG\account" } + } + } - It "returns values from the get method where the farm account doesn't match" { + It "Should return values from the get method where the farm account doesn't match" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - $Global:SPDSCUPACheck = $false - Mock Get-SPServiceApplication { return $null } - It "throws in the set method if the user profile service app can't be found" { + $Global:SPDscUPACheck = $false + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } + + It "Should throw in the set method if the user profile service app can't be found" { { Set-TargetResource @testParams } | Should Throw } } - Context "User profile sync service is running and should be" { - Mock Get-SPServiceInstance { return @( @{ - Status = "Online" - ID = [Guid]::Parse("21946987-5163-418f-b781-2beb83aa191f") - UserProfileApplicationGuid = [Guid]::NewGuid() - TypeName = "User Profile Synchronization Service" - }) - } + Context -Name "User profile sync service is running and should be" -Fixture { + $testParams = @{ + UserProfileServiceAppName = "User Profile Service Service App" + FarmAccount = $mockCredential + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceInstance -MockWith { + $spSvcInstance = [pscustomobject]@{ + ID = [Guid]::Parse("21946987-5163-418f-b781-2beb83aa191f") + } + $spSvcInstance = $spSvcInstance | Add-Member ScriptMethod GetType { + return @{ Name = "UserProfileServiceInstance" } + } -PassThru -Force + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty Status "Online" -PassThru + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty UserProfileApplicationGuid ([Guid]::NewGuid()) -PassThru + return $spSvcInstance + } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } + + Context -Name "User profile sync service is running and shouldn't be" -Fixture { + $testParams = @{ + UserProfileServiceAppName = "User Profile Service Service App" + FarmAccount = $mockCredential + Ensure = "Absent" + } - $testParams.Ensure = "Absent" - - Context "User profile sync service is running and shouldn't be" { - Mock Get-SPServiceInstance { if ($Global:SPDSCUPACheck -eq $false) { + Mock -CommandName Get-SPServiceInstance -MockWith { + $spSvcInstance = [pscustomobject]@{ + ID = [Guid]::Parse("21946987-5163-418f-b781-2beb83aa191f") + } + $spSvcInstance = $spSvcInstance | Add-Member ScriptMethod GetType { + return @{ Name = "UserProfileServiceInstance" } + } -PassThru -Force + if ($Global:SPDSCUPACheck -eq $false) + { $Global:SPDSCUPACheck = $true - return @( @{ - Status = "Online" - ID = [Guid]::Parse("21946987-5163-418f-b781-2beb83aa191f") - UserProfileApplicationGuid = [Guid]::NewGuid() - TypeName = "User Profile Synchronization Service" - }) - } else { - return @( @{ - Status = "Disabled" - ID = [Guid]::Empty - UserProfileApplicationGuid = [Guid]::Empty - TypeName = "User Profile Synchronization Service" - }) + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty Status "Online" -PassThru + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty UserProfileApplicationGuid ([Guid]::NewGuid()) -PassThru + } + else + { + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty Status "Disabled" -PassThru + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty UserProfileApplicationGuid [Guid]::Empty -PassThru } - } + return $spSvcInstance + } - It "returns present from the get method" { - $Global:SPDSCUPACheck = $false + It "Should return present from the get method" { + $Global:SPDscUPACheck = $false (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns false from the test method" { - $Global:SPDSCUPACheck = $false + It "Should return false from the test method" { + $Global:SPDscUPACheck = $false Test-TargetResource @testParams | Should Be $false } - It "calls the stop service cmdlet from the set method" { - $Global:SPDSCUPACheck = $false + It "Should call the stop service cmdlet from the set method" { + $Global:SPDscUPACheck = $false Set-TargetResource @testParams Assert-MockCalled Stop-SPServiceInstance } } - Context "User profile sync service is not running and shouldn't be" { - Mock Get-SPServiceInstance { return @( @{ - Status = "Disabled" + Context -Name "User profile sync service is not running and shouldn't be" -Fixture { + $testParams = @{ + UserProfileServiceAppName = "User Profile Service Service App" + FarmAccount = $mockCredential + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceInstance -MockWith { + $spSvcInstance = [pscustomobject]@{ ID = [Guid]::Parse("21946987-5163-418f-b781-2beb83aa191f") - UserProfileApplicationGuid = [Guid]::Empty - TypeName = "User Profile Synchronization Service" - }) - } + } + $spSvcInstance = $spSvcInstance | Add-Member ScriptMethod GetType { + return @{ Name = "UserProfileServiceInstance" } + } -PassThru -Force + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty Status "Disabled" -PassThru + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty UserProfileApplicationGuid [Guid]::Empty -PassThru + return $spSvcInstance + } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } + Context -Name "User profile sync service is not running and shouldn't be because the database is read only" -Fixture { + $testParams = @{ + UserProfileServiceAppName = "User Profile Service Service App" + FarmAccount = $mockCredential + Ensure = "Present" + RunOnlyWhenWriteable = $true + } - - $testParams.Ensure = "Present" - $testParams.Add("RunOnlyWhenWriteable", $true) - Context "User profile sync service is not running and shouldn't be because the database is read only" { - Mock Get-SPServiceInstance { return @( @{ - Status = "Disabled" + Mock -CommandName Get-SPServiceInstance -MockWith { + $spSvcInstance = [pscustomobject]@{ ID = [Guid]::Parse("21946987-5163-418f-b781-2beb83aa191f") - UserProfileApplicationGuid = [Guid]::Empty - TypeName = "User Profile Synchronization Service" - }) + } + $spSvcInstance = $spSvcInstance | Add-Member ScriptMethod GetType { + return @{ Name = "UserProfileServiceInstance" } + } -PassThru -Force + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty Status "Disabled" -PassThru + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty UserProfileApplicationGuid ([Guid]::NewGuid()) -PassThru + return $spSvcInstance } - Mock Get-SPDatabase { + Mock -CommandName Get-SPDatabase -MockWith { return @( @{ Name = "SP_ProfileDB" @@ -256,25 +371,36 @@ Describe "SPUserProfileSyncService - SharePoint Build $((Get-Item $SharePointCmd ) } - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "User profile sync service is running and shouldn't be because the database is read only" { - Mock Get-SPServiceInstance { return @( @{ - Status = "Online" - ID = [Guid]::Parse("21946987-5163-418f-b781-2beb83aa191f") - UserProfileApplicationGuid = [Guid]::NewGuid() - TypeName = "User Profile Synchronization Service" - }) - } + Context -Name "User profile sync service is running and shouldn't be because the database is read only" -Fixture { + $testParams = @{ + UserProfileServiceAppName = "User Profile Service Service App" + FarmAccount = $mockCredential + Ensure = "Present" + RunOnlyWhenWriteable = $true + } + + Mock -CommandName Get-SPServiceInstance -MockWith { + $spSvcInstance = [pscustomobject]@{ + ID = [Guid]::Parse("21946987-5163-418f-b781-2beb83aa191f") + } + $spSvcInstance = $spSvcInstance | Add-Member ScriptMethod GetType { + return @{ Name = "UserProfileServiceInstance" } + } -PassThru -Force + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty Status "Online" -PassThru + $spSvcInstance = $spSvcInstance | Add-Member NoteProperty UserProfileApplicationGuid ([Guid]::NewGuid()) -PassThru + return $spSvcInstance + } - Mock Get-SPDatabase { + Mock -CommandName Get-SPDatabase -MockWith { return @( @{ Name = "SP_ProfileDB" @@ -283,16 +409,16 @@ Describe "SPUserProfileSyncService - SharePoint Build $((Get-Item $SharePointCmd ) } - It "returns absent from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "calls the stop service cmdlet from the set method" { - $Global:SPDSCUPACheck = $false + It "Should call the stop service cmdlet from the set method" { + $Global:SPDscUPACheck = $false Set-TargetResource @testParams Assert-MockCalled Stop-SPServiceInstance @@ -300,26 +426,27 @@ Describe "SPUserProfileSyncService - SharePoint Build $((Get-Item $SharePointCmd } } 16 { - Context "All methods throw exceptions as user profile sync doesn't exist in 2016" { - It "throws on the get method" { + Context -Name "All methods throw exceptions as user profile sync doesn't exist in 2016" -Fixture { + $testParams = @{ + UserProfileServiceAppName = "User Profile Service Service App" + FarmAccount = $mockCredential + } + + It "Should throw on the get method" { { Get-TargetResource @testParams } | Should Throw } - It "throws on the test method" { + It "Should throw on the test method" { { Test-TargetResource @testParams } | Should Throw } - It "throws on the set method" { + It "Should throw on the set method" { { Set-TargetResource @testParams } | Should Throw } } } } - - + } +} - - - - } -} \ No newline at end of file +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPVisioServiceApp.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPVisioServiceApp.Tests.ps1 index cc00a94cf..c024711ae 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPVisioServiceApp.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPVisioServiceApp.Tests.ps1 @@ -1,145 +1,198 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPVisioServiceApp" -$ModuleName = "MSFT_SPVisioServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPVisioServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Test Visio App" - ApplicationPool = "Test App Pool" - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") + # Initialize Tests + $getTypeFullName = "Microsoft.Office.Visio.Server.Administration.VisioGraphicsServiceApplication" - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue + # Mocks for all contexts + Mock -CommandName New-SPVisioServiceApplication -MockWith { } + Mock -CommandName Remove-SPServiceApplication -MockWith { } + Mock -CommandName New-SPVisioServiceApplicationProxy -MockWith { } - Mock Remove-SPServiceApplication { } - - Context "When no service applications exist in the current farm" { - - Mock Get-SPServiceApplication { return $null } - Mock New-SPVisioServiceApplication { } + # Test contexts + Context -Name "When no service applications exist in the current farm" -Fixture { + $testParams = @{ + Name = "Test Visio App" + ApplicationPool = "Test App Pool" + Ensure = "Present" + } - It "returns absent from the Get method" { + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } + + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams - Assert-MockCalled New-SPVisioServiceApplication } } - Context "When service applications exist in the current farm but the specific Visio Graphics app does not" { - - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Some other service app type" - }) } - - It "returns absent from the Get method" { + Context -Name "When service applications exist in the current farm but the specific Visio Graphics app does not" -Fixture { + $testParams = @{ + Name = "Test Visio App" + ApplicationPool = "Test App Pool" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod ` + -Name GetType ` + -Value { + return @{ + FullName = "Microsoft.Office.UnKnownWebServiceApplication" + } + } -PassThru -Force + return $spServiceApp + } + + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - } - Context "When a service application exists and is configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When a service application exists and is configured correctly" -Fixture { + $testParams = @{ + Name = "Test Visio App" + ApplicationPool = "Test App Pool" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Visio Graphics Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } - Context "When a service application exists and is not configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ + Context -Name "When a service application exists and is not configured correctly" -Fixture { + $testParams = @{ + Name = "Test Visio App" + ApplicationPool = "Test App Pool" + Ensure = "Present" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Visio Graphics Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = "Wrong App Pool Name" } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } + Mock -CommandName Get-SPServiceApplicationPool { + return @{ + Name = $testParams.ApplicationPool + } } - Mock Get-SPServiceApplicationPool { return @{ Name = $testParams.ApplicationPool } } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "calls the update service app cmdlet from the set method" { + It "Should call the update service app cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Get-SPServiceApplicationPool } } + + Context -Name "When the service app exists but it shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } - $testParams = @{ - Name = "Test App" - ApplicationPool = "-" - Ensure = "Absent" - } - - Context "When the service app exists but it shouldn't" { - Mock Get-SPServiceApplication { - return @(@{ + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [PSCustomObject]@{ TypeName = "Visio Graphics Service Application" DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns present from the Get method" { + It "Should return present from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the service application in the set method" { + It "Should remove the service application in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplication } } - Context "When the service app doesn't exist and shouldn't" { - Mock Get-SPServiceApplication { return $null } + Context -Name "When the service app doesn't exist and shouldn't" -Fixture { + $testParams = @{ + Name = "Test App" + ApplicationPool = "-" + Ensure = "Absent" + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + return $null + } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPWeb.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPWeb.Tests.ps1 index de6f6033f..6caf00c0d 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPWeb.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPWeb.Tests.ps1 @@ -1,56 +1,60 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4693.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPWeb" -$ModuleName = "MSFT_SPWeb" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPWeb - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - - InModuleScope $ModuleName { - - $testParams = @{ - Url = "http://site.sharepoint.com/sites/web" - Name = "Team Site" - Description = "desc" - } - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - + # Initialize tests $fakeWebApp = [PSCustomObject]@{ } - $fakeWebApp | Add-Member -MemberType ScriptMethod -Name GrantAccessToProcessIdentity -PassThru -Value { } - - Mock New-Object { [PSCustomObject]@{ WebApplication = $fakeWebApp} } -Verifiable -ParameterFilter { $TypeName -eq "Microsoft.SharePoint.SPSite" } + $fakeWebApp | Add-Member -MemberType ScriptMethod ` + -Name GrantAccessToProcessIdentity ` + -PassThru ` + -Value { } + + # Mocks for all contexts + Mock -CommandName New-Object -MockWith { + [PSCustomObject]@{ + WebApplication = $fakeWebApp + } + } -ParameterFilter { + $TypeName -eq "Microsoft.SharePoint.SPSite" + } + Mock -CommandName Remove-SPWeb -MockWith { } - Mock Remove-SPWeb { } -Verifiable - - Context "The SPWeb doesn't exist yet and should" { + # Test contexts + Context -Name "The SPWeb doesn't exist yet and should" -Fixture { + $testParams = @{ + Url = "http://site.sharepoint.com/sites/web" + Name = "Team Site" + Description = "desc" + } - Mock Get-SPWeb { return $null } + Mock -CommandName Get-SPWeb -MockWith { return $null } - It "returns 'Absent' from the get method" { + It "Should return 'Absent' from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "creates a new SPWeb from the set method" { - Mock New-SPWeb { } -Verifiable + It "Should create a new SPWeb from the set method" { + Mock -CommandName New-SPWeb { } -Verifiable Set-TargetResource @testParams @@ -59,9 +63,14 @@ Describe "SPWeb - SharePoint Build $((Get-Item $SharePointCmdletModule).Director } } - Context "The SPWeb exists and has the correct name and description" { + Context -Name "The SPWeb exists and has the correct name and description" -Fixture { + $testParams = @{ + Url = "http://site.sharepoint.com/sites/web" + Name = "Team Site" + Description = "desc" + } - Mock Get-SPWeb { + Mock -CommandName Get-SPWeb -MockWith { return @{ Url = $testParams.Url Title = $testParams.Name @@ -74,7 +83,7 @@ Describe "SPWeb - SharePoint Build $((Get-Item $SharePointCmdletModule).Director } } - It "returns the SPWeb data from the get method" { + It "Should return the SPWeb data from the get method" { $result = Get-TargetResource @testParams @@ -85,44 +94,48 @@ Describe "SPWeb - SharePoint Build $((Get-Item $SharePointCmdletModule).Director } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - context "The SPWeb exists and should not" { - - $testParams.Ensure = "Absent" + Context -Name "The SPWeb exists and should not" -Fixture { + $testParams = @{ + Url = "http://site.sharepoint.com/sites/web" + Name = "Team Site" + Description = "desc" + Ensure = "Absent" + } - Mock Get-SPWeb { + Mock -CommandName Get-SPWeb -MockWith { return @{ Url = $testParams.Url } } - It "returns 'Present' from the get method" { - + It "Should return 'Present' from the get method" { (Get-TargetResource @testParams).Ensure | Should be "Present" - } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "removes the SPWeb in the set method" { - + It "Should remove the SPWeb in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPWeb } } - context "The SPWeb exists but has the wrong editable values" { - - $testParams.Ensure = "Present" - $testParams.UseParentTopNav = $false - $testParams.UniquePermissions = $true + Context -Name "The SPWeb exists but has the wrong editable values" -Fixture { + $testParams = @{ + Url = "http://site.sharepoint.com/sites/web" + Name = "Team Site" + Description = "desc" + UseParentTopNav = $false + UniquePermissions = $true + } $web = [pscustomobject] @{ Url = $testParams.Url @@ -132,11 +145,13 @@ Describe "SPWeb - SharePoint Build $((Get-Item $SharePointCmdletModule).Director HasUniquePerm = $false } - $web | Add-Member -Name Update -MemberType ScriptMethod -Value { } + $web | Add-Member -Name Update ` + -MemberType ScriptMethod ` + -Value { } - Mock Get-SPWeb { $web } + Mock -CommandName Get-SPWeb -MockWith { $web } - It "returns the SPWeb data from the get method" { + It "Should return the SPWeb data from the get method" { $result = Get-TargetResource @testParams @@ -146,11 +161,11 @@ Describe "SPWeb - SharePoint Build $((Get-Item $SharePointCmdletModule).Director } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "updates the values in the set method" { + It "Should update the values in the set method" { Set-TargetResource @testParams @@ -162,5 +177,7 @@ Describe "SPWeb - SharePoint Build $((Get-Item $SharePointCmdletModule).Director Assert-MockCalled New-Object } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppBlockedFileTypes.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppBlockedFileTypes.Tests.ps1 index 701fa711a..f65271c13 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppBlockedFileTypes.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppBlockedFileTypes.Tests.ps1 @@ -1,39 +1,43 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPWebAppBlockedFileTypes" -$ModuleName = "MSFT_SPWebAppBlockedFileTypes" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPWebAppBlockedFileTypes - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Url = "http://sites.sharepoint.com" - Blocked = @("exe", "dll", "ps1") - } - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + # Initialize tests + + # Mocks for all contexts + Mock -CommandName New-SPAuthenticationProvider -MockWith { } + Mock -CommandName New-SPWebApplication -MockWith { } + Mock -CommandName Get-SPAuthenticationProvider -MockWith { + return @{ + DisableKerberos = $true + AllowAnonymous = $false + } } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock New-SPAuthenticationProvider { } - Mock New-SPWebApplication { } - Mock Get-SPAuthenticationProvider { return @{ DisableKerberos = $true; AllowAnonymous = $false } } - - Context "The web appliation exists and a specific blocked file type list matches" { - Mock Get-SPWebApplication { + + # Test contexts + Context -Name "The web appliation exists and a specific blocked file type list matches" -Fixture { + $testParams = @{ + Url = "http://sites.sharepoint.com" + Blocked = @("exe", "dll", "ps1") + } + + Mock -CommandName Get-SPWebapplication -MockWith { [Collections.Generic.List[String]]$CurrentBlockedFiles = @("exe", "ps1", "dll") $webApp = @{ DisplayName = $testParams.Name @@ -53,23 +57,28 @@ Describe "SPWebAppBlockedFileTypes - SharePoint Build $((Get-Item $SharePointCmd Url = $testParams.Url BlockedFileExtensions = $CurrentBlockedFiles } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns the current data from the get method" { + It "Should return the current data from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The web appliation exists and a specific blocked file type list does not match" { - Mock Get-SPWebApplication { + Context -Name "The web appliation exists and a specific blocked file type list does not match" -Fixture { + $testParams = @{ + Url = "http://sites.sharepoint.com" + Blocked = @("exe", "dll", "ps1") + } + + Mock -CommandName Get-SPWebapplication -MockWith { [Collections.Generic.List[String]]$CurrentBlockedFiles = @("exe", "pdf", "dll") $webApp = @{ DisplayName = $testParams.Name @@ -89,35 +98,35 @@ Describe "SPWebAppBlockedFileTypes - SharePoint Build $((Get-Item $SharePointCmd Url = $testParams.Url BlockedFileExtensions = $CurrentBlockedFiles } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns the current data from the get method" { + It "Should return the current data from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false - It "updates the workflow settings" { + $Global:SPDscWebApplicationUpdateCalled = $false + It "Should update the workflow settings" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - $testParams = @{ - Url = "http://sites.sharepoint.com" - EnsureBlocked = @("exe") - EnsureAllowed = @("pdf") - } + Context -Name "The web appliation exists and a list of types to include and exclude both match" -Fixture { + $testParams = @{ + Url = "http://sites.sharepoint.com" + EnsureBlocked = @("exe") + EnsureAllowed = @("pdf") + } - Context "The web appliation exists and a list of types to include and exclude both match" { - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { [Collections.Generic.List[String]]$CurrentBlockedFiles = @("exe", "ps1", "dll") $webApp = @{ DisplayName = $testParams.Name @@ -137,23 +146,29 @@ Describe "SPWebAppBlockedFileTypes - SharePoint Build $((Get-Item $SharePointCmd Url = $testParams.Url BlockedFileExtensions = $CurrentBlockedFiles } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns the current data from the get method" { + It "Should return the current data from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The web appliation exists and a list of types to include and exclude both failed" { - Mock Get-SPWebApplication { + Context -Name "The web appliation exists and a list of types to include and exclude both failed" -Fixture { + $testParams = @{ + Url = "http://sites.sharepoint.com" + EnsureBlocked = @("exe") + EnsureAllowed = @("pdf") + } + + Mock -CommandName Get-SPWebapplication -MockWith { [Collections.Generic.List[String]]$CurrentBlockedFiles = @("pdf", "dll") $webApp = @{ DisplayName = $testParams.Name @@ -173,29 +188,36 @@ Describe "SPWebAppBlockedFileTypes - SharePoint Build $((Get-Item $SharePointCmd Url = $testParams.Url BlockedFileExtensions = $CurrentBlockedFiles } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns the current data from the get method" { + It "Should return the current data from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false - It "updates the workflow settings" { + $Global:SPDscWebApplicationUpdateCalled = $false + It "Should update the workflow settings" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "All blocked file type parameters are passed to the methods" { - Mock Get-SPWebApplication { + Context -Name "All blocked file type parameters are passed to the methods" -Fixture { + $testParams = @{ + Url = "http://sites.sharepoint.com" + Blocked = @("exe", "dll", "ps1") + EnsureBlocked = @("exe", "dll") + EnsureAllowed = @("ps1") + } + + Mock -CommandName Get-SPWebapplication -MockWith { [Collections.Generic.List[String]]$CurrentBlockedFiles = @("pdf", "dll") $webApp = @{ DisplayName = $testParams.Name @@ -215,30 +237,27 @@ Describe "SPWebAppBlockedFileTypes - SharePoint Build $((Get-Item $SharePointCmd Url = $testParams.Url BlockedFileExtensions = $CurrentBlockedFiles } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - $testParams = @{ - Url = "http://sites.sharepoint.com" - Blocked = @("exe", "dll", "ps1") - EnsureBlocked = @("exe", "dll") - EnsureAllowed = @("ps1") - } - - It "throws an exception on the test method" { + It "Should throw an exception on the test method" { { Test-TargetResource @testParams } | Should throw } - It "throws an exception on the set method" { + It "Should throw an exception on the set method" { { Set-TargetResource @testParams } | Should throw } } - Context "No blocked file type parameters are passed to the methods" { - Mock Get-SPWebApplication { + Context -Name "No blocked file type parameters are passed to the methods" -Fixture { + $testParams = @{ + Url = "http://sites.sharepoint.com" + } + + Mock -CommandName Get-SPWebapplication -MockWith { [Collections.Generic.List[String]]$CurrentBlockedFiles = @("pdf", "dll") $webApp = @{ DisplayName = $testParams.Name @@ -258,23 +277,22 @@ Describe "SPWebAppBlockedFileTypes - SharePoint Build $((Get-Item $SharePointCmd Url = $testParams.Url BlockedFileExtensions = $CurrentBlockedFiles } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - $testParams = @{ - Url = "http://sites.sharepoint.com" - } - - It "throws an exception on the test method" { + + It "Should throw an exception on the test method" { { Test-TargetResource @testParams } | Should throw } - It "throws an exception on the set method" { + It "Should throw an exception on the set method" { { Set-TargetResource @testParams } | Should throw } } - } -} \ No newline at end of file + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppGeneralSettings.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppGeneralSettings.Tests.ps1 index d04b3e393..84a102059 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppGeneralSettings.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppGeneralSettings.Tests.ps1 @@ -1,55 +1,59 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPWebAppGeneralSettings" -$ModuleName = "MSFT_SPWebAppGeneralSettings" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPWebAppGeneralSettings - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Url = "http://sites.sharepoint.com" - TimeZone = 3081 - Alerts = $true - AlertsLimit = 10 - RSS = $true - BlogAPI = $true - BlogAPIAuthenticated = $true - BrowserFileHandling = "Permissive" - SecurityValidation = $true - SecurityValidationExpires = $true - SecurityValidationTimeoutMinutes = 10 - RecycleBinEnabled = $true - RecycleBinCleanupEnabled = $true - RecycleBinRetentionPeriod = 30 - SecondStageRecycleBinQuota = 30 - MaximumUploadSize = 100 - CustomerExperienceProgram = $true - PresenceEnabled = $true - } - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + # Initialize tests + + # Mocks for all contexts + Mock -CommandName New-SPAuthenticationProvider -MockWith { } + Mock -CommandName New-SPWebApplication -MockWith { } + Mock -CommandName Get-SPAuthenticationProvider -MockWith { + return @{ + DisableKerberos = $true + AllowAnonymous = $false + } } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock New-SPAuthenticationProvider { } - Mock New-SPWebApplication { } - Mock Get-SPAuthenticationProvider { return @{ DisableKerberos = $true; AllowAnonymous = $false } } - Context "The web appliation exists and has the correct general settings" { - Mock Get-SPWebApplication { + # Test contexts + Context -Name "The web appliation exists and has the correct general settings" -Fixture { + $testParams = @{ + Url = "http://sites.sharepoint.com" + TimeZone = 3081 + Alerts = $true + AlertsLimit = 10 + RSS = $true + BlogAPI = $true + BlogAPIAuthenticated = $true + BrowserFileHandling = "Permissive" + SecurityValidation = $true + SecurityValidationExpires = $true + SecurityValidationTimeoutMinutes = 10 + RecycleBinEnabled = $true + RecycleBinCleanupEnabled = $true + RecycleBinRetentionPeriod = 30 + SecondStageRecycleBinQuota = 30 + MaximumUploadSize = 100 + CustomerExperienceProgram = $true + PresenceEnabled = $true + } + + Mock -CommandName Get-SPWebapplication -MockWith { $webApp = @{ DisplayName = $testParams.Name ApplicationPool = @{ @@ -86,23 +90,44 @@ Describe "SPWebAppGeneralSettings - SharePoint Build $((Get-Item $SharePointCmdl BrowserCEIPEnabled = $testParams.CustomerExperienceProgram PresenceEnabled = $testParams.PresenceEnabled } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns the current data from the get method" { + It "Should return the current data from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The web appliation exists and uses incorrect general settings" { - Mock Get-SPWebApplication { + Context -Name "The web appliation exists and uses incorrect general settings" -Fixture { + $testParams = @{ + Url = "http://sites.sharepoint.com" + TimeZone = 3081 + Alerts = $true + AlertsLimit = 10 + RSS = $true + BlogAPI = $true + BlogAPIAuthenticated = $true + BrowserFileHandling = "Permissive" + SecurityValidation = $true + SecurityValidationExpires = $true + SecurityValidationTimeoutMinutes = 10 + RecycleBinEnabled = $true + RecycleBinCleanupEnabled = $true + RecycleBinRetentionPeriod = 30 + SecondStageRecycleBinQuota = 30 + MaximumUploadSize = 100 + CustomerExperienceProgram = $true + PresenceEnabled = $true + } + + Mock -CommandName Get-SPWebapplication -MockWith { $webApp = @{ DisplayName = $testParams.Name ApplicationPool = @{ @@ -137,25 +162,27 @@ Describe "SPWebAppGeneralSettings - SharePoint Build $((Get-Item $SharePointCmdl BrowserCEIPEnabled = $false PresenceEnabled = $false } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns the current data from the get method" { + It "Should return the current data from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false - It "updates the general settings" { + $Global:SPDscWebApplicationUpdateCalled = $false + It "Should update the general settings" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppPermissions.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppPermissions.Tests.ps1 index ebb3b12cc..f4260dce0 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppPermissions.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppPermissions.Tests.ps1 @@ -1,608 +1,960 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPWebAppPermissions" -$ModuleName = "MSFT_SPWebAppPermissions" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDSC\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPWebAppPermissions" { - InModuleScope $ModuleName { - $testParams = @{ - WebAppUrl = "http://sharepoint.contoso.com" - AllPermissions = $true - } - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + # Initialize tests try { [Microsoft.SharePoint.SPBasePermissions] } catch { - Add-Type @" + Add-Type -TypeDefinition @" namespace Microsoft.SharePoint { - public enum SPBasePermissions { FullMask, EmptyMask, ManageLists, CancelCheckout, AddListItems, EditListItems, DeleteListItems, ViewListItems, ApproveItems, OpenItems, ViewVersions, DeleteVersions, CreateAlerts, ViewFormPages, ManagePermissions, ViewUsageData, ManageSubwebs, ManageWeb, AddAndCustomizePages, ApplyThemeAndBorder, ApplyStyleSheets, CreateGroups, BrowseDirectories,CreateSSCSite, ViewPages, EnumeratePermissions, BrowseUserInfo, ManageAlerts, UseRemoteAPIs, UseClientIntegration, Open, EditMyUserInfo, ManagePersonalViews, AddDelPrivateWebParts, UpdatePersonalWebParts}; + public enum SPBasePermissions { + FullMask, EmptyMask, ManageLists, CancelCheckout, AddListItems, EditListItems, DeleteListItems, + ViewListItems, ApproveItems, OpenItems, ViewVersions, DeleteVersions, CreateAlerts, + ViewFormPages, ManagePermissions, ViewUsageData, ManageSubwebs, ManageWeb, AddAndCustomizePages, + ApplyThemeAndBorder, ApplyStyleSheets, CreateGroups, BrowseDirectories,CreateSSCSite, ViewPages, + EnumeratePermissions, BrowseUserInfo, ManageAlerts, UseRemoteAPIs, UseClientIntegration, Open, + EditMyUserInfo, ManagePersonalViews, AddDelPrivateWebParts, UpdatePersonalWebParts + }; } "@ } + # Mocks for all contexts - Context "The web application doesn't exist" { - Mock Get-SPWebApplication { return $null } + # Test contexts + Context -Name "The web application doesn't exist" -Fixture { + $testParams = @{ + WebAppUrl = "http://sharepoint.contoso.com" + AllPermissions = $true + } + + Mock -CommandName Get-SPWebapplication -MockWith { return $null } - It "returns exception from the get method" { + It "Should return exception from the get method" { { Get-TargetResource @testParams } | Should throw "The specified web application could not be found." } - It "returns exception from the test method" { + It "Should return exception from the test method" { { Test-TargetResource @testParams } | Should throw "The specified web application could not be found." } - It "returns exception from the set method" { + It "Should return exception from the set method" { { Set-TargetResource @testParams } | Should throw "The specified web application could not be found." } } - Context "AllPermissions specified together with one of the other parameters" { + Context -Name "AllPermissions specified together with one of the other parameters" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" AllPermissions = $true - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - Mock Get-SPWebApplication { return $null } - - It "returns exception from the get method" { - { Get-TargetResource @testParams } | Should throw "Do not specify parameters ListPermissions, SitePermissions or PersonalPermissions when specifying parameter AllPermissions" - } - - It "returns exception from the test method" { - { Test-TargetResource @testParams } | Should throw "Do not specify parameters ListPermissions, SitePermissions or PersonalPermissions when specifying parameter AllPermissions" - } - - It "returns exception from the set method" { - { Set-TargetResource @testParams } | Should throw "Do not specify parameters ListPermissions, SitePermissions or PersonalPermissions when specifying parameter AllPermissions" + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { + { Get-TargetResource @testParams } | Should throw ("Do not specify parameters " + ` + "ListPermissions, SitePermissions or PersonalPermissions when " + ` + "specifying parameter AllPermissions") + } + + It "Should return exception from the test method" { + { Test-TargetResource @testParams } | Should throw ("Do not specify parameters " + ` + "ListPermissions, SitePermissions or PersonalPermissions when " + ` + "specifying parameter AllPermissions") + } + + It "Should return exception from the set method" { + { Set-TargetResource @testParams } | Should throw ("Do not specify parameters " + ` + "ListPermissions, SitePermissions or PersonalPermissions when " + ` + "specifying parameter AllPermissions") } } - Context "Not all three parameters specified" { + Context -Name "Not all three parameters specified" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") } - Mock Get-SPWebApplication { return $null } - It "returns exception from the get method" { - { Get-TargetResource @testParams } | Should throw "One of the parameters ListPermissions, SitePermissions or PersonalPermissions is missing" + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { + { Get-TargetResource @testParams } | Should throw ("One of the parameters " + ` + "ListPermissions, SitePermissions or PersonalPermissions is missing") } - It "returns exception from the test method" { - { Test-TargetResource @testParams } | Should throw "One of the parameters ListPermissions, SitePermissions or PersonalPermissions is missing" + It "Should return exception from the test method" { + { Test-TargetResource @testParams } | Should throw ("One of the parameters " + ` + "ListPermissions, SitePermissions or PersonalPermissions is missing") } - It "returns exception from the set method" { - { Set-TargetResource @testParams } | Should throw "One of the parameters ListPermissions, SitePermissions or PersonalPermissions is missing" + It "Should return exception from the set method" { + { Set-TargetResource @testParams } | Should throw ("One of the parameters " + ` + "ListPermissions, SitePermissions or PersonalPermissions is missing") } } - Context "Approve items without Edit Items" { + Context -Name "Approve items without Edit Items" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - Mock Get-SPWebApplication { return $null } - - It "returns exception from the get method" { + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Delete Items","View Items","Approve Items","Open Items", + "View Versions","Delete Versions","Create Alerts", + "View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { { Get-TargetResource @testParams } | Should throw "Edit Items is required when specifying Approve Items" } - It "returns exception from the test method" { + It "Should return exception from the test method" { { Test-TargetResource @testParams } | Should throw "Edit Items is required when specifying Approve Items" } - It "returns exception from the set method" { + It "Should return exception from the set method" { { Set-TargetResource @testParams } | Should throw "Edit Items is required when specifying Approve Items" } } - Context "View Items missing for various other parameters" { + Context -Name "View Items missing for various other parameters" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - Mock Get-SPWebApplication { return $null } - - It "returns exception from the get method" { - { Get-TargetResource @testParams } | Should throw "View Items is required when specifying Manage Lists, Override List Behaviors, Add Items, Edit Items, Delete Items, Approve Items, Open Items, View Versions, Delete Versions, Create Alerts, Manage Permissions, Manage Web Site, Add and Customize Pages, Manage Alerts, Use Client Integration Features, Manage Personal Views, Add/Remove Personal Web Parts or Update Personal Web Parts" - } - - It "returns exception from the test method" { - { Test-TargetResource @testParams } | Should throw "View Items is required when specifying Manage Lists, Override List Behaviors, Add Items, Edit Items, Delete Items, Approve Items, Open Items, View Versions, Delete Versions, Create Alerts, Manage Permissions, Manage Web Site, Add and Customize Pages, Manage Alerts, Use Client Integration Features, Manage Personal Views, Add/Remove Personal Web Parts or Update Personal Web Parts" - } - - It "returns exception from the set method" { - { Set-TargetResource @testParams } | Should throw "View Items is required when specifying Manage Lists, Override List Behaviors, Add Items, Edit Items, Delete Items, Approve Items, Open Items, View Versions, Delete Versions, Create Alerts, Manage Permissions, Manage Web Site, Add and Customize Pages, Manage Alerts, Use Client Integration Features, Manage Personal Views, Add/Remove Personal Web Parts or Update Personal Web Parts" + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","Approve Items","Open Items", + "View Versions","Delete Versions","Create Alerts", + "View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { + { Get-TargetResource @testParams } | Should throw ("View Items is required when " + ` + "specifying Manage Lists, Override List Behaviors, Add Items, Edit " + ` + "Items, Delete Items, Approve Items, Open Items, View Versions, Delete " + ` + "Versions, Create Alerts, Manage Permissions, Manage Web Site, Add and " + ` + "Customize Pages, Manage Alerts, Use Client Integration Features, " + ` + "Manage Personal Views, Add/Remove Personal Web Parts or Update " + ` + "Personal Web Parts") + } + + It "Should return exception from the test method" { + { Test-TargetResource @testParams } | Should throw ("View Items is required when " + ` + "specifying Manage Lists, Override List Behaviors, Add Items, Edit " + ` + "Items, Delete Items, Approve Items, Open Items, View Versions, Delete " + ` + "Versions, Create Alerts, Manage Permissions, Manage Web Site, Add and " + ` + "Customize Pages, Manage Alerts, Use Client Integration Features, " + ` + "Manage Personal Views, Add/Remove Personal Web Parts or Update " + ` + "Personal Web Parts") + } + + It "Should return exception from the set method" { + { Set-TargetResource @testParams } | Should throw ("View Items is required when " + ` + "specifying Manage Lists, Override List Behaviors, Add Items, Edit " + ` + "Items, Delete Items, Approve Items, Open Items, View Versions, Delete " + ` + "Versions, Create Alerts, Manage Permissions, Manage Web Site, Add and " + ` + "Customize Pages, Manage Alerts, Use Client Integration Features, " + ` + "Manage Personal Views, Add/Remove Personal Web Parts or Update " + ` + "Personal Web Parts") } } - Context "View Versions or Manage Permissions without Open Items" { + Context -Name "View Versions or Manage Permissions without Open Items" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items", + "Approve Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") } - Mock Get-SPWebApplication { return $null } - It "returns exception from the get method" { - { Get-TargetResource @testParams } | Should throw "Open Items is required when specifying View Versions or Manage Permissions" + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { + { Get-TargetResource @testParams } | Should throw ("Open Items is required when " + ` + "specifying View Versions or Manage Permissions") } - It "returns exception from the test method" { - { Test-TargetResource @testParams } | Should throw "Open Items is required when specifying View Versions or Manage Permissions" + It "Should return exception from the test method" { + { Test-TargetResource @testParams } | Should throw ("Open Items is required when " + ` + "specifying View Versions or Manage Permissions") } - It "returns exception from the set method" { - { Set-TargetResource @testParams } | Should throw "Open Items is required when specifying View Versions or Manage Permissions" + It "Should return exception from the set method" { + { Set-TargetResource @testParams } | Should throw ("Open Items is required when " + ` + "specifying View Versions or Manage Permissions") } } - Context "Delete Versions or Manage Permissions without View Versions" { + Context -Name "Delete Versions or Manage Permissions without View Versions" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items", + "Approve Items","Open Items","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") } - Mock Get-SPWebApplication { return $null } - It "returns exception from the get method" { - { Get-TargetResource @testParams } | Should throw "View Versions is required when specifying Delete Versions or Manage Permissions" + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { + { Get-TargetResource @testParams } | Should throw ("View Versions is required " + ` + "when specifying Delete Versions or Manage Permissions") } - It "returns exception from the test method" { - { Test-TargetResource @testParams } | Should throw "View Versions is required when specifying Delete Versions or Manage Permissions" + It "Should return exception from the test method" { + { Test-TargetResource @testParams } | Should throw ("View Versions is required " + ` + "when specifying Delete Versions or Manage Permissions") } - It "returns exception from the set method" { - { Set-TargetResource @testParams } | Should throw "View Versions is required when specifying Delete Versions or Manage Permissions" + It "Should return exception from the set method" { + { Set-TargetResource @testParams } | Should throw ("View Versions is required " + ` + "when specifying Delete Versions or Manage Permissions") } } - Context "Manage Alerts without Create Alerts" { + Context -Name "Manage Alerts without Create Alerts" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - Mock Get-SPWebApplication { return $null } - - It "returns exception from the get method" { + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { { Get-TargetResource @testParams } | Should throw "Create Alerts is required when specifying Manage Alerts" } - It "returns exception from the test method" { + It "Should return exception from the test method" { { Test-TargetResource @testParams } | Should throw "Create Alerts is required when specifying Manage Alerts" } - It "returns exception from the set method" { + It "Should return exception from the set method" { { Set-TargetResource @testParams } | Should throw "Create Alerts is required when specifying Manage Alerts" } } - Context "Manage Web Site without Add and Customize Pages" { + Context -Name "Manage Web Site without Add and Customize Pages" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - Mock Get-SPWebApplication { return $null } - - It "returns exception from the get method" { + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Apply Themes and Borders","Apply Style Sheets", + "Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { { Get-TargetResource @testParams } | Should throw "Add and Customize Pages is required when specifying Manage Web Site" } - It "returns exception from the test method" { + It "Should return exception from the test method" { { Test-TargetResource @testParams } | Should throw "Add and Customize Pages is required when specifying Manage Web Site" } - It "returns exception from the set method" { + It "Should return exception from the set method" { { Set-TargetResource @testParams } | Should throw "Add and Customize Pages is required when specifying Manage Web Site" } } - Context "Manage Permissions, Manage Web Site, Add and Customize Pages or Enumerate Permissions without Browse Directories" { + Context -Name "Manage Permissions, Manage Web Site, Add and Customize Pages or Enumerate Permissions without Browse Directories" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - Mock Get-SPWebApplication { return $null } - - It "returns exception from the get method" { - { Get-TargetResource @testParams } | Should throw "Browse Directories is required when specifying Manage Permissions, Manage Web Site, Add and Customize Pages or Enumerate Permissions" - } - - It "returns exception from the test method" { - { Test-TargetResource @testParams } | Should throw "Browse Directories is required when specifying Manage Permissions, Manage Web Site, Add and Customize Pages or Enumerate Permissions" - } - - It "returns exception from the set method" { - { Set-TargetResource @testParams } | Should throw "Browse Directories is required when specifying Manage Permissions, Manage Web Site, Add and Customize Pages or Enumerate Permissions" + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { + { Get-TargetResource @testParams } | Should throw ("Browse Directories is " + ` + "required when specifying Manage Permissions, Manage Web Site, " + ` + "Add and Customize Pages or Enumerate Permissions") + } + + It "Should return exception from the test method" { + { Test-TargetResource @testParams } | Should throw ("Browse Directories is " + ` + "required when specifying Manage Permissions, Manage Web Site, " + ` + "Add and Customize Pages or Enumerate Permissions") + } + + It "Should return exception from the set method" { + { Set-TargetResource @testParams } | Should throw ("Browse Directories is " + ` + "required when specifying Manage Permissions, Manage Web Site, " + ` + "Add and Customize Pages or Enumerate Permissions") } } - Context "View Pages missing for various other parameters" { + Context -Name "View Pages missing for various other parameters" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - Mock Get-SPWebApplication { return $null } - - It "returns exception from the get method" { - { Get-TargetResource @testParams } | Should throw "View Pages is required when specifying Manage Lists, Override List Behaviors, Add Items, Edit Items, Delete Items, View Items, Approve Items, Open Items, View Versions, Delete Versions, Create Alerts, Manage Permissions, View Web Analytics Data, Create Subsites, Manage Web Site, Add and Customize Pages, Apply Themes and Borders, Apply Style Sheets, Create Groups, Browse Directories, Use Self-Service Site Creation, Enumerate Permissions, Manage Alerts, Manage Personal Views, Add/Remove Personal Web Parts or Update Personal Web Parts" - } - - It "returns exception from the test method" { - { Test-TargetResource @testParams } | Should throw "View Pages is required when specifying Manage Lists, Override List Behaviors, Add Items, Edit Items, Delete Items, View Items, Approve Items, Open Items, View Versions, Delete Versions, Create Alerts, Manage Permissions, View Web Analytics Data, Create Subsites, Manage Web Site, Add and Customize Pages, Apply Themes and Borders, Apply Style Sheets, Create Groups, Browse Directories, Use Self-Service Site Creation, Enumerate Permissions, Manage Alerts, Manage Personal Views, Add/Remove Personal Web Parts or Update Personal Web Parts" - } - - It "returns exception from the set method" { - { Set-TargetResource @testParams } | Should throw "View Pages is required when specifying Manage Lists, Override List Behaviors, Add Items, Edit Items, Delete Items, View Items, Approve Items, Open Items, View Versions, Delete Versions, Create Alerts, Manage Permissions, View Web Analytics Data, Create Subsites, Manage Web Site, Add and Customize Pages, Apply Themes and Borders, Apply Style Sheets, Create Groups, Browse Directories, Use Self-Service Site Creation, Enumerate Permissions, Manage Alerts, Manage Personal Views, Add/Remove Personal Web Parts or Update Personal Web Parts" + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","Enumerate Permissions", + "Browse User Information","Manage Alerts", + "Use Remote Interfaces","Use Client Integration Features", + "Open","Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { + { Get-TargetResource @testParams } | Should throw ("View Pages is required when " + ` + "specifying Manage Lists, Override List Behaviors, Add Items, Edit " + ` + "Items, Delete Items, View Items, Approve Items, Open Items, View " + ` + "Versions, Delete Versions, Create Alerts, Manage Permissions, View " + ` + "Web Analytics Data, Create Subsites, Manage Web Site, Add and " + ` + "Customize Pages, Apply Themes and Borders, Apply Style Sheets, Create " + ` + "Groups, Browse Directories, Use Self-Service Site Creation, Enumerate " + ` + "Permissions, Manage Alerts, Manage Personal Views, Add/Remove Personal " + ` + "Web Parts or Update Personal Web Parts") + } + + It "Should return exception from the test method" { + { Test-TargetResource @testParams } | Should throw ("View Pages is required when " + ` + "specifying Manage Lists, Override List Behaviors, Add Items, Edit " + ` + "Items, Delete Items, View Items, Approve Items, Open Items, View " + ` + "Versions, Delete Versions, Create Alerts, Manage Permissions, View " + ` + "Web Analytics Data, Create Subsites, Manage Web Site, Add and " + ` + "Customize Pages, Apply Themes and Borders, Apply Style Sheets, Create " + ` + "Groups, Browse Directories, Use Self-Service Site Creation, Enumerate " + ` + "Permissions, Manage Alerts, Manage Personal Views, Add/Remove Personal " + ` + "Web Parts or Update Personal Web Parts") + } + + It "Should return exception from the set method" { + { Set-TargetResource @testParams } | Should throw ("View Pages is required when " + ` + "specifying Manage Lists, Override List Behaviors, Add Items, Edit " + ` + "Items, Delete Items, View Items, Approve Items, Open Items, View " + ` + "Versions, Delete Versions, Create Alerts, Manage Permissions, View " + ` + "Web Analytics Data, Create Subsites, Manage Web Site, Add and " + ` + "Customize Pages, Apply Themes and Borders, Apply Style Sheets, Create " + ` + "Groups, Browse Directories, Use Self-Service Site Creation, Enumerate " + ` + "Permissions, Manage Alerts, Manage Personal Views, Add/Remove Personal " + ` + "Web Parts or Update Personal Web Parts") } } - Context "Manage Permissions or Manage Web Site without Enumerate Permissions" { + Context -Name "Manage Permissions or Manage Web Site without Enumerate Permissions" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - Mock Get-SPWebApplication { return $null } - - It "returns exception from the get method" { + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Browse User Information","Manage Alerts", + "Use Remote Interfaces","Use Client Integration Features", + "Open","Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { { Get-TargetResource @testParams } | Should throw "Enumerate Permissions is required when specifying Manage Permissions or Manage Web Site" } - It "returns exception from the test method" { + It "Should return exception from the test method" { { Test-TargetResource @testParams } | Should throw "Enumerate Permissions is required when specifying Manage Permissions or Manage Web Site" } - It "returns exception from the set method" { + It "Should return exception from the set method" { { Set-TargetResource @testParams } | Should throw "Enumerate Permissions is required when specifying Manage Permissions or Manage Web Site" } } - Context "Manage Permissions, Create Subsites, Manage Web Site, Create Groups, Use Self-Service Site Creation, Enumerate Permissions or Edit Personal User Information without Browse User Information" { + Context -Name "Manage Permissions, Create Subsites, Manage Web Site, Create Groups, Use Self-Service Site Creation, Enumerate Permissions or Edit Personal User Information without Browse User Information" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - Mock Get-SPWebApplication { return $null } - - It "returns exception from the get method" { - { Get-TargetResource @testParams } | Should throw "Browse User Information is required when specifying Manage Permissions, Create Subsites, Manage Web Site, Create Groups, Use Self-Service Site Creation, Enumerate Permissions or Edit Personal User Information" - } - - It "returns exception from the test method" { - { Test-TargetResource @testParams } | Should throw "Browse User Information is required when specifying Manage Permissions, Create Subsites, Manage Web Site, Create Groups, Use Self-Service Site Creation, Enumerate Permissions or Edit Personal User Information" - } - - It "returns exception from the set method" { - { Set-TargetResource @testParams } | Should throw "Browse User Information is required when specifying Manage Permissions, Create Subsites, Manage Web Site, Create Groups, Use Self-Service Site Creation, Enumerate Permissions or Edit Personal User Information" + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Manage Alerts", + "Use Remote Interfaces","Use Client Integration Features", + "Open","Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { + { Get-TargetResource @testParams } | Should throw ("Browse User Information is " + ` + "required when specifying Manage Permissions, Create Subsites, " + ` + "Manage Web Site, Create Groups, Use Self-Service Site Creation, " + ` + "Enumerate Permissions or Edit Personal User Information") + } + + It "Should return exception from the test method" { + { Test-TargetResource @testParams } | Should throw ("Browse User Information is " + ` + "required when specifying Manage Permissions, Create Subsites, " + ` + "Manage Web Site, Create Groups, Use Self-Service Site Creation, " + ` + "Enumerate Permissions or Edit Personal User Information") + } + + It "Should return exception from the set method" { + { Set-TargetResource @testParams } | Should throw ("Browse User Information is " + ` + "required when specifying Manage Permissions, Create Subsites, " + ` + "Manage Web Site, Create Groups, Use Self-Service Site Creation, " + ` + "Enumerate Permissions or Edit Personal User Information") } } - Context "Use Client Integration Features without Use Remote Interfaces" { + Context -Name "Use Client Integration Features without Use Remote Interfaces" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - Mock Get-SPWebApplication { return $null } - - It "returns exception from the get method" { + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { { Get-TargetResource @testParams } | Should throw "Use Remote Interfaces is required when specifying Use Client Integration Features" } - It "returns exception from the test method" { + It "Should return exception from the test method" { { Test-TargetResource @testParams } | Should throw "Use Remote Interfaces is required when specifying Use Client Integration Features" } - It "returns exception from the set method" { + It "Should return exception from the set method" { { Set-TargetResource @testParams } | Should throw "Use Remote Interfaces is required when specifying Use Client Integration Features" } } - Context "Open is required when specifying any of the other permissions" { + Context -Name "Open is required when specifying any of the other permissions" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - Mock Get-SPWebApplication { return $null } - - It "returns exception from the get method" { + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { { Get-TargetResource @testParams } | Should throw "Open is required when specifying any of the other permissions" } - It "returns exception from the test method" { + It "Should return exception from the test method" { { Test-TargetResource @testParams } | Should throw "Open is required when specifying any of the other permissions" } - It "returns exception from the set method" { + It "Should return exception from the set method" { { Set-TargetResource @testParams } | Should throw "Open is required when specifying any of the other permissions" } } - Context "Add/Remove Personal Web Parts without Update Personal Web Parts" { + Context -Name "Add/Remove Personal Web Parts without Update Personal Web Parts" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts" } - Mock Get-SPWebApplication { return $null } - It "returns exception from the get method" { + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + + It "Should return exception from the get method" { { Get-TargetResource @testParams } | Should throw "Update Personal Web Parts is required when specifying Add/Remove Personal Web Parts" } - It "returns exception from the test method" { + It "Should return exception from the test method" { { Test-TargetResource @testParams } | Should throw "Update Personal Web Parts is required when specifying Add/Remove Personal Web Parts" } - It "returns exception from the set method" { + It "Should return exception from the set method" { { Set-TargetResource @testParams } | Should throw "Update Personal Web Parts is required when specifying Add/Remove Personal Web Parts" } } - Context "AllPermissions specified, but FullMask is not set" { + Context -Name "AllPermissions specified, but FullMask is not set" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" AllPermissions = $true } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $returnval = @{ - RightsMask = "ManageLists","CancelCheckout","AddListItems","EditListItems","DeleteListItems","ViewListItems","ApproveItems","OpenItems","ViewVersions","DeleteVersions","CreateAlerts","ViewFormPages" + RightsMask = @("ManageLists","CancelCheckout","AddListItems","EditListItems", + "DeleteListItems","ViewListItems","ApproveItems","OpenItems", + "ViewVersions","DeleteVersions","CreateAlerts","ViewFormPages") } - $returnval = $returnval | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $returnval = $returnval | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return $returnval } - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false - It "updates Web App permissions from the set method" { + $Global:SPDscWebApplicationUpdateCalled = $false + It "Should update Web App permissions from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "FullMask is set, but AllPermissions is not specified" { + Context -Name "FullMask is set, but AllPermissions is not specified" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - - Mock Get-SPWebApplication { + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + + Mock -CommandName Get-SPWebapplication -MockWith { $returnval = @{ RightsMask = "FullMask" } - $returnval = $returnval | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $returnval = $returnval | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return $returnval } - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false - It "updates Web App permissions from the set method" { + $Global:SPDscWebApplicationUpdateCalled = $false + It "Should update Web App permissions from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "AllPermissions specified and FullMask is set" { + Context -Name "AllPermissions specified and FullMask is set" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" AllPermissions = $true } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $returnval = @{ RightsMask = "FullMask" } - $returnval = $returnval | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $returnval = $returnval | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return $returnval } - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "List/Site/Personal permissions set, but ListPermissions does not match" { + Context -Name "List/Site/Personal permissions set, but ListPermissions does not match" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - - Mock Get-SPWebApplication { + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + + Mock -CommandName Get-SPWebapplication -MockWith { $returnval = @{ - RightsMask = "CancelCheckout","AddListItems","EditListItems","DeleteListItems","ViewListItems","ApproveItems","OpenItems","ViewVersions","DeleteVersions","CreateAlerts","ViewFormPages","ManagePermissions","ViewUsageData","ManageSubwebs","ManageWeb","AddAndCustomizePages","ApplyThemeAndBorder","ApplyStyleSheets","CreateGroups","BrowseDirectories","CreateSSCSite","ViewPages","EnumeratePermissions","BrowseUserInfo","ManageAlerts","UseRemoteAPIs","UseClientIntegration","Open","EditMyUserInfo","ManagePersonalViews","AddDelPrivateWebParts","UpdatePersonalWebParts" + RightsMask = @("CancelCheckout","AddListItems","EditListItems","DeleteListItems", + "ViewListItems","ApproveItems","OpenItems","ViewVersions", + "DeleteVersions","CreateAlerts","ViewFormPages", + "ManagePermissions","ViewUsageData","ManageSubwebs","ManageWeb", + "AddAndCustomizePages","ApplyThemeAndBorder","ApplyStyleSheets", + "CreateGroups","BrowseDirectories","CreateSSCSite","ViewPages", + "EnumeratePermissions","BrowseUserInfo","ManageAlerts","UseRemoteAPIs", + "UseClientIntegration","Open","EditMyUserInfo","ManagePersonalViews", + "AddDelPrivateWebParts","UpdatePersonalWebParts") } - $returnval = $returnval | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $returnval = $returnval | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return $returnval } - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false - It "updates Web App permissions from the set method" { + $Global:SPDscWebApplicationUpdateCalled = $false + It "Should update Web App permissions from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "List/Site/Personal permissions set, but SitePermissions does not match" { + Context -Name "List/Site/Personal permissions set, but SitePermissions does not match" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - - Mock Get-SPWebApplication { + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + + Mock -CommandName Get-SPWebapplication -MockWith { $returnval = @{ - RightsMask = "ManageLists","CancelCheckout","AddListItems","EditListItems","DeleteListItems","ViewListItems","ApproveItems","OpenItems","ViewVersions","DeleteVersions","CreateAlerts","ViewFormPages","ViewUsageData","ManageSubwebs","ManageWeb","AddAndCustomizePages","ApplyThemeAndBorder","ApplyStyleSheets","CreateGroups","BrowseDirectories","CreateSSCSite","ViewPages","EnumeratePermissions","BrowseUserInfo","ManageAlerts","UseRemoteAPIs","UseClientIntegration","Open","EditMyUserInfo","ManagePersonalViews","AddDelPrivateWebParts","UpdatePersonalWebParts" + RightsMask = @("ManageLists","CancelCheckout","AddListItems","EditListItems", + "DeleteListItems","ViewListItems","ApproveItems","OpenItems", + "ViewVersions","DeleteVersions","CreateAlerts","ViewFormPages", + "ViewUsageData","ManageSubwebs","ManageWeb", + "AddAndCustomizePages","ApplyThemeAndBorder","ApplyStyleSheets", + "CreateGroups","BrowseDirectories","CreateSSCSite","ViewPages", + "EnumeratePermissions","BrowseUserInfo","ManageAlerts", + "UseRemoteAPIs","UseClientIntegration","Open","EditMyUserInfo", + "ManagePersonalViews","AddDelPrivateWebParts", + "UpdatePersonalWebParts") } - $returnval = $returnval | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $returnval = $returnval | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return $returnval } - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false - It "updates Web App permissions from the set method" { + $Global:SPDscWebApplicationUpdateCalled = $false + It "Should update Web App permissions from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "List/Site/Personal permissions set, but PersonalPermissions does not match" { + Context -Name "List/Site/Personal permissions set, but PersonalPermissions does not match" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - - Mock Get-SPWebApplication { + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + + Mock -CommandName Get-SPWebapplication -MockWith { $returnval = @{ - RightsMask = "ManageLists","CancelCheckout","AddListItems","EditListItems","DeleteListItems","ViewListItems","ApproveItems","OpenItems","ViewVersions","DeleteVersions","CreateAlerts","ViewFormPages","ManagePermissions","ViewUsageData","ManageSubwebs","ManageWeb","AddAndCustomizePages","ApplyThemeAndBorder","ApplyStyleSheets","CreateGroups","BrowseDirectories","CreateSSCSite","ViewPages","EnumeratePermissions","BrowseUserInfo","ManageAlerts","UseRemoteAPIs","UseClientIntegration","Open","EditMyUserInfo","AddDelPrivateWebParts","UpdatePersonalWebParts" + RightsMask = @("ManageLists","CancelCheckout","AddListItems","EditListItems", + "DeleteListItems","ViewListItems","ApproveItems","OpenItems", + "ViewVersions","DeleteVersions","CreateAlerts","ViewFormPages", + "ManagePermissions","ViewUsageData","ManageSubwebs","ManageWeb", + "AddAndCustomizePages","ApplyThemeAndBorder","ApplyStyleSheets", + "CreateGroups","BrowseDirectories","CreateSSCSite","ViewPages", + "EnumeratePermissions","BrowseUserInfo","ManageAlerts", + "UseRemoteAPIs","UseClientIntegration","Open","EditMyUserInfo", + "AddDelPrivateWebParts","UpdatePersonalWebParts") } - $returnval = $returnval | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $returnval = $returnval | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return $returnval } - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false - It "updates Web App permissions from the set method" { + $Global:SPDscWebApplicationUpdateCalled = $false + It "Should update Web App permissions from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "List/Site/Personal permissions set and all permissions match" { + Context -Name "List/Site/Personal permissions set and all permissions match" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" - ListPermissions = "Manage Lists","Override List Behaviors", "Add Items","Edit Items","Delete Items","View Items","Approve Items","Open Items","View Versions","Delete Versions","Create Alerts","View Application Pages" - SitePermissions = "Manage Permissions","View Web Analytics Data","Create Subsites","Manage Web Site","Add and Customize Pages","Apply Themes and Borders","Apply Style Sheets","Create Groups","Browse Directories","Use Self-Service Site Creation","View Pages","Enumerate Permissions","Browse User Information","Manage Alerts","Use Remote Interfaces","Use Client Integration Features","Open","Edit Personal User Information" - PersonalPermissions = "Manage Personal Views","Add/Remove Personal Web Parts","Update Personal Web Parts" - } - - Mock Get-SPWebApplication { + ListPermissions = @("Manage Lists","Override List Behaviors", "Add Items", + "Edit Items","Delete Items","View Items","Approve Items", + "Open Items","View Versions","Delete Versions", + "Create Alerts","View Application Pages") + SitePermissions = @("Manage Permissions","View Web Analytics Data", + "Create Subsites","Manage Web Site", + "Add and Customize Pages","Apply Themes and Borders", + "Apply Style Sheets","Create Groups","Browse Directories", + "Use Self-Service Site Creation","View Pages", + "Enumerate Permissions","Browse User Information", + "Manage Alerts","Use Remote Interfaces", + "Use Client Integration Features","Open", + "Edit Personal User Information") + PersonalPermissions = @("Manage Personal Views","Add/Remove Personal Web Parts", + "Update Personal Web Parts") + } + + Mock -CommandName Get-SPWebapplication -MockWith { $returnval = @{ - RightsMask = "ManageLists","CancelCheckout","AddListItems","EditListItems","DeleteListItems","ViewListItems","ApproveItems","OpenItems","ViewVersions","DeleteVersions","CreateAlerts","ViewFormPages","ManagePermissions","ViewUsageData","ManageSubwebs","ManageWeb","AddAndCustomizePages","ApplyThemeAndBorder","ApplyStyleSheets","CreateGroups","BrowseDirectories","CreateSSCSite","ViewPages","EnumeratePermissions","BrowseUserInfo","ManageAlerts","UseRemoteAPIs","UseClientIntegration","Open","EditMyUserInfo","ManagePersonalViews","AddDelPrivateWebParts","UpdatePersonalWebParts" + RightsMask = @("ManageLists","CancelCheckout","AddListItems","EditListItems", + "DeleteListItems","ViewListItems","ApproveItems","OpenItems", + "ViewVersions","DeleteVersions","CreateAlerts","ViewFormPages", + "ManagePermissions","ViewUsageData","ManageSubwebs","ManageWeb", + "AddAndCustomizePages","ApplyThemeAndBorder","ApplyStyleSheets", + "CreateGroups","BrowseDirectories","CreateSSCSite","ViewPages", + "EnumeratePermissions","BrowseUserInfo","ManageAlerts", + "UseRemoteAPIs","UseClientIntegration","Open","EditMyUserInfo", + "ManagePersonalViews","AddDelPrivateWebParts", + "UpdatePersonalWebParts") } - $returnval = $returnval | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $returnval = $returnval | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return $returnval } - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppPolicy.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppPolicy.Tests.ps1 index b4c1c0a87..4458fa1a3 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppPolicy.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppPolicy.Tests.ps1 @@ -1,92 +1,89 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPWebAppPolicy" -$ModuleName = "MSFT_SPWebAppPolicy" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPWebAppPolicy - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - WebAppUrl = "http://sharepoint.contoso.com" - Members = @( - (New-CimInstance -ClassName MSFT_SPWebAppPolicy -Property @{ - Username = "contoso\user1" - PermissionLevel = "Full Control" - ActAsSystemAccount = $true - } -ClientOnly) - (New-CimInstance -ClassName MSFT_SPWebAppPolicy -Property @{ - Username = "contoso\user2" - PermissionLevel = "Full Read" - ActAsSystemAccount = $false - } -ClientOnly) - ) - } - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + # Initialize tests + try { [Microsoft.SharePoint.Administration.SPPolicyRoleType] } + catch { + Add-Type -TypeDefinition @" +namespace Microsoft.SharePoint.Administration { + public enum SPPolicyRoleType { FullRead, FullControl, DenyWrite, DenyAll }; +} +"@ } - Mock Test-SPDSCIsADUser { + # Mocks for all contexts + Mock -CommandName Test-SPDSCIsADUser { return $true } - Mock New-SPClaimsPrincipal { + Mock -CommandName New-SPClaimsPrincipal -MockWith { return @{ Value = $Identity -replace "i:0#.w\|" } } -ParameterFilter { $IdentityType -eq "EncodedClaim" } - Mock New-SPClaimsPrincipal { - $Global:SPDSCClaimsPrincipalUser = $Identity + Mock -CommandName New-SPClaimsPrincipal -MockWith { + $Global:SPDscClaimsPrincipalUser = $Identity return ( - New-Object Object | Add-Member ScriptMethod ToEncodedString { - return "i:0#.w|$($Global:SPDSCClaimsPrincipalUser)" + New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod ToEncodedString { + return "i:0#.w|$($Global:SPDscClaimsPrincipalUser)" } -PassThru ) } -ParameterFilter { $IdentityType -eq "WindowsSamAccountName" } - Mock Remove-SPDSCGenericObject { } - - try { [Microsoft.SharePoint.Administration.SPPolicyRoleType] } - catch { - Add-Type @" -namespace Microsoft.SharePoint.Administration { - public enum SPPolicyRoleType { FullRead, FullControl, DenyWrite, DenyAll }; -} -"@ - } + Mock -CommandName Remove-SPDSCGenericObject { } + # Test contexts + Context -Name "The web application doesn't exist" -Fixture { + $testParams = @{ + WebAppUrl = "http://sharepoint.contoso.com" + Members = @( + (New-CimInstance -ClassName MSFT_SPWebAppPolicy -Property @{ + Username = "contoso\user1" + PermissionLevel = "Full Control" + ActAsSystemAccount = $true + } -ClientOnly) + (New-CimInstance -ClassName MSFT_SPWebAppPolicy -Property @{ + Username = "contoso\user2" + PermissionLevel = "Full Read" + ActAsSystemAccount = $false + } -ClientOnly) + ) + } - Context "The web application doesn't exist" { - Mock Get-SPWebApplication { return $null } + Mock -CommandName Get-SPWebapplication -MockWith { return $null } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "returns null from the set method" { + It "Should return null from the set method" { { Set-TargetResource @testParams } | Should throw "Web application does not exist" } } - Context "Members and MembersToInclude parameters used simultaniously" { + Context -Name "Members and MembersToInclude parameters used simultaniously" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" Members = @( @@ -105,38 +102,38 @@ namespace Microsoft.SharePoint.Administration { ) } - It "return null from the get method" { - Get-TargetResource @testParams | Should Be $null + It "Should return null from the get method" { + Get-TargetResource @testParams | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "Cannot use the Members parameter together with the MembersToInclude or MembersToExclude parameters" } } - Context "No Member parameters at all" { + Context -Name "No Member parameters at all" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" } - It "return null from the get method" { - Get-TargetResource @testParams | Should Be $null + It "Should return null from the get method" { + Get-TargetResource @testParams | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "At least one of the following parameters must be specified: Members, MembersToInclude, MembersToExclude" } } - Context "ActAsSystemAccount parameter specified without Full Control in Members" { + Context -Name "ActAsSystemAccount parameter specified without Full Control in Members" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" Members = @( @@ -148,20 +145,20 @@ namespace Microsoft.SharePoint.Administration { ) } - It "return null from the get method" { - Get-TargetResource @testParams | Should Be $null + It "Should return null from the get method" { + Get-TargetResource @testParams | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "Members Parameter: You cannot specify ActAsSystemAccount with any other permission than Full Control" } } - Context "ActAsSystemAccount parameter specified without Full Control in MembersToInclude" { + Context -Name "ActAsSystemAccount parameter specified without Full Control in MembersToInclude" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" MembersToInclude = @( @@ -173,20 +170,20 @@ namespace Microsoft.SharePoint.Administration { ) } - It "return null from the get method" { - Get-TargetResource @testParams | Should Be $null + It "Should return null from the get method" { + Get-TargetResource @testParams | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "MembersToInclude Parameter: You cannot specify ActAsSystemAccount with any other permission than Full Control" } } - Context "The Members parameter used with SetCacheAccounts to True, but the Cache Users users aren't configured in the policy" { + Context -Name "The Members parameter used with SetCacheAccounts to True, but the Cache Users users aren't configured in the policy" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" Members = @( @@ -198,14 +195,14 @@ namespace Microsoft.SharePoint.Administration { ) SetCacheAccounts=$true } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Read" } ) - $roleBindings = $roleBindings | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $policies = @( @@ -215,12 +212,12 @@ namespace Microsoft.SharePoint.Administration { IsSystemUser = $false } ) - $policies = $policies | Add-Member ScriptMethod Add { + $policies = $policies | Add-Member -MemberType ScriptMethod -Name Add -Value { $policy = @{ IsSystemUser = $false } - $policy = $policy | Add-Member ScriptProperty PolicyRoleBindings { - return New-Object Object | Add-Member ScriptMethod Add {} -PassThru + $policy = $policy | Add-Member ScriptProperty -Name PolicyRoleBindings -Value { + return New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod -Name Add -Value {} -PassThru } -PassThru return $policy } -PassThru -Force @@ -228,8 +225,8 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{ portalsuperuseraccount = "contoso\sp_psu" @@ -237,29 +234,29 @@ namespace Microsoft.SharePoint.Administration { } } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false + $Global:SPDscWebApplicationUpdateCalled = $false It "add user policy from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "The MembersToInclude parameter used with SetCacheAccounts to True, but the Cache Users users aren't configured in the policy" { + Context -Name "The MembersToInclude parameter used with SetCacheAccounts to True, but the Cache Users users aren't configured in the policy" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" MembersToInclude = @( @@ -271,14 +268,14 @@ namespace Microsoft.SharePoint.Administration { ) SetCacheAccounts=$true } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Read" } ) - $roleBindings = $roleBindings | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $policies = @( @@ -288,12 +285,12 @@ namespace Microsoft.SharePoint.Administration { IsSystemUser = $false } ) - $policies = $policies | Add-Member ScriptMethod Add { + $policies = $policies | Add-Member -MemberType ScriptMethod -Name Add -Value { $policy = @{ IsSystemUser = $false } - $policy = $policy | Add-Member ScriptProperty PolicyRoleBindings { - return New-Object Object | Add-Member ScriptMethod Add {} -PassThru + $policy = $policy | Add-Member ScriptProperty -Name PolicyRoleBindings -Value { + return New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod -Name Add -Value {} -PassThru } -PassThru return $policy } -PassThru -Force @@ -301,8 +298,8 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{ portalsuperuseraccount = "contoso\sp_psu" @@ -310,29 +307,29 @@ namespace Microsoft.SharePoint.Administration { } } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false + $Global:SPDscWebApplicationUpdateCalled = $false It "add user policy from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "The Members parameter used with SetCacheAccounts to True, but the Cache Users users aren't configured in the webapp" { + Context -Name "The Members parameter used with SetCacheAccounts to True, but the Cache Users users aren't configured in the webapp" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" Members = @( @@ -344,14 +341,14 @@ namespace Microsoft.SharePoint.Administration { ) SetCacheAccounts=$true } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Read" } ) - $roleBindings = $roleBindings | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $policies = @( @@ -361,12 +358,12 @@ namespace Microsoft.SharePoint.Administration { IsSystemUser = $false } ) - $policies = $policies | Add-Member ScriptMethod Add { + $policies = $policies | Add-Member -MemberType ScriptMethod -Name Add -Value { $policy = @{ IsSystemUser = $false } - $policy = $policy | Add-Member ScriptProperty PolicyRoleBindings { - return New-Object Object | Add-Member ScriptMethod Add {} -PassThru + $policy = $policy | Add-Member ScriptProperty -Name PolicyRoleBindings -Value { + return New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod -Name Add -Value {} -PassThru } -PassThru return $policy } -PassThru -Force @@ -374,34 +371,34 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{ } } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should throw exception in the test method" { + It "Should throw exception in the test method" { { Test-TargetResource @testParams } | Should throw "Cache accounts not configured properly. PortalSuperUserAccount or PortalSuperReaderAccount property is not configured." } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should throw "Cache accounts not configured properly. PortalSuperUserAccount or PortalSuperReaderAccount property is not configured." } } - Context "The MembersToInclude parameter used with SetCacheAccounts to True, but the Cache Users users aren't configured in the webapp" { + Context -Name "The MembersToInclude parameter used with SetCacheAccounts to True, but the Cache Users users aren't configured in the webapp" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" MembersToInclude = @( @@ -413,14 +410,14 @@ namespace Microsoft.SharePoint.Administration { ) SetCacheAccounts=$true } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Read" } ) - $roleBindings = $roleBindings | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $policies = @( @@ -430,12 +427,12 @@ namespace Microsoft.SharePoint.Administration { IsSystemUser = $false } ) - $policies = $policies | Add-Member ScriptMethod Add { + $policies = $policies | Add-Member -MemberType ScriptMethod -Name Add -Value { $policy = @{ IsSystemUser = $false } - $policy = $policy | Add-Member ScriptProperty PolicyRoleBindings { - return New-Object Object | Add-Member ScriptMethod Add {} -PassThru + $policy = $policy | Add-Member ScriptProperty -Name PolicyRoleBindings -Value { + return New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod -Name Add -Value {} -PassThru } -PassThru return $policy } -PassThru -Force @@ -443,34 +440,34 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{ } } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should throw exception in the test method" { + It "Should throw exception in the test method" { { Test-TargetResource @testParams } | Should throw "Cache accounts not configured properly. PortalSuperUserAccount or PortalSuperReaderAccount property is not configured." } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should throw "Cache accounts not configured properly. PortalSuperUserAccount or PortalSuperReaderAccount property is not configured." } } - Context "The Members parameter used with SetCacheAccounts to True and the Cache Users users are configured correctly" { + Context -Name "The Members parameter used with SetCacheAccounts to True and the Cache Users users are configured correctly" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" Members = @( @@ -482,14 +479,14 @@ namespace Microsoft.SharePoint.Administration { ) SetCacheAccounts=$true } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindingsFR = @( @{ Name = "Full Read" } ) - $roleBindingsFR = $roleBindingsFR | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindingsFR = $roleBindingsFR | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $roleBindingsFC = @( @@ -497,8 +494,8 @@ namespace Microsoft.SharePoint.Administration { Name = "Full Control" } ) - $roleBindingsFC = $roleBindingsFC | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindingsFC = $roleBindingsFC | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $policies = @( @@ -518,12 +515,12 @@ namespace Microsoft.SharePoint.Administration { IsSystemUser = $false } ) - $policies = $policies | Add-Member ScriptMethod Add { + $policies = $policies | Add-Member -MemberType ScriptMethod -Name Add -Value { $policy = @{ IsSystemUser = $false } - $policy = $policy | Add-Member ScriptProperty PolicyRoleBindings { - return New-Object Object | Add-Member ScriptMethod Add {} -PassThru + $policy = $policy | Add-Member ScriptProperty -Name PolicyRoleBindings -Value { + return New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod -Name Add -Value {} -PassThru } -PassThru return $policy } -PassThru -Force @@ -531,8 +528,8 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{ portalsuperuseraccount = "i:0#.w|contoso\sp_psu" @@ -540,23 +537,23 @@ namespace Microsoft.SharePoint.Administration { } } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The MembersToInclude parameter used with SetCacheAccounts to True and the Cache Users users are configured correctly" { + Context -Name "The MembersToInclude parameter used with SetCacheAccounts to True and the Cache Users users are configured correctly" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" MembersToInclude = @( @@ -568,14 +565,14 @@ namespace Microsoft.SharePoint.Administration { ) SetCacheAccounts=$true } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindingsFR = @( @{ Name = "Full Read" } ) - $roleBindingsFR = $roleBindingsFR | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindingsFR = $roleBindingsFR | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $roleBindingsFC = @( @@ -583,8 +580,8 @@ namespace Microsoft.SharePoint.Administration { Name = "Full Control" } ) - $roleBindingsFC = $roleBindingsFC | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindingsFC = $roleBindingsFC | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $policies = @( @@ -604,12 +601,12 @@ namespace Microsoft.SharePoint.Administration { IsSystemUser = $false } ) - $policies = $policies | Add-Member ScriptMethod Add { + $policies = $policies | Add-Member -MemberType ScriptMethod -Name Add -Value { $policy = @{ IsSystemUser = $false } - $policy = $policy | Add-Member ScriptProperty PolicyRoleBindings { - return New-Object Object | Add-Member ScriptMethod Add {} -PassThru + $policy = $policy | Add-Member ScriptProperty -Name PolicyRoleBindings -Value { + return New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod -Name Add -Value {} -PassThru } -PassThru return $policy } -PassThru -Force @@ -617,8 +614,8 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{ portalsuperuseraccount = "contoso\sp_psu" @@ -626,23 +623,23 @@ namespace Microsoft.SharePoint.Administration { } } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The MembersToExclude parameter used, but it specifies a Cache User" { + Context -Name "The MembersToExclude parameter used, but it specifies a Cache User" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" MembersToExclude = @( @@ -653,14 +650,14 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindingsFR = @( @{ Name = "Full Read" } ) - $roleBindingsFR = $roleBindingsFR | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindingsFR = $roleBindingsFR | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $roleBindingsFC = @( @@ -668,8 +665,8 @@ namespace Microsoft.SharePoint.Administration { Name = "Full Control" } ) - $roleBindingsFC = $roleBindingsFC | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindingsFC = $roleBindingsFC | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $policies = @( @@ -689,12 +686,12 @@ namespace Microsoft.SharePoint.Administration { IsSystemUser = $false } ) - $policies = $policies | Add-Member ScriptMethod Add { + $policies = $policies | Add-Member -MemberType ScriptMethod -Name Add -Value { $policy = @{ IsSystemUser = $false } - $policy = $policy | Add-Member ScriptProperty PolicyRoleBindings { - return New-Object Object | Add-Member ScriptMethod Add {} -PassThru + $policy = $policy | Add-Member ScriptProperty -Name PolicyRoleBindings -Value { + return New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod -Name Add -Value {} -PassThru } -PassThru return $policy } -PassThru -Force @@ -702,8 +699,8 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{ portalsuperuseraccount = "contoso\sp_psu" @@ -711,27 +708,27 @@ namespace Microsoft.SharePoint.Administration { } } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "should throw exception in the test method" { + It "Should throw exception in the test method" { { Test-TargetResource @testParams } | Should throw "You cannot exclude the Cache accounts from the Web Application Policy" } - It "should throw exception in the set method" { + It "Should throw exception in the set method" { { Set-TargetResource @testParams } | Should throw "You cannot exclude the Cache accounts from the Web Application Policy" } } - Context "The Members parameter contains users that aren't configured in the policy" { + Context -Name "The Members parameter contains users that aren't configured in the policy" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" Members = @( @@ -747,14 +744,14 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Read" } ) - $roleBindings = $roleBindings | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $policies = @( @@ -764,12 +761,12 @@ namespace Microsoft.SharePoint.Administration { IsSystemUser = $false } ) - $policies = $policies | Add-Member ScriptMethod Add { + $policies = $policies | Add-Member -MemberType ScriptMethod -Name Add -Value { $policy = @{ IsSystemUser = $false } - $policy = $policy | Add-Member ScriptProperty PolicyRoleBindings { - return New-Object Object | Add-Member ScriptMethod Add {} -PassThru + $policy = $policy | Add-Member ScriptProperty -Name PolicyRoleBindings -Value { + return New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod -Name Add -Value {} -PassThru } -PassThru return $policy } -PassThru -Force @@ -777,33 +774,33 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the set method" { + It "Should return false from the set method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false + $Global:SPDscWebApplicationUpdateCalled = $false It "add user policy from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "The Members parameter does not contains users that are configured in the policy" { + Context -Name "The Members parameter does not contains users that are configured in the policy" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" Members = @( @@ -814,14 +811,14 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Read" } ) - $roleBindings = $roleBindings | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $policies = @( @@ -840,33 +837,33 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false + $Global:SPDscWebApplicationUpdateCalled = $false It "remove user policy from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "The MembersToInclude parameter contains users that are not configured in the policy" { + Context -Name "The MembersToInclude parameter contains users that are not configured in the policy" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" MembersToInclude = @( @@ -882,14 +879,14 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Read" } ) - $roleBindings = $roleBindings | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $policies = @( @@ -899,12 +896,12 @@ namespace Microsoft.SharePoint.Administration { IsSystemUser = $false } ) - $policies = $policies | Add-Member ScriptMethod Add { + $policies = $policies | Add-Member -MemberType ScriptMethod -Name Add -Value { $policy = @{ IsSystemUser = $false } - $policy = $policy | Add-Member ScriptProperty PolicyRoleBindings { - return New-Object Object | Add-Member ScriptMethod Add {} -PassThru + $policy = $policy | Add-Member ScriptProperty -Name PolicyRoleBindings -Value { + return New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod -Name Add -Value {} -PassThru } -PassThru return $policy } -PassThru -Force @@ -912,33 +909,33 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false + $Global:SPDscWebApplicationUpdateCalled = $false It "add user policy from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "The MembersToInclude parameter contains users that are configured in the policy" { + Context -Name "The MembersToInclude parameter contains users that are configured in the policy" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" MembersToInclude = @( @@ -949,7 +946,7 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Read" @@ -972,8 +969,8 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } @@ -982,16 +979,16 @@ namespace Microsoft.SharePoint.Administration { - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The MembersToExclude parameter contains users that are configured in the policy" { + Context -Name "The MembersToExclude parameter contains users that are configured in the policy" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" MembersToExclude = @( @@ -1000,14 +997,14 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Read" } ) - $roleBindings = $roleBindings | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru $policies = @( @@ -1026,34 +1023,34 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru | - Add-Member NoteProperty Properties @{} -PassThru + Add-Member -MemberType NoteProperty Properties @{} -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false + $Global:SPDscWebApplicationUpdateCalled = $false It "remove user policy from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "The users in the Members parameter have different settings than configured in the policy" { + Context -Name "The users in the Members parameter have different settings than configured in the policy" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" Members = @( @@ -1064,17 +1061,17 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Read" } ) - $roleBindings = $roleBindings | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru - $roleBindings = $roleBindings | Add-Member ScriptMethod Add { - $Global:SPWebAppPolicyAddCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name Add -Value { + $Global:SPDscWebAppPolicyAddCalled = $true } -PassThru -Force $policies = @( @@ -1084,12 +1081,12 @@ namespace Microsoft.SharePoint.Administration { IsSystemUser = $false } ) - $policies = $policies | Add-Member ScriptMethod Add { + $policies = $policies | Add-Member -MemberType ScriptMethod -Name Add -Value { $policy = @{ IsSystemUser = $false } - $policy = $policy | Add-Member ScriptProperty PolicyRoleBindings { - return New-Object Object | Add-Member ScriptMethod Add {} -PassThru + $policy = $policy | Add-Member ScriptProperty -Name PolicyRoleBindings -Value { + return New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod -Name Add -Value {} -PassThru } -PassThru return $policy } -PassThru -Force @@ -1097,33 +1094,33 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false + $Global:SPDscWebApplicationUpdateCalled = $false It "correct user policy from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "The users in the MembersToInclude parameter have different settings than configured in the policy" { + Context -Name "The users in the MembersToInclude parameter have different settings than configured in the policy" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" MembersToInclude = @( @@ -1134,17 +1131,17 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Read" } ) - $roleBindings = $roleBindings | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru - $roleBindings = $roleBindings | Add-Member ScriptMethod Add { - $Global:SPWebAppPolicyAddCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name Add -Value { + $Global:SPDscWebAppPolicyAddCalled = $true } -PassThru -Force $policies = @( @@ -1154,12 +1151,12 @@ namespace Microsoft.SharePoint.Administration { IsSystemUser = $false } ) - $policies = $policies | Add-Member ScriptMethod Add { + $policies = $policies | Add-Member -MemberType ScriptMethod -Name Add -Value { $policy = @{ IsSystemUser = $false } - $policy = $policy | Add-Member ScriptProperty PolicyRoleBindings { - return New-Object Object | Add-Member ScriptMethod Add {} -PassThru + $policy = $policy | Add-Member ScriptProperty -Name PolicyRoleBindings -Value { + return New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod -Name Add -Value {} -PassThru } -PassThru return $policy } -PassThru -Force @@ -1167,33 +1164,33 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false + $Global:SPDscWebApplicationUpdateCalled = $false It "correct user policy from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "The users in the Members parameter have different settings than configured in the policy - ActAsSystemAccount" { + Context -Name "The users in the Members parameter have different settings than configured in the policy - ActAsSystemAccount" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" Members = @( @@ -1204,17 +1201,17 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Control" } ) - $roleBindings = $roleBindings | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru - $roleBindings = $roleBindings | Add-Member ScriptMethod Add { - $Global:SPWebAppPolicyAddCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name Add -Value { + $Global:SPDscWebAppPolicyAddCalled = $true } -PassThru -Force $policies = @( @@ -1224,12 +1221,12 @@ namespace Microsoft.SharePoint.Administration { IsSystemUser = $false } ) - $policies = $policies | Add-Member ScriptMethod Add { + $policies = $policies | Add-Member -MemberType ScriptMethod -Name Add -Value { $policy = @{ IsSystemUser = $false } - $policy = $policy | Add-Member ScriptProperty PolicyRoleBindings { - return New-Object Object | Add-Member ScriptMethod Add {} -PassThru + $policy = $policy | Add-Member ScriptProperty -Name PolicyRoleBindings -Value { + return New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod -Name Add -Value {} -PassThru } -PassThru return $policy } -PassThru -Force @@ -1237,33 +1234,33 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false + $Global:SPDscWebApplicationUpdateCalled = $false It "correct user policy from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "The users in the MembersToInclude parameter have different settings than configured in the policy - ActAsSystemAccount" { + Context -Name "The users in the MembersToInclude parameter have different settings than configured in the policy - ActAsSystemAccount" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" MembersToInclude = @( @@ -1274,17 +1271,17 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Control" } ) - $roleBindings = $roleBindings | Add-Member ScriptMethod RemoveAll { - $Global:SPWebAppPolicyRemoveAllCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name RemoveAll -Value { + $Global:SPDscWebAppPolicyRemoveAllCalled = $true } -PassThru - $roleBindings = $roleBindings | Add-Member ScriptMethod Add { - $Global:SPWebAppPolicyAddCalled = $true + $roleBindings = $roleBindings | Add-Member -MemberType ScriptMethod -Name Add -Value { + $Global:SPDscWebAppPolicyAddCalled = $true } -PassThru -Force $policies = @( @@ -1294,12 +1291,12 @@ namespace Microsoft.SharePoint.Administration { IsSystemUser = $false } ) - $policies = $policies | Add-Member ScriptMethod Add { + $policies = $policies | Add-Member -MemberType ScriptMethod -Name Add -Value { $policy = @{ IsSystemUser = $false } - $policy = $policy | Add-Member ScriptProperty PolicyRoleBindings { - return New-Object Object | Add-Member ScriptMethod Add {} -PassThru + $policy = $policy | Add-Member ScriptProperty -Name PolicyRoleBindings -Value { + return New-Object -TypeName "Object" | Add-Member -MemberType ScriptMethod -Name Add -Value {} -PassThru } -PassThru return $policy } -PassThru -Force @@ -1307,33 +1304,33 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true } -PassThru return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false + $Global:SPDscWebApplicationUpdateCalled = $false It "correct user policy from the set method" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } } - Context "The users in the Members parameter have the same settings as configured in the policy" { + Context -Name "The users in the Members parameter have the same settings as configured in the policy" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" Members = @( @@ -1345,7 +1342,7 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Control" @@ -1363,24 +1360,24 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The users in the Members parameter have the same settings as configured in the policy, in Claims format" { + Context -Name "The users in the Members parameter have the same settings as configured in the policy, in Claims format" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" Members = @( @@ -1392,7 +1389,7 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Control" @@ -1410,24 +1407,24 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The users in the MembersToInclude parameter have the same settings as configured in the policy" { + Context -Name "The users in the MembersToInclude parameter have the same settings as configured in the policy" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" MembersToInclude = @( @@ -1438,7 +1435,7 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Control" @@ -1456,24 +1453,24 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The users in the MembersToExclude parameter aren't configured in the policy" { + Context -Name "The users in the MembersToExclude parameter aren't configured in the policy" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" MembersToExclude = @( @@ -1482,7 +1479,7 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Control" @@ -1500,24 +1497,24 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } return @($webApp) } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The users in the Members parameter have the same settings as configured in the policy, in Claims format with a windows group in the results" { + Context -Name "The users in the Members parameter have the same settings as configured in the policy, in Claims format with a windows group in the results" -Fixture { $testParams = @{ WebAppUrl = "http://sharepoint.contoso.com" Members = @( @@ -1529,7 +1526,7 @@ namespace Microsoft.SharePoint.Administration { } -ClientOnly) ) } - Mock Get-SPWebApplication { + Mock -CommandName Get-SPWebapplication -MockWith { $roleBindings = @( @{ Name = "Full Control" @@ -1547,8 +1544,8 @@ namespace Microsoft.SharePoint.Administration { $webApp = @{ Url = $testParams.WebAppUrl UseClaimsAuthentication = $true - PolicyRoles = New-Object Object | - Add-Member ScriptMethod GetSpecialRole { return @{} } -PassThru + PolicyRoles = New-Object -TypeName "Object" | + Add-Member -MemberType ScriptMethod -Name GetSpecialRole -Value { return @{} } -PassThru Policies = $policies Properties = @{} } @@ -1558,13 +1555,15 @@ namespace Microsoft.SharePoint.Administration { return "contoso\group1" } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppProxyGroup.tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppProxyGroup.tests.ps1 index a98d3f41b..ccad6cf82 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppProxyGroup.tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppProxyGroup.tests.ps1 @@ -1,95 +1,98 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPWebAppProxyGroup" -$ModuleName = "MSFT_SPWebAppProxyGroup" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDSC\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPWebAppProxyGroup - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") + # Initialize tests - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - - - - - Context "WebApplication does not exist" { + # Mocks for all contexts + Mock -CommandName Set-SPWebApplication -MockWith { } + + # Test contexts + Context -Name "WebApplication does not exist" -Fixture { $testParams = @{ WebAppUrl = "https://web.contoso.com" ServiceAppProxyGroup = "Web1ProxyGroup" } - Mock get-spwebapplication {} + Mock -CommandName Get-SPWebApplication -MockWIth {} - It "return null property from the get method" { + It "Should return null property from the get method" { (Get-TargetResource @testParams).WebAppUrl | Should Be $null } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } } - Context "WebApplication Proxy Group connection matches desired config" { + Context -Name "WebApplication Proxy Group connection matches desired config" -Fixture { $testParams = @{ WebAppUrl = "https://web.contoso.com" ServiceAppProxyGroup = "Web1ProxyGroup" } - Mock get-spwebapplication { return @{ ServiceApplicationProxyGroup = @{ name = "Web1ProxyGroup"}} } + Mock -CommandName Get-SPWebApplication -MockWIth { + return @{ + ServiceApplicationProxyGroup = @{ + Name = "Web1ProxyGroup" + } + } + } - It "return values from the get method" { + It "Should return values from the get method" { (Get-TargetResource @testParams).ServiceAppProxyGroup | Should Be "Web1ProxyGroup" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "WebApplication Proxy Group connection does not match desired config" { + Context -Name "WebApplication Proxy Group connection does not match desired config" -Fixture { $testParams = @{ WebAppUrl = "https://web.contoso.com" ServiceAppProxyGroup = "Default" } - Mock get-spwebapplication { return @{ ServiceApplicationProxyGroup = @{ name = "Web1ProxyGroup"}} } - Mock set-spwebapplication { } + Mock -CommandName Get-SPWebApplication -MockWIth { + return @{ + ServiceApplicationProxyGroup = @{ + Name = "Web1ProxyGroup" + } + } + } - It "return values from the get method" { + It "Should return values from the get method" { (Get-TargetResource @testParams).ServiceAppProxyGroup | Should Be "Web1ProxyGroup" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "updates the webapplication from the set method" { + It "Should update the webapplication from the set method" { Set-TargetResource @testParams Assert-MockCalled Set-SPWebApplication } } - - - - - } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppSiteUseAndDeletion.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppSiteUseAndDeletion.Tests.ps1 index e2351b8fe..e5e73715e 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppSiteUseAndDeletion.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppSiteUseAndDeletion.Tests.ps1 @@ -1,118 +1,146 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPWebAppSiteUseAndDeletion" -$ModuleName = "MSFT_SPWebAppSiteUseAndDeletion" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPWebAppSiteUseAndDeletion - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Url = "http://example.contoso.local" - SendUnusedSiteCollectionNotifications = $true - UnusedSiteNotificationPeriod = 90 - AutomaticallyDeleteUnusedSiteCollections = $true - UnusedSiteNotificationsBeforeDeletion = 30 - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue + # Initialize tests + + # Mocks for all contexts - Context "The server is not part of SharePoint farm" { - Mock Get-SPFarm { throw "Unable to detect local farm" } + # Test contexts + Context -Name "The server is not part of SharePoint farm" -Fixture { + $testParams = @{ + Url = "http://example.contoso.local" + SendUnusedSiteCollectionNotifications = $true + UnusedSiteNotificationPeriod = 90 + AutomaticallyDeleteUnusedSiteCollections = $true + UnusedSiteNotificationsBeforeDeletion = 30 + } + + Mock -CommandName Get-SPFarm -MockWith { throw "Unable to detect local farm" } - It "return null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Be $null } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "throws an exception in the set method to say there is no local farm" { + It "Should throw an exception in the set method to say there is no local farm" { { Set-TargetResource @testParams } | Should throw "No local SharePoint farm was detected" } } - Context "The Web Application isn't available" { - Mock Get-SPWebApplication -MockWith { return $null + Context -Name "The Web Application isn't available" -Fixture { + $testParams = @{ + Url = "http://example.contoso.local" + SendUnusedSiteCollectionNotifications = $true + UnusedSiteNotificationPeriod = 90 + AutomaticallyDeleteUnusedSiteCollections = $true + UnusedSiteNotificationsBeforeDeletion = 30 + } + + Mock -CommandName Get-SPWebApplication -MockWith { + return $null } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should be $false } - It "throws an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "Configured web application could not be found" } } - Context "The server is in a farm and the incorrect settings have been applied" { - Mock Get-SPWebApplication -MockWith { + Context -Name "The server is in a farm and the incorrect settings have been applied" -Fixture { + $testParams = @{ + Url = "http://example.contoso.local" + SendUnusedSiteCollectionNotifications = $true + UnusedSiteNotificationPeriod = 90 + AutomaticallyDeleteUnusedSiteCollections = $true + UnusedSiteNotificationsBeforeDeletion = 30 + } + + Mock -CommandName Get-SPWebApplication -MockWith { $returnVal = @{ SendUnusedSiteCollectionNotifications = $false UnusedSiteNotificationPeriod = @{ TotalDays = 45; } AutomaticallyDeleteUnusedSiteCollections = $false UnusedSiteNotificationsBeforeDeletion = 28 } - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCSiteUseUpdated = $true } -PassThru + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod -Name Update -Value { $Global:SPDscSiteUseUpdated = $true } -PassThru return $returnVal } - Mock Get-SPFarm { return @{} } + Mock -CommandName Get-SPFarm -MockWith { return @{} } - It "return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPDSCSiteUseUpdated = $false - It "updates the Site Use and Deletion settings" { + $Global:SPDscSiteUseUpdated = $false + It "Should update the Site Use and Deletion settings" { Set-TargetResource @testParams - $Global:SPDSCSiteUseUpdated | Should Be $true + $Global:SPDscSiteUseUpdated | Should Be $true } } - Context "The server is in a farm and the correct settings have been applied" { - Mock Get-SPWebApplication -MockWith { + Context -Name "The server is in a farm and the correct settings have been applied" -Fixture { + $testParams = @{ + Url = "http://example.contoso.local" + SendUnusedSiteCollectionNotifications = $true + UnusedSiteNotificationPeriod = 90 + AutomaticallyDeleteUnusedSiteCollections = $true + UnusedSiteNotificationsBeforeDeletion = 30 + } + + Mock -CommandName Get-SPWebApplication -MockWith { $returnVal = @{ SendUnusedSiteCollectionNotifications = $true UnusedSiteNotificationPeriod = @{ TotalDays = 90; } AutomaticallyDeleteUnusedSiteCollections = $true UnusedSiteNotificationsBeforeDeletion = 30 } - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCSiteUseUpdated = $true } -PassThru + $returnVal = $returnVal | Add-Member -MemberType ScriptMethod -Name Update -Value { $Global:SPDscSiteUseUpdated = $true } -PassThru return $returnVal } - Mock Get-SPFarm { return @{} } + Mock -CommandName Get-SPFarm -MockWith { return @{} } - It "return values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppThrottlingSettings.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppThrottlingSettings.Tests.ps1 index 5fcaeb924..81229518c 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppThrottlingSettings.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppThrottlingSettings.Tests.ps1 @@ -1,53 +1,57 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPWebAppThrottlingSettings" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPWebAppThrottlingSettings - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Url = "http://sites.sharepoint.com" - ListViewThreshold = 1000 - AllowObjectModelOverride = $true - AdminThreshold = 2000 - ListViewLookupThreshold = 12 - HappyHourEnabled = $true - HappyHour = (New-CimInstance -ClassName MSFT_SPWebApplicationHappyHour -Property @{ - Hour = 2 - Minute = 0 - Duration = 1 - } -ClientOnly) - UniquePermissionThreshold = 100 - RequestThrottling = $true - ChangeLogEnabled = $true - ChangeLogExpiryDays = 30 - EventHandlersEnabled = $true - } - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPWebAppThrottlingSettings" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Initialize tests + + # Mocks for all contexts + Mock -CommandName New-SPAuthenticationProvider -MockWith { } + Mock -CommandName New-SPWebApplication -MockWith { } + Mock -CommandName Get-SPAuthenticationProvider -MockWith { + return @{ + DisableKerberos = $true + AllowAnonymous = $false + } } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock New-SPAuthenticationProvider { } - Mock New-SPWebApplication { } - Mock Get-SPAuthenticationProvider { return @{ DisableKerberos = $true; AllowAnonymous = $false } } - - Context "The web appliation exists and has the correct throttling settings" { - Mock Get-SPWebApplication { return @(@{ + + # Test contexts + Context -Name "The web appliation exists and has the correct throttling settings" -Fixture { + $testParams = @{ + Url = "http://sites.sharepoint.com" + ListViewThreshold = 1000 + AllowObjectModelOverride = $true + AdminThreshold = 2000 + ListViewLookupThreshold = 12 + HappyHourEnabled = $true + HappyHour = (New-CimInstance -ClassName MSFT_SPWebApplicationHappyHour -Property @{ + Hour = 2 + Minute = 0 + Duration = 1 + } -ClientOnly) + UniquePermissionThreshold = 100 + RequestThrottling = $true + ChangeLogEnabled = $true + ChangeLogExpiryDays = 30 + EventHandlersEnabled = $true + } + + Mock -CommandName Get-SPWebapplication -MockWith { return @(@{ DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool @@ -82,17 +86,36 @@ Describe "SPWebAppThrottlingSettings - SharePoint Build $((Get-Item $SharePointC EventHandlersEnabled = $testParams.EventHandlersEnabled })} - It "returns the current data from the get method" { + It "Should return the current data from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The web appliation exists and uses incorrect throttling settings" { - Mock Get-SPWebApplication { + Context -Name "The web appliation exists and uses incorrect throttling settings" -Fixture { + $testParams = @{ + Url = "http://sites.sharepoint.com" + ListViewThreshold = 1000 + AllowObjectModelOverride = $true + AdminThreshold = 2000 + ListViewLookupThreshold = 12 + HappyHourEnabled = $true + HappyHour = (New-CimInstance -ClassName MSFT_SPWebApplicationHappyHour -Property @{ + Hour = 2 + Minute = 0 + Duration = 1 + } -ClientOnly) + UniquePermissionThreshold = 100 + RequestThrottling = $true + ChangeLogEnabled = $true + ChangeLogExpiryDays = 30 + EventHandlersEnabled = $true + } + + Mock -CommandName Get-SPWebapplication -MockWith { $webApp = @{ DisplayName = $testParams.Name ApplicationPool = @{ @@ -127,27 +150,27 @@ Describe "SPWebAppThrottlingSettings - SharePoint Build $((Get-Item $SharePointC } EventHandlersEnabled = $testParams.EventHandlersEnabled } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true - } -PassThru | Add-Member ScriptMethod SetDailyUnthrottledPrivilegedOperationWindow { - $Global:SPWebApplicationUpdateHappyHourCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value { + $Global:SPDscWebApplicationUpdateCalled = $true + } -PassThru | Add-Member -MemberType ScriptMethod SetDailyUnthrottledPrivilegedOperationWindow { + $Global:SPDscWebApplicationUpdateHappyHourCalled = $true } -PassThru return @($webApp) } - It "returns the current data from the get method" { + It "Should return the current data from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false - $Global:SPWebApplicationUpdateHappyHourCalled = $false - It "updates the throttling settings" { + $Global:SPDscWebApplicationUpdateCalled = $false + $Global:SPDscWebApplicationUpdateHappyHourCalled = $false + It "Should update the throttling settings" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true } $testParams = @{ @@ -168,15 +191,15 @@ Describe "SPWebAppThrottlingSettings - SharePoint Build $((Get-Item $SharePointC ChangeLogExpiryDays = 30 EventHandlersEnabled = $true } - $Global:SPWebApplicationUpdateCalled = $false - $Global:SPWebApplicationUpdateHappyHourCalled = $false - It "updates the incorrect happy hour settings" { + $Global:SPDscWebApplicationUpdateCalled = $false + $Global:SPDscWebApplicationUpdateHappyHourCalled = $false + It "Should update the incorrect happy hour settings" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateCalled | Should Be $true - $Global:SPWebApplicationUpdateHappyHourCalled | Should Be $true + $Global:SPDscWebApplicationUpdateCalled | Should Be $true + $Global:SPDscWebApplicationUpdateHappyHourCalled | Should Be $true } - it "throws exceptions where invalid happy hour settings are provided" { + It "Should throw exceptions where invalid happy hour settings are provided" { $testParams = @{ Name = "SharePoint Sites" ApplicationPool = "SharePoint Web Apps" @@ -229,5 +252,7 @@ Describe "SPWebAppThrottlingSettings - SharePoint Build $((Get-Item $SharePointC { Set-TargetResource @testParams } | Should throw } } - } -} \ No newline at end of file + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppWorkflowSettings.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppWorkflowSettings.Tests.ps1 index 70ac702da..316e52e83 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppWorkflowSettings.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebAppWorkflowSettings.Tests.ps1 @@ -1,41 +1,45 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPWebAppWorkflowSettings" -$ModuleName = "MSFT_SPWebAppWorkflowSettings" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPWebAppWorkflowSettings - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Url = "http://sites.sharepoint.com" - ExternalWorkflowParticipantsEnabled = $true - UserDefinedWorkflowsEnabled = $true - EmailToNoPermissionWorkflowParticipantsEnable = $true - } - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope + # Initialize tests + + # Mocks for all contexts + Mock -CommandName New-SPAuthenticationProvider -MockWith { } + Mock -CommandName New-SPWebApplication -MockWith { } + Mock -CommandName Get-SPAuthenticationProvider -MockWith { + return @{ + DisableKerberos = $true + AllowAnonymous = $false + } } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock New-SPAuthenticationProvider { } - Mock New-SPWebApplication { } - Mock Get-SPAuthenticationProvider { return @{ DisableKerberos = $true; AllowAnonymous = $false } } - Context "The web appliation exists and has the correct workflow settings" { - Mock Get-SPWebApplication { return @(@{ + # Test contexts + Context -Name "The web appliation exists and has the correct workflow settings" -Fixture { + $testParams = @{ + Url = "http://sites.sharepoint.com" + ExternalWorkflowParticipantsEnabled = $true + UserDefinedWorkflowsEnabled = $true + EmailToNoPermissionWorkflowParticipantsEnable = $true + } + + Mock -CommandName Get-SPWebapplication -MockWith { return @(@{ DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool @@ -56,17 +60,24 @@ Describe "SPWebAppWorkflowSettings - SharePoint Build $((Get-Item $SharePointCmd ExternalWorkflowParticipantsEnabled = $true })} - It "returns the current data from the get method" { + It "Should return the current data from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - Context "The web appliation exists and uses incorrect workflow settings" { - Mock Get-SPWebApplication { + Context -Name "The web appliation exists and uses incorrect workflow settings" -Fixture { + $testParams = @{ + Url = "http://sites.sharepoint.com" + ExternalWorkflowParticipantsEnabled = $true + UserDefinedWorkflowsEnabled = $true + EmailToNoPermissionWorkflowParticipantsEnable = $true + } + + Mock -CommandName Get-SPWebapplication -MockWith { $webApp = @{ DisplayName = $testParams.Name ApplicationPool = @{ @@ -87,28 +98,28 @@ Describe "SPWebAppWorkflowSettings - SharePoint Build $((Get-Item $SharePointCmd EmailToNoPermissionWorkflowParticipantsEnabled = $false ExternalWorkflowParticipantsEnabled = $false } - $webApp = $webApp | Add-Member ScriptMethod Update { - $Global:SPWebApplicationUpdateCalled = $true - } -PassThru | Add-Member ScriptMethod UpdateWorkflowConfigurationSettings { - $Global:SPWebApplicationUpdateWorkflowCalled = $true + $webApp = $webApp | Add-Member -MemberType ScriptMethod -Name Update -Value {} -PassThru | + Add-Member -MemberType ScriptMethod -Name UpdateWorkflowConfigurationSettings -Value { + $Global:SPDscWebApplicationUpdateWorkflowCalled = $true } -PassThru return @($webApp) } - It "returns the current data from the get method" { + It "Should return the current data from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - $Global:SPWebApplicationUpdateCalled = $false - $Global:SPWebApplicationUpdateWorkflowCalled = $false - It "updates the workflow settings" { + $Global:SPDscWebApplicationUpdateWorkflowCalled = $false + It "Should update the workflow settings" { Set-TargetResource @testParams - $Global:SPWebApplicationUpdateWorkflowCalled | Should Be $true + $Global:SPDscWebApplicationUpdateWorkflowCalled | Should Be $true } } - } -} \ No newline at end of file + } +} + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebApplication.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebApplication.Tests.ps1 index fe847c244..0da1f0d2e 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebApplication.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebApplication.Tests.ps1 @@ -1,48 +1,47 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPWebApplication" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\Modules\SharePointDsc.Util\SharePointDsc.Util.psm1") -Force - -Describe "SPWebApplication - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "SharePoint Sites" - ApplicationPool = "SharePoint Web Apps" - ApplicationPoolAccount = "DEMO\ServiceAccount" - Url = "http://sites.sharepoint.com" - AuthenticationMethod = "NTLM" - Ensure = "Present" - } - - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) - Mock New-SPAuthenticationProvider { } - Mock New-SPWebApplication { } - Mock Remove-SPWebApplication { } +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPWebApplication" - Context "The specified Managed Account does not exist" { - Mock Get-SPWebApplication { return $null } - Mock Get-SPDSCContentService { +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Initialize tests + + # Mocks for all contexts + Mock -CommandName New-SPAuthenticationProvider -MockWith { } + Mock -CommandName New-SPWebApplication -MockWith { } + Mock -CommandName Remove-SPWebApplication -MockWith { } + Mock -CommandName Get-SPManagedAccount -MockWith {} + + # Test contexts + Context -Name "The specified Managed Account does not exist" -Fixture { + $testParams = @{ + Name = "SharePoint Sites" + ApplicationPool = "SharePoint Web Apps" + ApplicationPoolAccount = "DEMO\ServiceAccount" + Url = "http://sites.sharepoint.com" + AuthenticationMethod = "NTLM" + Ensure = "Present" + } + + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + Mock -CommandName Get-SPDSCContentService -MockWith { return @{ Name = "PlaceHolder" } } - Mock Get-SPManagedAccount { + Mock -CommandName Get-SPManagedAccount -MockWith { Throw "No matching accounts were found" } @@ -51,76 +50,94 @@ Describe "SPWebApplication - SharePoint Build $((Get-Item $SharePointCmdletModul } } - Context "The web application that uses NTLM doesn't exist but should" { - Mock Get-SPWebApplication { return $null } - Mock Get-SPDSCContentService { + Context -Name "The web application that uses NTLM doesn't exist but should" -Fixture { + $testParams = @{ + Name = "SharePoint Sites" + ApplicationPool = "SharePoint Web Apps" + ApplicationPoolAccount = "DEMO\ServiceAccount" + Url = "http://sites.sharepoint.com" + AuthenticationMethod = "NTLM" + Ensure = "Present" + } + + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + Mock -CommandName Get-SPDSCContentService -MockWith { return @{ Name = "PlaceHolder" } } - Mock Get-SPManagedAccount {} - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "calls the new cmdlet from the set method" { - Set-TargetResource @testParams - - Assert-MockCalled New-SPWebApplication - Assert-MockCalled New-SPAuthenticationProvider -ParameterFilter { $DisableKerberos -eq $true } - } - - $testParams.Add("InstallAccount", (New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)))) - It "calls the new cmdlet from the set method where InstallAccount is used" { + It "Should call the new cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPWebApplication Assert-MockCalled New-SPAuthenticationProvider -ParameterFilter { $DisableKerberos -eq $true } } - $testParams.Remove("InstallAccount") $testParams.Add("AllowAnonymous", $true) - It "calls the new cmdlet from the set where anonymous authentication is requested" { + It "Should call the new cmdlet from the set where anonymous authentication is requested" { Set-TargetResource @testParams Assert-MockCalled New-SPWebApplication Assert-MockCalled New-SPAuthenticationProvider -ParameterFilter { $DisableKerberos -eq $true } } - $testParams.Remove("AllowAnonymous") } - $testParams.AuthenticationMethod = "Kerberos" + Context -Name "The web application that uses Kerberos doesn't exist but should" -Fixture { + $testParams = @{ + Name = "SharePoint Sites" + ApplicationPool = "SharePoint Web Apps" + ApplicationPoolAccount = "DEMO\ServiceAccount" + Url = "http://sites.sharepoint.com" + AuthenticationMethod = "Kerberos" + Ensure = "Present" + } - Context "The web application that uses Kerberos doesn't exist but should" { - Mock Get-SPWebApplication { return $null } - Mock Get-SPDSCContentService { + Mock -CommandName Get-SPWebapplication -MockWith { return $null } + Mock -CommandName Get-SPDSCContentService -MockWith { return @{ Name = "PlaceHolder" } } - Mock Get-SPManagedAccount {} + Mock -CommandName Get-SPManagedAccount -MockWith {} - It "returns absent from the get method" { + It "Should return absent from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "calls the new cmdlet from the set method" { + It "Should call the new cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPWebApplication } } - $testParams.AuthenticationMethod = "NTLM" + Context -Name "The web appliation does exist and should that uses NTLM" -Fixture { + $testParams = @{ + Name = "SharePoint Sites" + ApplicationPool = "SharePoint Web Apps" + ApplicationPoolAccount = "DEMO\ServiceAccount" + Url = "http://sites.sharepoint.com" + AuthenticationMethod = "NTLM" + Ensure = "Present" + } - Context "The web appliation does exist and should that uses NTLM" { - Mock Get-SPAuthenticationProvider { return @{ DisableKerberos = $true; AllowAnonymous = $false } } - Mock Get-SPWebApplication { return @(@{ + Mock -CommandName Get-SPAuthenticationProvider -MockWith { + return @{ + DisableKerberos = $true + AllowAnonymous = $false + } + } + + Mock -CommandName Get-SPWebapplication -MockWith { return @(@{ DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool @@ -138,20 +155,33 @@ Describe "SPWebApplication - SharePoint Build $((Get-Item $SharePointCmdletModul Url = $testParams.Url })} - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - $testParams.AuthenticationMethod = "Kerberos" + Context -Name "The web appliation does exist and should that uses Kerberos" -Fixture { + $testParams = @{ + Name = "SharePoint Sites" + ApplicationPool = "SharePoint Web Apps" + ApplicationPoolAccount = "DEMO\ServiceAccount" + Url = "http://sites.sharepoint.com" + AuthenticationMethod = "Kerberos" + Ensure = "Present" + } - Context "The web appliation does exist and should that uses Kerberos" { - Mock Get-SPAuthenticationProvider { return @{ DisableKerberos = $false; AllowAnonymous = $false } } - Mock Get-SPWebApplication { return @(@{ + Mock -CommandName Get-SPAuthenticationProvider -MockWith { + return @{ + DisableKerberos = $false + AllowAnonymous = $false + } + } + + Mock -CommandName Get-SPWebapplication -MockWith { return @(@{ DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool @@ -169,27 +199,33 @@ Describe "SPWebApplication - SharePoint Build $((Get-Item $SharePointCmdletModul Url = $testParams.Url })} - It "returns present from the get method" { + It "Should return present from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true from the test method" { + It "Should return true from the test method" { Test-TargetResource @testParams | Should Be $true } } - $testParams = @{ - Name = "SharePoint Sites" - ApplicationPool = "SharePoint Web Apps" - ApplicationPoolAccount = "DEMO\ServiceAccount" - Url = "http://sites.sharepoint.com" - AuthenticationMethod = "NTLM" - Ensure = "Absent" - } - - Context "A web application exists but shouldn't" { - Mock Get-SPAuthenticationProvider { return @{ DisableKerberos = $true; AllowAnonymous = $false } } - Mock Get-SPWebApplication { return @(@{ + Context -Name "A web application exists but shouldn't" -Fixture { + $testParams = @{ + Name = "SharePoint Sites" + ApplicationPool = "SharePoint Web Apps" + ApplicationPoolAccount = "DEMO\ServiceAccount" + Url = "http://sites.sharepoint.com" + AuthenticationMethod = "NTLM" + Ensure = "Absent" + } + + Mock -CommandName Get-SPAuthenticationProvider -MockWith { + return @{ + DisableKerberos = $true + AllowAnonymous = $false + } + } + + Mock -CommandName Get-SPWebapplication -MockWith { return @(@{ DisplayName = $testParams.Name ApplicationPool = @{ Name = $testParams.ApplicationPool @@ -207,30 +243,41 @@ Describe "SPWebApplication - SharePoint Build $((Get-Item $SharePointCmdletModul Url = $testParams.Url })} - It "returns present from the Get method" { + It "Should return present from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "should remove the web application in the set method" { + It "Should remove the web application in the set method" { Set-TargetResource @testParams Assert-MockCalled Remove-SPWebApplication } } - Context "A web application doesn't exist and shouldn't" { - Mock Get-SPWebApplication { return $null } + Context -Name "A web application doesn't exist and shouldn't" -Fixture { + $testParams = @{ + Name = "SharePoint Sites" + ApplicationPool = "SharePoint Web Apps" + ApplicationPoolAccount = "DEMO\ServiceAccount" + Url = "http://sites.sharepoint.com" + AuthenticationMethod = "NTLM" + Ensure = "Absent" + } + + Mock -CommandName Get-SPWebapplication -MockWith { return $null } - It "returns absent from the Get method" { + It "Should return absent from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - } + } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebApplicationAppDomain.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebApplicationAppDomain.Tests.ps1 index 1bc4d0804..b42d7861d 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPWebApplicationAppDomain.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPWebApplicationAppDomain.Tests.ps1 @@ -1,58 +1,66 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPWebApplicationAppDomain" -$ModuleName = "MSFT_SPWebApplicationAppDomain" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPWebApplicationAppDomain - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - AppDomain = "contosointranetapps.com" - WebApplication ="http://portal.contoso.com" - Zone = "Default" - Port = 80; - SSL = $false - } + # Initialize tests - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - Mock New-SPWebApplicationAppDomain { } - Mock Remove-SPWebApplicationAppDomain { } - Mock Start-Sleep { } + # Mocks for all contexts + Mock -CommandName New-SPWebApplicationAppDomain -MockWith { } + Mock -CommandName Remove-SPWebApplicationAppDomain -MockWith { } + Mock -CommandName Start-Sleep -MockWith { } + + # Test contexts + Context -Name "No app domain settings have been configured for the specified web app and zone" -Fixture { + $testParams = @{ + AppDomain = "contosointranetapps.com" + WebApplication ="http://portal.contoso.com" + Zone = "Default" + Port = 80; + SSL = $false + } - Context "No app domain settings have been configured for the specified web app and zone" { - Mock Get-SPWebApplicationAppDomain { return $null } + Mock -CommandName Get-SPWebApplicationAppDomain -MockWith { return $null } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "creates the new app domain entry" { + It "Should create the new app domain entry" { Set-TargetResource @testParams Assert-MockCalled New-SPWebApplicationAppDomain } } - Context "An app domain has been configured for the specified web app and zone but it's not correct" { - Mock Get-SPWebApplicationAppDomain { + Context -Name "An app domain has been configured for the specified web app and zone but it's not correct" -Fixture { + $testParams = @{ + AppDomain = "contosointranetapps.com" + WebApplication ="http://portal.contoso.com" + Zone = "Default" + Port = 80; + SSL = $false + } + + Mock -CommandName Get-SPWebApplicationAppDomain -MockWith { return @{ AppDomain = "wrong.domain" UrlZone = $testParams.Zone @@ -61,23 +69,31 @@ Describe "SPWebApplicationAppDomain - SharePoint Build $((Get-Item $SharePointCm } } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "creates the new app domain entry" { + It "Should create the new app domain entry" { Set-TargetResource @testParams Assert-MockCalled Remove-SPWebApplicationAppDomain Assert-MockCalled New-SPWebApplicationAppDomain } } - Context "The correct app domain has been configued for the requested web app and zone" { - Mock Get-SPWebApplicationAppDomain { + Context -Name "The correct app domain has been configued for the requested web app and zone" -Fixture { + $testParams = @{ + AppDomain = "contosointranetapps.com" + WebApplication ="http://portal.contoso.com" + Zone = "Default" + Port = 80; + SSL = $false + } + + Mock -CommandName Get-SPWebApplicationAppDomain -MockWith { return @{ AppDomain = $testParams.AppDomain UrlZone = $testParams.Zone @@ -86,23 +102,23 @@ Describe "SPWebApplicationAppDomain - SharePoint Build $((Get-Item $SharePointCm } } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $true } } - $testParams = @{ - AppDomain = "contosointranetapps.com" - WebApplication ="http://portal.contoso.com" - Zone = "Default" - } + Context -Name "The functions operate without optional parameters included" -Fixture { + $testParams = @{ + AppDomain = "contosointranetapps.com" + WebApplication ="http://portal.contoso.com" + Zone = "Default" + } - Context "The functions operate without optional parameters included" { - Mock Get-SPWebApplicationAppDomain { + Mock -CommandName Get-SPWebApplicationAppDomain -MockWith { return @{ AppDomain = "invalid.domain" UrlZone = $testParams.Zone @@ -111,21 +127,21 @@ Describe "SPWebApplicationAppDomain - SharePoint Build $((Get-Item $SharePointCm } } - It "returns null from the get method" { + It "Should return null from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns false from the test method" { + It "Should return false from the test method" { Test-TargetResource @testParams | Should Be $false } - It "creates the new app domain entry" { + It "Should create the new app domain entry" { Set-TargetResource @testParams Assert-MockCalled Remove-SPWebApplicationAppDomain Assert-MockCalled New-SPWebApplicationAppDomain } } - } + } } - +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPWordAutomationServiceApp.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPWordAutomationServiceApp.Tests.ps1 index 33ec81f39..fe579b570 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPWordAutomationServiceApp.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPWordAutomationServiceApp.Tests.ps1 @@ -1,52 +1,62 @@ -[CmdletBinding()] -param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) -) - -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPWordAutomationServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPWordAutomationServiceApp - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Word Automation Service Application" - Ensure = "Present" - ApplicationPool = "SharePoint Web Services" - DatabaseName = "WordAutomation_DB" - DatabaseServer = "SQLServer" - SupportedFileFormats = "docx", "doc", "mht", "rtf", "xml" - DisableEmbeddedFonts = $false - MaximumMemoryUsage = 100 - RecycleThreshold = 100 - DisableBinaryFileScan = $false - ConversionProcesses = 8 - JobConversionFrequency = 15 - NumberOfConversionsPerProcess = 12 - TimeBeforeConversionIsMonitored = 5 - MaximumConversionAttempts = 2 - MaximumSyncConversionRequests = 25 - KeepAliveTimeout = 30 - MaximumConversionTime = 300 - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Context "When no service applications exist in the current farm and Ensure is set to Present" { +[CmdletBinding()] +param( + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) +) + +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) + +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPWordAutomationServiceApp" + +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope + + # Initialize tests + $getTypeFullName = "Microsoft.Office.Word.Server.Service.WordServiceApplication" + + # Mocks for all contexts + Mock -CommandName Remove-SPServiceApplication -MockWith {} + Mock -CommandName Set-SPWordConversionServiceApplication -MockWith {} + Mock -CommandName Set-SPTimerJob {} + + # Test contexts + Context -Name "When no service applications exist in the current farm and Ensure is set to Present" -Fixture { + $testParams = @{ + Name = "Word Automation Service Application" + Ensure = "Present" + ApplicationPool = "SharePoint Web Services" + DatabaseName = "WordAutomation_DB" + DatabaseServer = "SQLServer" + SupportedFileFormats = "docx", "doc", "mht", "rtf", "xml" + DisableEmbeddedFonts = $false + MaximumMemoryUsage = 100 + RecycleThreshold = 100 + DisableBinaryFileScan = $false + ConversionProcesses = 8 + JobConversionFrequency = 15 + NumberOfConversionsPerProcess = 12 + TimeBeforeConversionIsMonitored = 5 + MaximumConversionAttempts = 2 + MaximumSyncConversionRequests = 25 + KeepAliveTimeout = 30 + MaximumConversionTime = 300 + } - Mock Get-SPServiceApplication { return $null } - Mock New-SPWordConversionServiceApplication { + Mock -CommandName Get-SPServiceApplication -MockWith { return $null } + Mock -CommandName Get-SPServiceApplicationPool -MockWith { + return @(@{ + Name = $testParams.ApplicationPool + }) + } + + Mock -CommandName New-SPWordConversionServiceApplication -MockWith { $returnval = @(@{ WordServiceFormats = @{ OpenXmlDocument = $false @@ -68,65 +78,120 @@ Describe "SPWordAutomationServiceApp - SharePoint Build $((Get-Item $SharePointC KeepAliveTimeout = 30 MaximumConversionTime = 300 }) - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCSiteUseUpdated = $true } -PassThru return $returnval - } - Mock Get-SPServiceApplicationPool { - return @(@{ - Name = $testParams.ApplicationPool - }) - } - - Mock Get-SPTimerJob { - $returnval = @(@{ Name = "Just a name" }) - return ,$returnval } - Mock Set-SPTimerJob {} - It "returns null from the Get method" { - Get-TargetResource @testParams | Should BeNullOrEmpty - Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.Name } + It "Should return absent from the Get method" { + (Get-TargetResource @testParams).Ensure | Should Be "absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - $Global:SPDSCSiteUseUpdated = $false - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPWordConversionServiceApplication - $Global:SPDSCSiteUseUpdated | Should Be $true - } - } + } + } - Context "When no service applications exist in the current farm and Ensure is set to Present, but the Application Pool does not exist" { - Mock Get-SPServiceApplication { return $null } - Mock Get-SPServiceApplicationPool { return $null } + Context -Name "When no service applications exist in the current farm and Ensure is set to Present, but the Application Pool does not exist" -Fixture { + $testParams = @{ + Name = "Word Automation Service Application" + Ensure = "Present" + ApplicationPool = "SharePoint Web Services" + DatabaseName = "WordAutomation_DB" + DatabaseServer = "SQLServer" + SupportedFileFormats = "docx", "doc", "mht", "rtf", "xml" + DisableEmbeddedFonts = $false + MaximumMemoryUsage = 100 + RecycleThreshold = 100 + DisableBinaryFileScan = $false + ConversionProcesses = 8 + JobConversionFrequency = 15 + NumberOfConversionsPerProcess = 12 + TimeBeforeConversionIsMonitored = 5 + MaximumConversionAttempts = 2 + MaximumSyncConversionRequests = 25 + KeepAliveTimeout = 30 + MaximumConversionTime = 300 + } + + Mock -CommandName Get-SPServiceApplication -MockWith { return $null } + Mock -CommandName Get-SPServiceApplicationPool -MockWith { return $null } It "fails to create a new service application in the set method because the specified application pool is missing" { { Set-TargetResource @testParams } | Should throw "Specified application pool does not exist" } } - Context "When service applications exist in the current farm but the specific word automation app does not" { - - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Some other service app type" - }) } + Context -Name "When service applications exist in the current farm but the specific word automation app does not" -Fixture { + $testParams = @{ + Name = "Word Automation Service Application" + Ensure = "Present" + ApplicationPool = "SharePoint Web Services" + DatabaseName = "WordAutomation_DB" + DatabaseServer = "SQLServer" + SupportedFileFormats = "docx", "doc", "mht", "rtf", "xml" + DisableEmbeddedFonts = $false + MaximumMemoryUsage = 100 + RecycleThreshold = 100 + DisableBinaryFileScan = $false + ConversionProcesses = 8 + JobConversionFrequency = 15 + NumberOfConversionsPerProcess = 12 + TimeBeforeConversionIsMonitored = 5 + MaximumConversionAttempts = 2 + MaximumSyncConversionRequests = 25 + KeepAliveTimeout = 30 + MaximumConversionTime = 300 + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [pscustomobject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = "Microsoft.Office.UnKnownWebServiceApplication" } + } -PassThru -Force + return $spServiceApp + } + + It "Should return absent from the Get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Absent" + } - It "returns null from the Get method" { - Get-TargetResource @testParams | Should BeNullOrEmpty - Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.Name } - } - } + It "Should return false when the Test method is called" { + Test-TargetResource @testParams | Should Be $false + } + } - Context "When a service application exists and is configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ - TypeName = "Word Automation Services" - DisplayName = $testParams.Name - ApplicationPool = @{ Name = $testParams.ApplicationPool } + Context -Name "When a service application exists and is configured correctly" -Fixture { + $testParams = @{ + Name = "Word Automation Service Application" + Ensure = "Present" + ApplicationPool = "SharePoint Web Services" + DatabaseName = "WordAutomation_DB" + DatabaseServer = "SQLServer" + SupportedFileFormats = "docx", "doc", "mht", "rtf", "xml" + DisableEmbeddedFonts = $false + MaximumMemoryUsage = 100 + RecycleThreshold = 100 + DisableBinaryFileScan = $false + ConversionProcesses = 8 + JobConversionFrequency = 15 + NumberOfConversionsPerProcess = 12 + TimeBeforeConversionIsMonitored = 5 + MaximumConversionAttempts = 2 + MaximumSyncConversionRequests = 25 + KeepAliveTimeout = 30 + MaximumConversionTime = 300 + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [pscustomobject]@{ + DisplayName = $testParams.Name + ApplicationPool = @{ Name = $testParams.ApplicationPool } Database = @{ Name = $testParams.DatabaseName Server = @{ Name = $testParams.DatabaseServer } @@ -150,24 +215,52 @@ Describe "SPWordAutomationServiceApp - SharePoint Build $((Get-Item $SharePointC MaximumSyncConversionRequests = 25 KeepAliveTimeout = @{ TotalSeconds = 30 } MaximumConversionTime = @{ TotalSeconds = 300 } - }) - } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } - It "returns values from the get method" { + It "Should return values from the get method" { Get-TargetResource @testParams | Should Not BeNullOrEmpty } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } } - Context "When a service application exists and incorrect application pool is configured" { - Mock Get-SPServiceApplication { - $returnval = @(@{ - TypeName = "Word Automation Services" + Context -Name "When a service application exists and incorrect application pool is configured" -Fixture { + $testParams = @{ + Name = "Word Automation Service Application" + Ensure = "Present" + ApplicationPool = "SharePoint Web Services" + DatabaseName = "WordAutomation_DB" + DatabaseServer = "SQLServer" + SupportedFileFormats = "docx", "doc", "mht", "rtf", "xml" + DisableEmbeddedFonts = $false + MaximumMemoryUsage = 100 + RecycleThreshold = 100 + DisableBinaryFileScan = $false + ConversionProcesses = 8 + JobConversionFrequency = 15 + NumberOfConversionsPerProcess = 12 + TimeBeforeConversionIsMonitored = 5 + MaximumConversionAttempts = 2 + MaximumSyncConversionRequests = 25 + KeepAliveTimeout = 30 + MaximumConversionTime = 300 + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [pscustomobject]@{ DisplayName = $testParams.Name ApplicationPool = @{ Name = "Wrong App Pool Name" } + Database = @{ + Name = $testParams.DatabaseName + Server = @{ Name = $testParams.DatabaseServer } + } WordServiceFormats = @{ OpenXmlDocument = $false Word972003Document = $true @@ -187,39 +280,66 @@ Describe "SPWordAutomationServiceApp - SharePoint Build $((Get-Item $SharePointC MaximumSyncConversionRequests = 25 KeepAliveTimeout = 30 MaximumConversionTime = 300 - }) - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCSiteUseUpdated = $true } -PassThru - return $returnval - } + } + $spServiceApp = $spServiceApp | Add-Member ScriptMethod Update { + $Global:SPDscSiteUseUpdated = $true + } -PassThru + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } - Mock Get-SPServiceApplicationPool { return @{ Name = $testParams.ApplicationPool } } - Mock Set-SPWordConversionServiceApplication {} + Mock -CommandName Get-SPServiceApplicationPool -MockWith { return @{ Name = $testParams.ApplicationPool } } - Mock Get-SPTimerJob { + Mock -CommandName Get-SPTimerJob { $returnval = @(@{ Name = "Just a name" }) return ,$returnval } - Mock Set-SPTimerJob {} - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - $Global:SPDSCSiteUseUpdated = $false - It "calls the update service app cmdlet from the set method" { + $Global:SPDscSiteUseUpdated = $false + It "calls Set-SPWordConversionServiceApplication and update service app cmdlet from the set method" { Set-TargetResource @testParams Assert-MockCalled Get-SPServiceApplicationPool Assert-MockCalled Set-SPWordConversionServiceApplication - $Global:SPDSCSiteUseUpdated | Should Be $true + $Global:SPDscSiteUseUpdated | Should Be $true } } - Context "When a service application exists and incorrect settings are configured" { - Mock Get-SPServiceApplication { - $returnval = @(@{ - TypeName = "Word Automation Services" - DisplayName = $testParams.Name + Context -Name "When a service application exists and incorrect settings are configured" -Fixture { + $testParams = @{ + Name = "Word Automation Service Application" + Ensure = "Present" + ApplicationPool = "SharePoint Web Services" + DatabaseName = "WordAutomation_DB" + DatabaseServer = "SQLServer" + SupportedFileFormats = "docx", "doc", "mht", "rtf", "xml" + DisableEmbeddedFonts = $false + MaximumMemoryUsage = 100 + RecycleThreshold = 100 + DisableBinaryFileScan = $false + ConversionProcesses = 8 + JobConversionFrequency = 15 + NumberOfConversionsPerProcess = 12 + TimeBeforeConversionIsMonitored = 5 + MaximumConversionAttempts = 2 + MaximumSyncConversionRequests = 25 + KeepAliveTimeout = 30 + MaximumConversionTime = 300 + } + + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [pscustomobject]@{ + DisplayName = $testParams.Name + Database = @{ + Name = $testParams.DatabaseName + Server = @{ Name = $testParams.DatabaseServer } + } ApplicationPool = @{ Name = $testParams.ApplicationPool } WordServiceFormats = @{ OpenXmlDocument = $false @@ -240,118 +360,145 @@ Describe "SPWordAutomationServiceApp - SharePoint Build $((Get-Item $SharePointC MaximumSyncConversionRequests = 25 KeepAliveTimeout = 30 MaximumConversionTime = 300 - }) - $returnVal = $returnVal | Add-Member ScriptMethod Update { $Global:SPDSCSiteUseUpdated = $true } -PassThru - return $returnval - } - - Mock Get-SPServiceApplicationPool { return @{ Name = $testParams.ApplicationPool } } - Mock Set-SPWordConversionServiceApplication {} + } + $spServiceApp = $spServiceApp | Add-Member ScriptMethod Update { + $Global:SPDscSiteUseUpdated = $true + } -PassThru + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } - Mock Get-SPTimerJob { + Mock -CommandName Get-SPServiceApplicationPool { return @{ Name = $testParams.ApplicationPool } } + Mock -CommandName Get-SPTimerJob { $returnval = @(@{ Name = "Just a name" }) return ,$returnval } - Mock Set-SPTimerJob {} - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - $Global:SPDSCSiteUseUpdated = $false - It "calls the update service app cmdlet from the set method" { + $Global:SPDscSiteUseUpdated = $false + It "Should call the update service app cmdlet from the set method" { Set-TargetResource @testParams - Assert-MockCalled Get-SPServiceApplication - $Global:SPDSCSiteUseUpdated | Should Be $true + Assert-MockCalled Get-SPServiceApplication + $Global:SPDscSiteUseUpdated | Should Be $true } } - Context "When no service application exists and Ensure is set to Absent" { + Context -Name "When no service application exists and Ensure is set to Absent" -Fixture { $testParams = @{ Name = "Word Automation Service Application" Ensure = "Absent" } - Mock Get-SPServiceApplication { return $null } + Mock -CommandName Get-SPServiceApplication -MockWith { return $null } - It "returns values from the get method" { - Get-TargetResource @testParams | Should Not BeNullOrEmpty - Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.Name } - } + It "Should return absent from the Get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Absent" + } - It "returns true when the Test method is called" { + It "Should return true when the Test method is called" { Test-TargetResource @testParams | Should Be $true } - } + } - Context "When a service application exists and Ensure is set to Absent" { + Context -Name "When a service application exists and Ensure is set to Absent" -Fixture { $testParams = @{ Name = "Word Automation Service Application" Ensure = "Absent" } - Mock Get-SPServiceApplication { - return @(@{ - TypeName = "Word Automation Services" - DisplayName = $testParams.Name - }) - } - Mock Remove-SPServiceApplication { } - - It "should return null from the get method" { - Get-TargetResource @testParams | Should BeNullOrEmpty - Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.Name } - } + Mock -CommandName Get-SPServiceApplication -MockWith { + $spServiceApp = [pscustomobject]@{ + DisplayName = $testParams.Name + ApplicationPool = @{ Name = $testParams.ApplicationPool } + Database = @{ + Name = $testParams.DatabaseName + Server = @{ Name = $testParams.DatabaseServer } + } + WordServiceFormats = @{ + OpenXmlDocument = $true + Word972003Document = $true + RichTextFormat = $true + WebPage = $true + Word2003Xml = $true + } + DisableEmbeddedFonts = $false + MaximumMemoryUsage = 100 + RecycleProcessThreshold = 100 + DisableBinaryFileScan = $false + TotalActiveProcesses = 8 + TimerJobFrequency = @{ TotalMinutes = 15 } + ConversionsPerInstance = 12 + ConversionTimeout = @{ TotalMinutes = 5 } + MaximumConversionAttempts = 2 + MaximumSyncConversionRequests = 25 + KeepAliveTimeout = @{ TotalSeconds = 30 } + MaximumConversionTime = @{ TotalSeconds = 300 } + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp + } - It "should return false when the Test method is called" { - Test-TargetResource @testParams | Should Be $false + It "Should return present from the Get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Present" + } + + It "Should return true when the Test method is called" { + Test-TargetResource @testParams | Should Be $false } - It "should call the update service app cmdlet from the set method" { - Set-TargetResource @testParams - Assert-MockCalled Remove-SPServiceApplication + It "Should call the remove service application cmdlet in the set method" { + Set-TargetResource @testParams + Assert-MockCalled Remove-SPServiceApplication } } - Context "When Ensure is set to Absent, but another parameter is also used" { + Context -Name "When Ensure is set to Absent, but another parameter is also used" -Fixture { $testParams = @{ Name = "Word Automation Service Application" Ensure = "Absent" ApplicationPool = "SharePoint Web Services" } - It "should return null from the get method" { + It "Should return null from the get method" { { Get-TargetResource @testParams } | Should throw "You cannot use any of the parameters when Ensure is specified as Absent" } - It "should return false from the test method" { + It "Should return false from the test method" { { Test-TargetResource @testParams } | Should throw "You cannot use any of the parameters when Ensure is specified as Absent" } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "You cannot use any of the parameters when Ensure is specified as Absent" } } - Context "When Ensure is set to Present, but the Application Pool or Database parameters are missing" { + Context -Name "When Ensure is set to Present, but the Application Pool or Database parameters are missing" -Fixture { $testParams = @{ Name = "Word Automation Service Application" Ensure = "Present" ApplicationPool = "SharePoint Web Services" } - It "should return null from the get method" { + It "Should return null from the get method" { { Get-TargetResource @testParams } | Should throw "An Application Pool and Database Name are required to configure the Word Automation Service Application" } - It "should return false from the test method" { + It "Should return false from the test method" { { Test-TargetResource @testParams } | Should throw "An Application Pool and Database Name are required to configure the Word Automation Service Application" } - It "should throw an exception in the set method" { + It "Should throw an exception in the set method" { { Set-TargetResource @testParams } | Should throw "An Application Pool and Database Name are required to configure the Word Automation Service Application" } - } + } + } +} - } -} +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPWorkManagementServiceApp.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPWorkManagementServiceApp.Tests.ps1 index 4d798dbfd..48b8715ee 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPWorkManagementServiceApp.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.SPWorkManagementServiceApp.Tests.ps1 @@ -1,125 +1,122 @@ [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -DscResource "SPWorkManagementServiceApp" -$ModuleName = "MSFT_SPWorkManagementServiceApp" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SPWorkManagement - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Test Work Management App" - ApplicationPool = "Test App Pool" - } - $testParamsComplete = @{ - Name = "Test Work Management App" - ApplicationPool = "Test App Pool" - MinimumTimeBetweenEwsSyncSubscriptionSearches =10 - MinimumTimeBetweenProviderRefreshes=10 - MinimumTimeBetweenSearchQueries=10 - NumberOfSubscriptionSyncsPerEwsSyncRun=10 - NumberOfUsersEwsSyncWillProcessAtOnce=10 - NumberOfUsersPerEwsSyncBatch=10 - } + # Initialize tests + $getTypeFullName = "Microsoft.Office.Server.WorkManagement.WorkManagementServiceApplication" - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") + # Mocks for all contexts + Mock -CommandName Remove-SPServiceApplication -MockWith { } + Mock -CommandName New-SPWorkManagementServiceApplication -MockWith { } + Mock -CommandName New-SPWorkManagementServiceApplicationProxy -MockWith { } - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Context "When a service application exists and Ensure equals 'absent'" { - $testParamsAbsent = @{ + # Test contexts + Context -Name "When a service application exists and Ensure equals 'Absent'" -Fixture { + $testParams = @{ Name = "Test Work Management App" Ensure = "Absent" } - Mock Get-SPServiceApplication { - return @(@{ - TypeName = "Work Management Service Application" - DisplayName = $testParamsAbsent.Name + + Mock -CommandName Get-SPServiceApplication { + $spServiceApp = [pscustomobject]@{ + DisplayName = $testParams.Name ApplicationPool = @{ Name = "Wrong App Pool Name" } - }) + } + $spServiceApp = $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - Mock Remove-SPServiceApplication{ } - It "returns true when the Test method is called" { - Test-TargetResource @testParamsAbsent | Should Be $false + It "Should return true when the Test method is called" { + Test-TargetResource @testParams | Should Be $false } - It "calls the remove service app cmdlet from the set method" { - Set-TargetResource @testParamsAbsent + It "Should call the remove service app cmdlet from the set method" { + Set-TargetResource @testParams Assert-MockCalled Remove-SPServiceApplication } } - Context "When no service applications exist in the current farm" { - - Mock Get-SPServiceApplication { return $null } - Mock New-SPWorkManagementServiceApplication { } - Mock Set-SPWorkManagementServiceApplication { } + Context -Name "When no service applications exist in the current farm" -Fixture { + $testParams = @{ + Name = "Test Work Management App" + ApplicationPool = "Test App Pool" + } - Mock New-SPWorkManagementServiceApplicationProxy { } - It "returns null from the Get method" { + Mock -CommandName Get-SPServiceApplication { return $null } + + It "Should return null from the Get method" { (Get-TargetResource @testParams).Ensure | Should Be "Absent" } - It "returns false when the Test method is called" { + It "Should return false when the Test method is called" { Test-TargetResource @testParams | Should Be $false } - It "creates a new service application in the set method" { + It "Should create a new service application in the set method" { Set-TargetResource @testParams Assert-MockCalled New-SPWorkManagementServiceApplication } } - - Context "When service applications exist in the current farm but the specific Work Management app does not" { - Mock Set-SPWorkManagementServiceApplication { } - Mock New-SPWorkManagementServiceApplication { } - Mock New-SPWorkManagementServiceApplicationProxy { } - $Global:GetSpServiceApplicationCalled=$false - Mock Get-SPServiceApplication { - if($Global:GetSpServiceApplicationCalled -eq $false){ - $Global:GetSpServiceApplicationCalled=$true; - return @(@{ - TypeName = "Some other service app type" - }) - } - return @(@{ - TypeName = "Work Management Service Application" - }) + + Context -Name "When service applications exist in the current farm but the specific Work Management app does not" -Fixture { + $testParams = @{ + Name = "Test Work Management App" + ApplicationPool = "Test App Pool" } - - It "returns null from the Get method" { - (Get-TargetResource @testParams).Ensure | Should Be "Absent" + Mock -CommandName Get-SPServiceApplication { + $spServiceApp = [pscustomobject]@{ + DisplayName = $testParams.Name + } + $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = "Microsoft.Office.UnKnownWebServiceApplication" } + } -PassThru -Force + return $spServiceApp } - It "creates new app from the Get method" { - Set-TargetResource @testParams - Assert-MockCalled Get-SPServiceApplication -ParameterFilter { $Name -eq $testParams.Name } - Assert-MockCalled Set-SPWorkManagementServiceApplication -ParameterFilter { $Name -eq $testParams.Name } + It "Should return absent from the Get method" { + (Get-TargetResource @testParams).Ensure | Should Be "Absent" } + It "Should return false when the Test method is called" { + Test-TargetResource @testParams | Should Be $false + } } - Context "When a service application exists and is configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ - TypeName = "Work Management Service Application" - DisplayName = $testParamsComplete.Name - ApplicationPool = @{ Name = $testParamsComplete.ApplicationPool } + Context -Name "When a service application exists and is configured correctly" -Fixture { + $testParams = @{ + Name = "Test Work Management App" + ApplicationPool = "Test App Pool" + MinimumTimeBetweenEwsSyncSubscriptionSearches =10 + MinimumTimeBetweenProviderRefreshes=10 + MinimumTimeBetweenSearchQueries=10 + NumberOfSubscriptionSyncsPerEwsSyncRun=10 + NumberOfUsersEwsSyncWillProcessAtOnce=10 + NumberOfUsersPerEwsSyncBatch=10 + } + + Mock -CommandName Get-SPServiceApplication { + $spServiceApp = [pscustomobject]@{ + DisplayName = $testParams.Name + ApplicationPool = @{ Name = $testParams.ApplicationPool } AdminSettings = @{ MinimumTimeBetweenEwsSyncSubscriptionSearches = (new-timespan -minutes 10) MinimumTimeBetweenProviderRefreshes= (new-timespan -minutes 10) @@ -127,25 +124,37 @@ Describe "SPWorkManagement - SharePoint Build $((Get-Item $SharePointCmdletModul NumberOfSubscriptionSyncsPerEwsSyncRun=10 NumberOfUsersEwsSyncWillProcessAtOnce= 10 NumberOfUsersPerEwsSyncBatch= 10 - } - - }) + } + $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - It "returns values from the get method" { + It "Should return values from the get method" { (Get-TargetResource @testParams).Ensure | Should Be "Present" } - It "returns true when the Test method is called" { - Test-TargetResource @testParamsComplete | Should Be $true + It "Should return true when the Test method is called" { + Test-TargetResource @testParams | Should Be $true } } - Context "When a service application exists and is not configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ - TypeName = "Work Management Service Application" + Context -Name "When a service application exists and is not configured correctly" -Fixture { + $testParams = @{ + Name = "Test Work Management App" + ApplicationPool = "Test App Pool" + MinimumTimeBetweenEwsSyncSubscriptionSearches =10 + MinimumTimeBetweenProviderRefreshes=10 + MinimumTimeBetweenSearchQueries=10 + NumberOfSubscriptionSyncsPerEwsSyncRun=10 + NumberOfUsersEwsSyncWillProcessAtOnce=10 + NumberOfUsersPerEwsSyncBatch=10 + } + + Mock -CommandName Get-SPServiceApplication { + $spServiceApp = [pscustomobject]@{ DisplayName = $testParams.Name ApplicationPool = @{ Name = "Wrong App Pool Name" } AdminSettings = @{ @@ -155,23 +164,26 @@ Describe "SPWorkManagement - SharePoint Build $((Get-Item $SharePointCmdletModul NumberOfSubscriptionSyncsPerEwsSyncRun=10 NumberOfUsersEwsSyncWillProcessAtOnce= 10 NumberOfUsersPerEwsSyncBatch= 10 - } - - }) + } + $spServiceApp | Add-Member -MemberType ScriptMethod -Name GetType -Value { + return @{ FullName = $getTypeFullName } + } -PassThru -Force + return $spServiceApp } - Mock Set-SPWorkManagementServiceApplication { } + Mock -CommandName Set-SPWorkManagementServiceApplication { } - It "returns false when the Test method is called" { - Test-TargetResource @testParamsComplete | Should Be $false + It "Should return false when the Test method is called" { + Test-TargetResource @testParams | Should Be $false } - It "calls the update service app cmdlet from the set method" { - Set-TargetResource @testParamsComplete + It "Should call the update service app cmdlet from the set method" { + Set-TargetResource @testParams Assert-MockCalled Set-SPWorkManagementServiceApplication Assert-MockCalled Get-SPServiceApplication } } - } } + +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.SPusageApplication.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.SPusageApplication.Tests.ps1 deleted file mode 100644 index 25988b909..000000000 --- a/Tests/Unit/SharePointDsc/SharePointDsc.SPusageApplication.Tests.ps1 +++ /dev/null @@ -1,246 +0,0 @@ -[CmdletBinding()] -param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) -) - -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest - -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path -$Global:CurrentSharePointStubModule = $SharePointCmdletModule - -$ModuleName = "MSFT_SPUsageApplication" -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\DSCResources\$ModuleName\$ModuleName.psm1") -Force - -Describe "SPUsageApplication - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - InModuleScope $ModuleName { - $testParams = @{ - Name = "Usage Service App" - UsageLogCutTime = 60 - UsageLogLocation = "L:\UsageLogs" - UsageLogMaxFileSizeKB = 1024 - UsageLogMaxSpaceGB = 10 - DatabaseName = "SP_Usage" - DatabaseServer = "sql.test.domain" - FailoverDatabaseServer = "anothersql.test.domain" - Ensure = "Present" - } - Import-Module (Join-Path ((Resolve-Path $PSScriptRoot\..\..\..).Path) "Modules\SharePointDsc") - - Mock Invoke-SPDSCCommand { - return Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments -NoNewScope - } - - Remove-Module -Name "Microsoft.SharePoint.PowerShell" -Force -ErrorAction SilentlyContinue - Import-Module $Global:CurrentSharePointStubModule -WarningAction SilentlyContinue - - Mock New-SPUsageApplication { } - Mock Set-SPUsageService { } - Mock Get-SPUsageService { return @{ - UsageLogCutTime = $testParams.UsageLogCutTime - UsageLogDir = $testParams.UsageLogLocation - UsageLogMaxFileSize = ($testParams.UsageLogMaxFileSizeKB * 1024) - UsageLogMaxSpaceGB = $testParams.UsageLogMaxSpaceGB - }} - Mock Remove-SPServiceApplication - Mock Get-SPServiceApplicationProxy { - return (New-Object Object | Add-Member ScriptMethod Provision {} -PassThru | Add-Member -NotePropertyName Status -NotePropertyValue "Online" -PassThru | Add-Member -NotePropertyName TypeName -NotePropertyValue "Usage and Health Data Collection Proxy" -PassThru) - } - - Context "When no service applications exist in the current farm" { - - Mock Get-SPServiceApplication { return $null } - - It "returns null from the Get method" { - (Get-TargetResource @testParams).Ensure | Should Be "Absent" - } - - It "returns false when the Test method is called" { - Test-TargetResource @testParams | Should Be $false - } - - It "creates a new service application in the set method" { - Set-TargetResource @testParams - Assert-MockCalled New-SPUsageApplication - } - - It "creates a new service application with custom database credentials" { - $testParams.Add("DatabaseCredentials", (New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)))) - Set-TargetResource @testParams - Assert-MockCalled New-SPUsageApplication - } - } - - Context "When service applications exist in the current farm but not the specific usage service app" { - - Mock Get-SPServiceApplication { return @(@{ - TypeName = "Some other service app type" - }) } - - It "returns absent from the Get method" { - (Get-TargetResource @testParams).Ensure | Should Be "Absent" - } - - It "returns false when the Test method is called" { - Test-TargetResource @testParams | Should Be $false - } - } - - Context "When a service application exists and is configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ - TypeName = "Usage and Health Data Collection Service Application" - DisplayName = $testParams.Name - UsageDatabase = @{ - Name = $testParams.DatabaseName - Server = @{ Name = $testParams.DatabaseServer } - } - }) - } - - It "returns values from the get method" { - (Get-TargetResource @testParams).Ensure | Should Be "Present" - } - - It "returns true when the Test method is called" { - Test-TargetResource @testParams | Should Be $true - } - } - - Context "When a service application exists and log path are not configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ - TypeName = "Usage and Health Data Collection Service Application" - DisplayName = $testParams.Name - UsageDatabase = @{ - Name = $testParams.DatabaseName - Server = @{ Name = $testParams.DatabaseServer } - } - }) - } - Mock Get-SPUsageService { return @{ - UsageLogCutTime = $testParams.UsageLogCutTime - UsageLogDir = "C:\Wrong\Location" - UsageLogMaxFileSize = ($testParams.UsageLogMaxFileSizeKB * 1024) - UsageLogMaxSpaceGB = $testParams.UsageLogMaxSpaceGB - }} - - It "returns false when the Test method is called" { - Test-TargetResource @testParams | Should Be $false - } - - It "calls the update service app cmdlet from the set method" { - Set-TargetResource @testParams - - Assert-MockCalled Set-SPUsageService - } - } - - Context "When a service application exists and log size is not configured correctly" { - Mock Get-SPServiceApplication { - return @(@{ - TypeName = "Usage and Health Data Collection Service Application" - DisplayName = $testParams.Name - UsageDatabase = @{ - Name = $testParams.DatabaseName - Server = @{ Name = $testParams.DatabaseServer } - } - }) - } - Mock Get-SPUsageService { return @{ - UsageLogCutTime = $testParams.UsageLogCutTime - UsageLogDir = $testParams.UsageLogLocation - UsageLogMaxFileSize = ($testParams.UsageLogMaxFileSizeKB * 1024) - UsageLogMaxSpaceGB = 1 - }} - - It "returns false when the Test method is called" { - Test-TargetResource @testParams | Should Be $false - } - - It "calls the update service app cmdlet from the set method" { - Set-TargetResource @testParams - - Assert-MockCalled Set-SPUsageService - } - } - - $testParams = @{ - Name = "Test App" - Ensure = "Absent" - } - - Context "When the service app exists but it shouldn't" { - Mock Get-SPServiceApplication { - return @(@{ - TypeName = "Usage and Health Data Collection Service Application" - DisplayName = $testParams.Name - UsageDatabase = @{ - Name = "db" - Server = @{ Name = "server" } - } - }) - } - - It "returns 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 remove the service application in the set method" { - Set-TargetResource @testParams - Assert-MockCalled Remove-SPServiceApplication - } - } - - Context "When the service app doesn't exist and shouldn't" { - Mock Get-SPServiceApplication { return $null } - - It "returns 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 $true - } - } - - $testParams = @{ - Name = "Test App" - Ensure = "Present" - } - - Context "The proxy for the service app is offline when it should be running" { - Mock Get-SPServiceApplication { - return @(@{ - TypeName = "Usage and Health Data Collection Service Application" - DisplayName = $testParams.Name - UsageDatabase = @{ - Name = "db" - Server = @{ Name = "server" } - } - }) - } - Mock Get-SPServiceApplicationProxy { - return (New-Object Object | Add-Member ScriptMethod Provision {$Global:SPDSCUSageAppProxyStarted = $true} -PassThru | Add-Member -NotePropertyName Status -NotePropertyValue "Disabled" -PassThru | Add-Member -NotePropertyName TypeName -NotePropertyValue "Usage and Health Data Collection Proxy" -PassThru) - } - $Global:SPDSCUSageAppProxyStarted = $false - - 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 start the proxy in the set method" { - Set-TargetResource @testParams - $Global:SPDSCUSageAppProxyStarted | Should Be $true - } - } - } -} diff --git a/Tests/Unit/SharePointDsc/SharePointDsc.Util.Tests.ps1 b/Tests/Unit/SharePointDsc/SharePointDsc.Util.Tests.ps1 index 976e34427..d467dcfdd 100644 --- a/Tests/Unit/SharePointDsc/SharePointDsc.Util.Tests.ps1 +++ b/Tests/Unit/SharePointDsc/SharePointDsc.Util.Tests.ps1 @@ -1,104 +1,159 @@ +# Ignoring this because we need to generate a stub credential to run the tests here +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] [CmdletBinding()] param( - [string] $SharePointCmdletModule = (Join-Path $PSScriptRoot "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" -Resolve) + [Parameter(Mandatory = $false)] + [string] + $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" ` + -Resolve) ) -$ErrorActionPreference = 'stop' -Set-StrictMode -Version latest +Import-Module -Name (Join-Path -Path $PSScriptRoot ` + -ChildPath "..\SharePointDsc.TestHarness.psm1" ` + -Resolve) -$RepoRoot = (Resolve-Path $PSScriptRoot\..\..\..).Path +$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule ` + -SubModulePath "Modules\SharePointDsc.Util\SharePointDsc.Util.psm1" ` + -ExcludeInvokeHelper -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc") -Force -Import-Module (Join-Path $RepoRoot "Modules\SharePointDsc\Modules\SharePointDsc.Util\SharePointDsc.Util.psm1") -Force +Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope -Describe "SharePointDsc.Util - SharePoint Build $((Get-Item $SharePointCmdletModule).Directory.BaseName)" { - Context "Validate Get-SPDSCAssemblyVersion" { - It "returns the version number of a given executable" { - Get-SPDSCAssemblyVersion -PathToAssembly "C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe" | Should Not Be 0 + Context -Name "Validate Get-SPDSCAssemblyVersion" -Fixture { + It "Should return the version number of a given executable" { + $testPath = "C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe" + Get-SPDSCAssemblyVersion -PathToAssembly $testPath | Should Not Be 0 + } } - } - - Context "Validate Invoke-SPDSCCommand" { - Mock Invoke-Command { return $null } -ModuleName "SharePointDsc.Util" - Mock New-PSSession { return $null } -ModuleName "SharePointDsc.Util" - Mock Get-PSSnapin { return $null } -ModuleName "SharePointDsc.Util" - Mock Add-PSSnapin { return $null } -ModuleName "SharePointDsc.Util" - - It "executes a command as the local run as user" { - Invoke-SPDSCCommand -ScriptBlock { return "value" } - } - - It "executes a command as the local run as user with additional arguments" { - Invoke-SPDSCCommand -ScriptBlock { return "value" } -Arguments @{ Something = "42" } - } - - It "executes a command as the specified InstallAccount user where it is different to the current user" { - Invoke-SPDSCCommand -ScriptBlock { return "value" } -Credential (New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force))) - } - - It "throws an exception when the run as user is the same as the InstallAccount user" { - { Invoke-SPDSCCommand -ScriptBlock { return "value" } -Credential (New-Object System.Management.Automation.PSCredential ("$($Env:USERDOMAIN)\$($Env:USERNAME)", (ConvertTo-SecureString "password" -AsPlainText -Force)))} | Should Throw - } - - It "throws normal exceptions when triggered in the script block" { - Mock Invoke-Command { throw [Exception] "A random exception" } -ModuleName "SharePointDsc.Util" - - { Invoke-SPDSCCommand -ScriptBlock { return "value" } } | Should Throw - } - - It "throws normal exceptions when triggered in the script block using InstallAccount" { - Mock Invoke-Command { throw [Exception] "A random exception" } -ModuleName "SharePointDsc.Util" - - { Invoke-SPDSCCommand -ScriptBlock { return "value" } -Credential (New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)))} | Should Throw - } - - It "handles a SharePoint update conflict exception by rebooting the server to retry" { - Mock Invoke-Command { throw [Exception] "An update conflict has occurred, and you must re-try this action." } -ModuleName "SharePointDsc.Util" - { Invoke-SPDSCCommand -ScriptBlock { return "value" } } | Should Not Throw + Context -Name "Validate Invoke-SPDSCCommand" -Fixture { + + Mock -CommandName Invoke-Command -MockWith { + return $null + } + Mock -CommandName New-PSSession -MockWith { + return $null + } + Mock -CommandName Get-PSSnapin -MockWith { + return $null + } + Mock -CommandName Add-PSSnapin -MockWith { + return $null + } + + # The use of the '4>&1' operator is used to hide the verbose output from the + # Invoke-SPDSCCommand command in these tests as it is not necessary to Validate + # the output of the tests. + + It "Should execute a command as the local run as user" { + Invoke-SPDSCCommand -ScriptBlock { return "value" } 4>&1 + } + + It "Should execute a command as the local run as user with additional arguments" { + Invoke-SPDSCCommand -ScriptBlock { return "value" } ` + -Arguments @{ Something = "42" } 4>&1 + } + + It "Should execute a command as the specified InstallAccount user where it is different to the current user" { + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential ("username", $mockPassword) + Invoke-SPDSCCommand -ScriptBlock { return "value" } ` + -Credential $mockCredential 4>&1 + } + + It "Should throw an exception when the run as user is the same as the InstallAccount user" { + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential ("$($Env:USERDOMAIN)\$($Env:USERNAME)", $mockPassword) + { Invoke-SPDSCCommand -ScriptBlock { return "value" } ` + -Credential $mockCredential 4>&1 } | Should Throw + } + + It "Should throw normal exceptions when triggered in the script block" { + Mock -CommandName Invoke-Command -MockWith { + throw [Exception] "A random exception" + } + + { Invoke-SPDSCCommand -ScriptBlock { return "value" } 4>&1 } | Should Throw + } + + It "Should throw normal exceptions when triggered in the script block using InstallAccount" { + Mock -CommandName Invoke-Command -MockWith { + throw [Exception] "A random exception" + } + + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential ("username", $mockPassword) + { Invoke-SPDSCCommand -ScriptBlock { return "value" } ` + -Credential $mockCredential 4>&1 } | Should Throw + } + + It "Should handle a SharePoint update conflict exception by rebooting the server to retry" { + Mock -CommandName Invoke-Command -MockWith { + throw [Exception] "An update conflict has occurred, and you must re-try this action." + } + + { Invoke-SPDSCCommand -ScriptBlock { return "value" } 4>&1 } | Should Not Throw + } + + It "Should handle a SharePoint update conflict exception by rebooting the server to retry using InstallAccount" { + Mock -CommandName Invoke-Command -MockWith { + throw [Exception] "An update conflict has occurred, and you must re-try this action." + } + + $mockPassword = ConvertTo-SecureString -String "password" -AsPlainText -Force + $mockCredential = New-Object -TypeName System.Management.Automation.PSCredential ("username", $mockPassword) + { Invoke-SPDSCCommand -ScriptBlock { return "value" } ` + -Credential $mockCredential 4>&1 } | Should Not Throw + } } - It "handles a SharePoint update conflict exception by rebooting the server to retry using InstallAccount" { - Mock Invoke-Command { throw [Exception] "An update conflict has occurred, and you must re-try this action." } -ModuleName "SharePointDsc.Util" - - { Invoke-SPDSCCommand -ScriptBlock { return "value" } -Credential (New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString "password" -AsPlainText -Force)))} | Should Not Throw + Context -Name "Validate Test-SPDscParameterState" -Fixture { + It "Should return true for two identical tables" { + $desired = @{ Example = "test" } + Test-SPDscParameterState -CurrentValues $desired ` + -DesiredValues $desired | Should Be $true + } + + It "Should return false when a value is different" { + $current = @{ Example = "something" } + $desired = @{ Example = "test" } + Test-SPDscParameterState -CurrentValues $current ` + -DesiredValues $desired | Should Be $false + } + + It "Should return false when a value is missing" { + $current = @{ } + $desired = @{ Example = "test" } + Test-SPDscParameterState -CurrentValues $current ` + -DesiredValues $desired | Should Be $false + } + + It "Should return true when only a specified value matches, but other non-listed values do not" { + $current = @{ Example = "test"; SecondExample = "true" } + $desired = @{ Example = "test"; SecondExample = "false" } + Test-SPDscParameterState -CurrentValues $current ` + -DesiredValues $desired ` + -ValuesToCheck @("Example") | Should Be $true + } + + It "Should return false when only specified values do not match, but other non-listed values do " { + $current = @{ Example = "test"; SecondExample = "true" } + $desired = @{ Example = "test"; SecondExample = "false" } + Test-SPDscParameterState -CurrentValues $current ` + -DesiredValues $desired ` + -ValuesToCheck @("SecondExample") | Should Be $false + } + + It "Should return false when an empty array is used in the current values" { + $current = @{ } + $desired = @{ Example = "test"; SecondExample = "false" } + Test-SPDscParameterState -CurrentValues $current ` + -DesiredValues $desired | Should Be $false + } } } +} - Context "Validate Test-SPDscParameterState" { - It "Returns true for two identical tables" { - $desired = @{ Example = "test" } - Test-SPDscParameterState -CurrentValues $desired -DesiredValues $desired | Should Be $true - } - - It "Returns false when a value is different" { - $current = @{ Example = "something" } - $desired = @{ Example = "test" } - Test-SPDscParameterState -CurrentValues $current -DesiredValues $desired | Should Be $false - } - - It "Returns false when a value is missing" { - $current = @{ } - $desired = @{ Example = "test" } - Test-SPDscParameterState -CurrentValues $current -DesiredValues $desired | Should Be $false - } - - It "Returns true when only a specified value matches, but other non-listed values do not" { - $current = @{ Example = "test"; SecondExample = "true" } - $desired = @{ Example = "test"; SecondExample = "false" } - Test-SPDscParameterState -CurrentValues $current -DesiredValues $desired -ValuesToCheck @("Example") | Should Be $true - } - - It "Returns false when only specified values do not match, but other non-listed values do " { - $current = @{ Example = "test"; SecondExample = "true" } - $desired = @{ Example = "test"; SecondExample = "false" } - Test-SPDscParameterState -CurrentValues $current -DesiredValues $desired -ValuesToCheck @("SecondExample") | Should Be $false - } - - It "Returns false when an empty array is used in the current values" { - $current = @{ } - $desired = @{ Example = "test"; SecondExample = "false" } - Test-SPDscParameterState -CurrentValues $current -DesiredValues $desired | Should Be $false - } - } -} \ No newline at end of file +Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope diff --git a/appveyor.yml b/appveyor.yml index 06a104cb8..179a0ba74 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,58 +1,18 @@ -version: 1.3.0.{build} +version: 1.4.0.{build} image: WMF 5 install: - appveyor DownloadFile https://dist.nuget.org/win-x86-commandline/latest/nuget.exe - ps: | - Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force - Install-Module Pester -Force - Copy-item -Path "$env:APPVEYOR_BUILD_FOLDER\Modules\SharePointDsc" -Destination 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\SharePointDsc' -Recurse - git clone -q https://github.com/PowerShell/DscResource.Tests "$env:APPVEYOR_BUILD_FOLDER\Modules\SharePointDsc\DscResource.Tests" - git clone -q https://github.com/PowerShell/DscResources "$env:APPVEYOR_BUILD_FOLDER\DscResources" - Import-Module "$env:APPVEYOR_BUILD_FOLDER\Modules\SharePointDsc\DscResource.Tests\TestHelper.psm1" -force + Import-Module "$env:APPVEYOR_BUILD_FOLDER\.appveyor\appveyor.psm1" + Start-AppveyorInstallTask - build: off test_script: - ps: | - $testResultsFile = ".\TestsResults.xml" - $testCoverageFiles = @() - Import-Module "$env:APPVEYOR_BUILD_FOLDER\Tests\Unit\SharePointDsc.TestHarness.psm1" - $res = Invoke-SPDscUnitTestSuite -testResultsFile $testResultsFile -DscTestsPath "$env:APPVEYOR_BUILD_FOLDER\Modules\SharePointDsc\DscResource.Tests" - (New-Object 'System.Net.WebClient').UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path $testResultsFile)) - if ($res.FailedCount -gt 0) { - throw "$($res.FailedCount) tests failed." - } + Start-AppveyorTestScriptTask after_test: - ps: | - Move-Item "$env:APPVEYOR_BUILD_FOLDER\Modules\SharePointDsc\DscResource.Tests" "$env:APPVEYOR_BUILD_FOLDER\" - Import-Module "$env:APPVEYOR_BUILD_FOLDER\DscResource.Tests\TestHelper.psm1" -force - New-Item "$env:APPVEYOR_BUILD_FOLDER\modules\SharePointDsc\en-US" -ItemType Directory - Import-Module "$env:APPVEYOR_BUILD_FOLDER\DscResources\DscResource.DocumentationHelper" - Write-DscResourcePowerShellHelp -OutputPath "$env:APPVEYOR_BUILD_FOLDER\modules\SharePointDsc\en-US" -ModulePath "$env:APPVEYOR_BUILD_FOLDER\modules\SharePointDsc" -Verbose - - Add-Type -assemblyname System.IO.Compression.FileSystem - - New-Item "$env:APPVEYOR_BUILD_FOLDER\wikicontent" -ItemType Directory - Write-DscResourceWikiSite -OutputPath "$env:APPVEYOR_BUILD_FOLDER\wikicontent" -ModulePath "$env:APPVEYOR_BUILD_FOLDER\modules\SharePointDsc" -Verbose - $zipFileName = "SharePointDsc_$($env:APPVEYOR_BUILD_VERSION)_wikicontent.zip" - [System.IO.Compression.ZipFile]::CreateFromDirectory("$env:APPVEYOR_BUILD_FOLDER\wikicontent", "$env:APPVEYOR_BUILD_FOLDER\$zipFileName") - Get-ChildItem "$env:APPVEYOR_BUILD_FOLDER\$zipFileName" | % { Push-AppveyorArtifact $_.FullName -FileName $_.Name } - - Get-ChildItem "$env:APPVEYOR_BUILD_FOLDER\Modules\**\readme.md" -Recurse | Remove-Item -Confirm:$false - - $manifest = Join-Path "$env:APPVEYOR_BUILD_FOLDER\modules\SharePointDsc" "SharePointDsc.psd1" - (Get-Content $manifest -Raw).Replace("1.3.0.0", $env:APPVEYOR_BUILD_VERSION) | Out-File $manifest - $zipFileName = "SharePointDsc_$($env:APPVEYOR_BUILD_VERSION).zip" - [System.IO.Compression.ZipFile]::CreateFromDirectory("$env:APPVEYOR_BUILD_FOLDER\modules\SharePointDsc", "$env:APPVEYOR_BUILD_FOLDER\$zipFileName") - New-DscChecksum -Path $env:APPVEYOR_BUILD_FOLDER -Outpath $env:APPVEYOR_BUILD_FOLDER - Get-ChildItem "$env:APPVEYOR_BUILD_FOLDER\$zipFileName" | % { Push-AppveyorArtifact $_.FullName -FileName $_.Name } - Get-ChildItem "$env:APPVEYOR_BUILD_FOLDER\$zipFileName.checksum" | % { Push-AppveyorArtifact $_.FullName -FileName $_.Name } - - cd "$env:APPVEYOR_BUILD_FOLDER\modules\SharePointDsc" - New-Nuspec -packageName "SharePointDsc" -version $env:APPVEYOR_BUILD_VERSION -author "Microsoft" -owners "Microsoft" -licenseUrl "https://github.com/PowerShell/DscResources/blob/master/LICENSE" -projectUrl "https://github.com/$($env:APPVEYOR_REPO_NAME)" -packageDescription "SharePointDsc" -tags "DesiredStateConfiguration DSC DSCResourceKit" -destinationPath . - nuget pack ".\SharePointDsc.nuspec" -outputdirectory $env:APPVEYOR_BUILD_FOLDER - $nuGetPackageName = "SharePointDsc." + $env:APPVEYOR_BUILD_VERSION + ".nupkg" - Get-ChildItem "$env:APPVEYOR_BUILD_FOLDER\$nuGetPackageName" | % { Push-AppveyorArtifact $_.FullName -FileName $_.Name } + Start-AppveyorAfterTestTask