diff --git a/src/code/FindHelper.cs b/src/code/FindHelper.cs index 327d0e024..a3c5c5c35 100644 --- a/src/code/FindHelper.cs +++ b/src/code/FindHelper.cs @@ -105,7 +105,7 @@ public IEnumerable<PSResourceInfo> FindByResourceName( if (repository != null) { // Write error and disregard repository entries containing wildcards. - repository = Utils.ProcessNameWildcards(repository, removeWildcardEntries:false, out string[] errorMsgs, out _repositoryNameContainsWildcard); + repository = Utils.ProcessNameWildcards(repository, removeWildcardEntries: false, out string[] errorMsgs, out _repositoryNameContainsWildcard); foreach (string error in errorMsgs) { _cmdletPassedIn.WriteError(new ErrorRecord( @@ -156,7 +156,7 @@ public IEnumerable<PSResourceInfo> FindByResourceName( if (repositoriesToSearch != null && repositoriesToSearch.Count == 0) { _cmdletPassedIn.ThrowTerminatingError(new ErrorRecord( - new PSArgumentException ("Cannot resolve -Repository name. Run 'Get-PSResourceRepository' to view all registered repositories."), + new PSArgumentException("Cannot resolve -Repository name. Run 'Get-PSResourceRepository' to view all registered repositories."), "RepositoryNameIsNotResolved", ErrorCategory.InvalidArgument, this)); @@ -222,7 +222,8 @@ public IEnumerable<PSResourceInfo> FindByResourceName( bool shouldReportErrorForEachRepo = !suppressErrors && !_repositoryNameContainsWildcard; foreach (PSResourceInfo currentPkg in SearchByNames(currentServer, currentResponseUtil, currentRepository, shouldReportErrorForEachRepo)) { - if (currentPkg == null) { + if (currentPkg == null) + { _cmdletPassedIn.WriteDebug("No packages returned from server"); continue; } @@ -244,7 +245,7 @@ public IEnumerable<PSResourceInfo> FindByResourceName( { // Scenarios: Find-PSResource -Name "pkg" -> write error only if pkg wasn't found in any registered repositories // Scenarios: Find-PSResource -Name "pkg" -Repository *Gallery -> write error if only if pkg wasn't found in any matching repositories. - foreach(string pkgName in pkgsDiscovered) + foreach (string pkgName in pkgsDiscovered) { var msg = repository == null ? $"Package '{pkgName}' could not be found in any registered repositories." : $"Package '{pkgName}' could not be found in registered repositories: '{string.Join(", ", repositoryNamesToSearch)}'."; @@ -256,7 +257,7 @@ public IEnumerable<PSResourceInfo> FindByResourceName( this)); } } -} + } public IEnumerable<PSCommandResourceInfo> FindByCommandOrDscResource( bool isSearchingForCommands, @@ -283,12 +284,12 @@ public IEnumerable<PSCommandResourceInfo> FindByCommandOrDscResource( // Error out if repository array of names to be searched contains wildcards. if (repository != null) { - repository = Utils.ProcessNameWildcards(repository, removeWildcardEntries:false, out string[] errorMsgs, out _repositoryNameContainsWildcard); + repository = Utils.ProcessNameWildcards(repository, removeWildcardEntries: false, out string[] errorMsgs, out _repositoryNameContainsWildcard); if (string.Equals(repository[0], "*")) { _cmdletPassedIn.ThrowTerminatingError(new ErrorRecord( - new PSArgumentException ("-Repository parameter does not support entry '*' with -CommandName and -DSCResourceName parameters."), + new PSArgumentException("-Repository parameter does not support entry '*' with -CommandName and -DSCResourceName parameters."), "RepositoryDoesNotSupportWildcardEntryWithCmdOrDSCName", ErrorCategory.InvalidArgument, this)); @@ -337,7 +338,7 @@ public IEnumerable<PSCommandResourceInfo> FindByCommandOrDscResource( if (repositoriesToSearch != null && repositoriesToSearch.Count == 0) { _cmdletPassedIn.ThrowTerminatingError(new ErrorRecord( - new PSArgumentException ("Cannot resolve -Repository name. Run 'Get-PSResourceRepository' to view all registered repositories."), + new PSArgumentException("Cannot resolve -Repository name. Run 'Get-PSResourceRepository' to view all registered repositories."), "RepositoryNameIsNotResolved", ErrorCategory.InvalidArgument, this)); @@ -487,12 +488,12 @@ public IEnumerable<PSResourceInfo> FindByTag( if (repository != null) { - repository = Utils.ProcessNameWildcards(repository, removeWildcardEntries:false, out string[] errorMsgs, out _repositoryNameContainsWildcard); + repository = Utils.ProcessNameWildcards(repository, removeWildcardEntries: false, out string[] errorMsgs, out _repositoryNameContainsWildcard); if (string.Equals(repository[0], "*")) { _cmdletPassedIn.ThrowTerminatingError(new ErrorRecord( - new PSArgumentException ("-Repository parameter does not support entry '*' with -Tag parameter."), + new PSArgumentException("-Repository parameter does not support entry '*' with -Tag parameter."), "RepositoryDoesNotSupportWildcardEntryWithTag", ErrorCategory.InvalidArgument, this)); @@ -541,7 +542,7 @@ public IEnumerable<PSResourceInfo> FindByTag( if (repositoriesToSearch != null && repositoriesToSearch.Count == 0) { _cmdletPassedIn.ThrowTerminatingError(new ErrorRecord( - new PSArgumentException ("Cannot resolve -Repository name. Run 'Get-PSResourceRepository' to view all registered repositories."), + new PSArgumentException("Cannot resolve -Repository name. Run 'Get-PSResourceRepository' to view all registered repositories."), "RepositoryNameIsNotResolved", ErrorCategory.InvalidArgument, this)); @@ -635,7 +636,7 @@ public IEnumerable<PSResourceInfo> FindByTag( if (currentResult.exception != null && !currentResult.exception.Message.Equals(string.Empty)) { errRecord = new ErrorRecord( - new ResourceNotFoundException($"Tags '{String.Join(", ", _tag)}' could not be found" , currentResult.exception), + new ResourceNotFoundException($"Tags '{String.Join(", ", _tag)}' could not be found", currentResult.exception), "FindTagConvertToPSResourceFailure", ErrorCategory.InvalidResult, this); @@ -729,7 +730,7 @@ private IEnumerable<PSResourceInfo> SearchByNames(ServerApiCall currentServer, R } } } - else if(pkgName.Contains("*")) + else if (pkgName.Contains("*")) { // Example: Find-PSResource -Name "Az*" // Example: Find-PSResource -Name "Az*" -Tag "Storage" @@ -1000,12 +1001,6 @@ private IEnumerable<PSResourceInfo> SearchByNames(ServerApiCall currentServer, R // After retrieving all packages find their dependencies if (_includeDependencies) { - if (currentServer.Repository.ApiVersion == PSRepositoryInfo.APIVersion.V3) - { - _cmdletPassedIn.WriteWarning("Installing dependencies is not currently supported for V3 server protocol repositories. The package will be installed without installing dependencies."); - yield break; - } - foreach (PSResourceInfo currentPkg in parentPkgs) { _cmdletPassedIn.WriteDebug($"Finding dependency packages for '{currentPkg.Name}'"); @@ -1102,7 +1097,8 @@ internal IEnumerable<PSResourceInfo> FindDependencyPackages( { _cmdletPassedIn.WriteVerbose(errRecord.Exception.Message); } - else { + else + { _cmdletPassedIn.WriteError(errRecord); } yield return null; @@ -1164,7 +1160,8 @@ internal IEnumerable<PSResourceInfo> FindDependencyPackages( { _cmdletPassedIn.WriteVerbose(errRecord.Exception.Message); } - else { + else + { _cmdletPassedIn.WriteError(errRecord); } yield return null; @@ -1199,7 +1196,8 @@ internal IEnumerable<PSResourceInfo> FindDependencyPackages( // Check to see if version falls within version range PSResourceInfo foundDep = currentResult.returnedObject; string depVersionStr = $"{foundDep.Version}"; - if (foundDep.IsPrerelease) { + if (foundDep.IsPrerelease) + { depVersionStr += $"-{foundDep.Prerelease}"; } @@ -1222,7 +1220,8 @@ internal IEnumerable<PSResourceInfo> FindDependencyPackages( yield return depRes; } } - else { + else + { List<string> pkgVersions = _packagesFound[depPkg.Name] as List<string>; // _packagesFound has depPkg.name in it, but the version is not the same if (!pkgVersions.Contains(FormatPkgVersionString(depPkg))) diff --git a/src/code/InstallHelper.cs b/src/code/InstallHelper.cs index e31c2b86c..d9d985e9e 100644 --- a/src/code/InstallHelper.cs +++ b/src/code/InstallHelper.cs @@ -187,7 +187,7 @@ private List<PSResourceInfo> ProcessRepositories( if (repository != null && repository.Length != 0) { // Write error and disregard repository entries containing wildcards. - repository = Utils.ProcessNameWildcards(repository, removeWildcardEntries:false, out string[] errorMsgs, out _); + repository = Utils.ProcessNameWildcards(repository, removeWildcardEntries: false, out string[] errorMsgs, out _); foreach (string error in errorMsgs) { _cmdletPassedIn.WriteError(new ErrorRecord( @@ -231,7 +231,7 @@ private List<PSResourceInfo> ProcessRepositories( if (repositoriesToSearch != null && repositoriesToSearch.Count == 0) { _cmdletPassedIn.ThrowTerminatingError(new ErrorRecord( - new PSArgumentException ("Cannot resolve -Repository name. Run 'Get-PSResourceRepository' to view all registered repositories."), + new PSArgumentException("Cannot resolve -Repository name. Run 'Get-PSResourceRepository' to view all registered repositories."), "RepositoryNameIsNotResolved", ErrorCategory.InvalidArgument, _cmdletPassedIn)); @@ -305,7 +305,8 @@ private List<PSResourceInfo> ProcessRepositories( bool installDepsForRepo = skipDependencyCheck; // If no more packages to install, then return - if (_pkgNamesToInstall.Count == 0) { + if (_pkgNamesToInstall.Count == 0) + { return allPkgsInstalled; } @@ -329,14 +330,9 @@ private List<PSResourceInfo> ProcessRepositories( } repositoryNamesToSearch.Add(repoName); - if ((currentRepository.ApiVersion == PSRepositoryInfo.APIVersion.V3) && (!installDepsForRepo)) - { - _cmdletPassedIn.WriteWarning("Installing dependencies is not currently supported for V3 server protocol repositories. The package will be installed without installing dependencies."); - installDepsForRepo = true; - } - var installedPkgs = InstallPackages(_pkgNamesToInstall.ToArray(), currentRepository, currentServer, currentResponseUtil, scope, skipDependencyCheck, findHelper); - foreach (var pkg in installedPkgs) + List<PSResourceInfo> installedPkgs = InstallPackages(_pkgNamesToInstall.ToArray(), currentRepository, currentServer, currentResponseUtil, scope, skipDependencyCheck, findHelper); + foreach (PSResourceInfo pkg in installedPkgs) { _pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase)); } @@ -535,8 +531,10 @@ private void MoveFilesIntoInstallPath( File.Delete(Path.Combine(finalModuleVersionDir, pkgInfo.Name + PSScriptFileExt)); } } - else { - if (_includeXml) { + else + { + if (_includeXml) + { _cmdletPassedIn.WriteVerbose(string.Format("Moving '{0}' to '{1}'", Path.Combine(dirNameVersion, scriptXML), Path.Combine(installPath, scriptXML))); Utils.MoveFiles(Path.Combine(dirNameVersion, scriptXML), Path.Combine(installPath, scriptXML)); } @@ -614,11 +612,6 @@ private List<PSResourceInfo> InstallPackages( if (!skipDependencyCheck) { - if (currentServer.Repository.ApiVersion == PSRepositoryInfo.APIVersion.V3) - { - _cmdletPassedIn.WriteWarning("Installing dependencies is not currently supported for V3 server protocol repositories. The package will be installed without installing dependencies."); - } - // Get the dependencies from the installed package. if (parentPkgObj.Dependencies.Length > 0) { @@ -748,7 +741,7 @@ private Hashtable BeginPackageInstall( return packagesHash; } - break; + break; case VersionType.SpecificVersion: string nugetVersionString = specificVersion.ToNormalizedString(); // 3.0.17-beta @@ -802,7 +795,9 @@ private Hashtable BeginPackageInstall( break; } - } else { + } + else + { pkgToInstall = currentResult.returnedObject; break; @@ -816,11 +811,13 @@ private Hashtable BeginPackageInstall( pkgToInstall.RepositorySourceLocation = repository.Uri.ToString(); pkgToInstall.AdditionalMetadata.TryGetValue("NormalizedVersion", out string pkgVersion); - if (pkgVersion == null) { + if (pkgVersion == null) + { // Not all NuGet providers (e.g. Artifactory, possibly others) send NormalizedVersion in NuGet package responses. // If they don't, we need to manually construct the combined version+prerelease from pkgToInstall.Version and the prerelease string. pkgVersion = pkgToInstall.Version.ToString(); - if (!String.IsNullOrEmpty(pkgToInstall.Prerelease)) { + if (!String.IsNullOrEmpty(pkgToInstall.Prerelease)) + { pkgVersion += $"-{pkgToInstall.Prerelease}"; } } @@ -913,11 +910,11 @@ private string CreateInstallationTempPath() try { var dir = Directory.CreateDirectory(tempInstallPath); // should check it gets created properly - // To delete file attributes from the existing ones get the current file attributes first and use AND (&) operator - // with a mask (bitwise complement of desired attributes combination). - // TODO: check the attributes and if it's read only then set it - // attribute may be inherited from the parent - // TODO: are there Linux accommodations we need to consider here? + // To delete file attributes from the existing ones get the current file attributes first and use AND (&) operator + // with a mask (bitwise complement of desired attributes combination). + // TODO: check the attributes and if it's read only then set it + // attribute may be inherited from the parent + // TODO: are there Linux accommodations we need to consider here? dir.Attributes &= ~FileAttributes.ReadOnly; } catch (Exception e) @@ -995,7 +992,8 @@ private bool TryInstallToTempPath( bool isModule = File.Exists(moduleManifest); bool isScript = File.Exists(scriptPath); - if (!isModule && !isScript) { + if (!isModule && !isScript) + { scriptPath = ""; } @@ -1425,7 +1423,7 @@ private bool CallAcceptLicense(PSResourceInfo p, string moduleManifest, string t "ForceAcceptLicense", ErrorCategory.InvalidArgument, _cmdletPassedIn); - + return false; } } diff --git a/src/code/PSResourceInfo.cs b/src/code/PSResourceInfo.cs index 409665edc..74e482ad3 100644 --- a/src/code/PSResourceInfo.cs +++ b/src/code/PSResourceInfo.cs @@ -1,17 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using Dbg = System.Diagnostics.Debug; +using Microsoft.PowerShell.Commands; using NuGet.Versioning; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; +using System.Linq; using System.Management.Automation; using System.Text.Json; using System.Xml; -using Microsoft.PowerShell.Commands; - -using Dbg = System.Diagnostics.Debug; namespace Microsoft.PowerShell.PSResourceGet.UtilClasses { @@ -82,7 +82,8 @@ public sealed class ResourceIncludes /// <param name="includes">Hashtable of PSGet includes</param> internal ResourceIncludes(Hashtable includes) { - if (includes == null) { return; } + if (includes == null) + { return; } Cmdlet = GetHashTableItem(includes, nameof(Cmdlet)); Command = GetHashTableItem(includes, nameof(Command)); @@ -194,8 +195,8 @@ public sealed class PSCommandResourceInfo /// <param name="parentResource">the parent module resource the command or dsc resource belongs to</param> public PSCommandResourceInfo(string[] names, PSResourceInfo parentResource) { - Names = names; - ParentResource = parentResource; + Names = names; + ParentResource = parentResource; } #endregion @@ -296,7 +297,7 @@ private PSResourceInfo( #region Private fields - private static readonly char[] Delimeter = {' ', ','}; + private static readonly char[] Delimeter = { ' ', ',' }; #endregion @@ -331,7 +332,7 @@ public bool TryWrite( return true; } - catch(Exception ex) + catch (Exception ex) { errorMsg = string.Format( CultureInfo.InvariantCulture, @@ -363,11 +364,11 @@ public static bool TryRead( try { // Read and deserialize information xml file. - var psObjectInfo = (PSObject) PSSerializer.Deserialize( + var psObjectInfo = (PSObject)PSSerializer.Deserialize( System.IO.File.ReadAllText( filePath)); - var additionalMetadata = GetProperty<Dictionary<string,string>>(nameof(PSResourceInfo.AdditionalMetadata), psObjectInfo); + var additionalMetadata = GetProperty<Dictionary<string, string>>(nameof(PSResourceInfo.AdditionalMetadata), psObjectInfo); Version version = GetVersionInfo(psObjectInfo, additionalMetadata, out string prerelease); psGetInfo = new PSResourceInfo( @@ -401,7 +402,7 @@ public static bool TryRead( return true; } - catch(Exception ex) + catch (Exception ex) { errorMsg = string.Format( CultureInfo.InvariantCulture, @@ -486,7 +487,7 @@ public static bool TryConvertFromXml( errorMsg = "TryConvertXmlToPSResourceInfo: Invalid XmlNodeList object. Object cannot be null."; return false; } - + try { Hashtable metadata = new Hashtable(StringComparer.InvariantCultureIgnoreCase); @@ -577,7 +578,8 @@ public static bool TryConvertFromXml( var additionalMetadataHashtable = new Dictionary<string, string>(); // Only add NormalizedVersion to additionalMetadata if server response included it - if (metadata.ContainsKey("NormalizedVersion")) { + if (metadata.ContainsKey("NormalizedVersion")) + { additionalMetadataHashtable.Add("NormalizedVersion", metadata["NormalizedVersion"].ToString()); } @@ -594,10 +596,10 @@ public static bool TryConvertFromXml( includes: includes, installedDate: null, installedLocation: null, - isPrerelease: (bool) metadata["IsPrerelease"], + isPrerelease: (bool)metadata["IsPrerelease"], licenseUri: metadata["LicenseUrl"] as Uri, name: metadata["Id"] as String, - powershellGetFormatVersion: null, + powershellGetFormatVersion: null, prerelease: metadata["Prerelease"] as String, projectUri: metadata["ProjectUrl"] as Uri, publishedDate: metadata["Published"] as DateTime?, @@ -608,7 +610,7 @@ public static bool TryConvertFromXml( type: typeInfo, updatedDate: null, version: metadata["Version"] as Version); - + return true; } catch (Exception ex) @@ -643,7 +645,7 @@ public static bool TryConvertFromJson( try { - Hashtable metadata = new Hashtable(StringComparer.InvariantCultureIgnoreCase); + Hashtable metadata = new(StringComparer.InvariantCultureIgnoreCase); JsonElement rootDom = pkgJson.RootElement; // Version @@ -716,7 +718,38 @@ public static bool TryConvertFromJson( } // Dependencies - // TODO, tracked via: https://github.com/PowerShell/PSResourceGet/issues/1169 + if (rootDom.TryGetProperty("dependencyGroups", out JsonElement dependencyGroupsElement)) + { + List<Dependency> pkgDeps = new(); + foreach ( + JsonElement dependencyGroup in dependencyGroupsElement.EnumerateArray().Where( + x => !string.IsNullOrWhiteSpace(x.GetProperty("@id").GetString()) + ) + ) + { + if (dependencyGroup.TryGetProperty("dependencies", out JsonElement dependenciesElement)) + { + foreach ( + JsonElement dependency in dependenciesElement.EnumerateArray().Where( + x => !string.IsNullOrWhiteSpace(x.GetProperty("@id").GetString()) + ) + ) + { + pkgDeps.Add( + new Dependency( + dependency.GetProperty("id").GetString(), + ( + VersionRange.TryParse(dependency.GetProperty("range").GetString(), out VersionRange versionRange) ? + versionRange : + VersionRange.All + ) + ) + ); + } + } + } + metadata["Dependencies"] = pkgDeps.ToArray(); + } // IsPrerelease // NuGet.org repository's response does contain 'isPrerelease' element so it can be accquired and set here. @@ -753,9 +786,10 @@ public static bool TryConvertFromJson( { metadata["Id"] = idElement.ToString(); } - + // ReleaseNotes - if (rootDom.TryGetProperty("releaseNotes", out JsonElement releaseNotesElement)) { + if (rootDom.TryGetProperty("releaseNotes", out JsonElement releaseNotesElement)) + { metadata["ReleaseNotes"] = releaseNotesElement.ToString(); } @@ -789,9 +823,9 @@ public static bool TryConvertFromJson( type: ResourceType.None, updatedDate: null, version: metadata["Version"] as Version); - + return true; - + } catch (Exception ex) { @@ -799,7 +833,7 @@ public static bool TryConvertFromJson( CultureInfo.InvariantCulture, @"TryConvertFromJson: Cannot parse PSResourceInfo from json object with error: {0}", ex.Message); - + return false; } } @@ -809,12 +843,12 @@ public static bool TryConvertFromJson( /// used for ContainerRegistry Server API call find response conversion to PSResourceInfo object /// </summary> public static bool TryConvertFromContainerRegistryJson( - string packageName, - JsonDocument packageMetadata, - ResourceType? resourceType, - out PSResourceInfo psGetInfo, - PSRepositoryInfo repository, - out string errorMsg) + string packageName, + JsonDocument packageMetadata, + ResourceType? resourceType, + out PSResourceInfo psGetInfo, + PSRepositoryInfo repository, + out string errorMsg) { psGetInfo = null; errorMsg = String.Empty; @@ -845,7 +879,7 @@ public static bool TryConvertFromContainerRegistryJson( metadata["Prerelease"] = prereleaseLabel; metadata["IsPrerelease"] = !String.IsNullOrEmpty(prereleaseLabel); } - else if(rootDom.TryGetProperty("ModuleVersion", out JsonElement moduleVersionElement)) + else if (rootDom.TryGetProperty("ModuleVersion", out JsonElement moduleVersionElement)) { // For modules (i.e with "ModuleVersion" property) it will just contain the numerical part not prerelease label, so we must find that from PrivateData.PSData.Prerelease entry versionValue = moduleVersionElement.ToString(); @@ -991,7 +1025,7 @@ public static bool TryConvertFromContainerRegistryJson( { { "NormalizedVersion", metadata["NormalizedVersion"].ToString() } }; - + psGetInfo = new PSResourceInfo( additionalMetadata: additionalMetadataHashtable, author: metadata["Authors"] as String, @@ -1019,7 +1053,7 @@ public static bool TryConvertFromContainerRegistryJson( version: metadata["Version"] as Version); return true; - + } catch (Exception ex) { @@ -1027,7 +1061,7 @@ public static bool TryConvertFromContainerRegistryJson( CultureInfo.InvariantCulture, @"TryConvertFromContainerRegistryJson: Cannot parse PSResourceInfo from json object with error: {0}", ex.Message); - + return false; } } @@ -1061,7 +1095,7 @@ public static bool TryConvertFromHashtableForPsd1( moduleNameHash.Add("ModuleName", modName); requiredModulesHashList.Add(moduleNameHash); } - } + } } } @@ -1075,7 +1109,7 @@ public static bool TryConvertFromHashtableForPsd1( { nameof(PSResourceInfo.Includes.DscResource), new PSObject(dscResourceNames) } }; - string prereleaseLabel = (string) pkgMetadata["Prerelease"]; + string prereleaseLabel = (string)pkgMetadata["Prerelease"]; bool isPrerelease = !String.IsNullOrEmpty(prereleaseLabel); Uri iconUri = pkgMetadata["IconUri"] as Uri; @@ -1105,7 +1139,7 @@ public static bool TryConvertFromHashtableForPsd1( isPrerelease: isPrerelease, licenseUri: licenseUri, name: pkgMetadata["Id"] as String, - powershellGetFormatVersion: null, + powershellGetFormatVersion: null, prerelease: prereleaseLabel, projectUri: projectUri, publishedDate: null, @@ -1119,7 +1153,7 @@ public static bool TryConvertFromHashtableForPsd1( return true; } - catch(Exception ex) + catch (Exception ex) { errorMsg = string.Format( CultureInfo.InvariantCulture, @@ -1154,13 +1188,13 @@ public static bool TryConvertFromHashtableForPs1( NuGetVersion nugetVersion = pkgMetadata["Version"] as NuGetVersion; bool isPrerelease = nugetVersion.IsPrerelease; Version version = nugetVersion.Version; - string prereleaseLabel = isPrerelease ? nugetVersion.ToNormalizedString().Split(new char[]{'-'})[1] : String.Empty; + string prereleaseLabel = isPrerelease ? nugetVersion.ToNormalizedString().Split(new char[] { '-' })[1] : String.Empty; var additionalMetadataHashtable = new Dictionary<string, string> { { "NormalizedVersion", nugetVersion.ToNormalizedString() } }; - ModuleSpecification[] requiredModules = pkgMetadata.ContainsKey("RequiredModules") ? pkgMetadata["RequiredModules"] as ModuleSpecification[] : new ModuleSpecification[]{}; + ModuleSpecification[] requiredModules = pkgMetadata.ContainsKey("RequiredModules") ? pkgMetadata["RequiredModules"] as ModuleSpecification[] : new ModuleSpecification[] { }; psGetInfo = new PSResourceInfo( additionalMetadata: additionalMetadataHashtable, @@ -1176,7 +1210,7 @@ public static bool TryConvertFromHashtableForPs1( isPrerelease: isPrerelease, licenseUri: pkgMetadata["LicenseUri"] as Uri, name: pkgMetadata["Id"] as String, - powershellGetFormatVersion: null, + powershellGetFormatVersion: null, prerelease: prereleaseLabel, projectUri: pkgMetadata["ProjectUri"] as Uri, publishedDate: null, @@ -1190,7 +1224,7 @@ public static bool TryConvertFromHashtableForPs1( return true; } - catch(Exception ex) + catch (Exception ex) { errorMsg = string.Format( CultureInfo.InvariantCulture, @@ -1250,7 +1284,7 @@ public static bool TryConvertFromHashtableForNuspec( isPrerelease: isPrerelease, licenseUri: licenseUri, name: pkgMetadata["id"] as String, - powershellGetFormatVersion: null, + powershellGetFormatVersion: null, prerelease: prereleaseLabel, projectUri: projectUri, publishedDate: null, @@ -1264,7 +1298,7 @@ public static bool TryConvertFromHashtableForNuspec( return true; } - catch(Exception ex) + catch (Exception ex) { errorMsg = string.Format( CultureInfo.InvariantCulture, @@ -1334,9 +1368,10 @@ private static T GetProperty<T>( private static Dependency[] GetDependencies(ArrayList dependencyInfos) { List<Dependency> dependenciesFound = new List<Dependency>(); - if (dependencyInfos == null) { return dependenciesFound.ToArray(); } + if (dependencyInfos == null) + { return dependenciesFound.ToArray(); } - foreach(PSObject dependencyObj in dependencyInfos) + foreach (PSObject dependencyObj in dependencyInfos) { // The dependency object can be a string or a hashtable // eg: @@ -1489,7 +1524,7 @@ internal static Uri ParseHttpUrl(string uriString) { Uri parsedUri; Uri.TryCreate(uriString, UriKind.Absolute, out parsedUri); - + return parsedUri; } @@ -1503,10 +1538,10 @@ internal static Dependency[] ParseHttpDependencies(string dependencyString) { /* Az.Profile:[0.1.0, ):|Az.Aks:[0.1.0, ):|Az.AnalysisServices:[0.1.0, ): - Post 1st Split: + Post 1st Split: ["Az.Profile:[0.1.0, ):", "Az.Aks:[0.1.0, ):", "Az.AnalysisServices:[0.1.0, ):"] */ - string[] dependencies = dependencyString.Split(new char[]{'|'}, StringSplitOptions.RemoveEmptyEntries); + string[] dependencies = dependencyString.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); List<Dependency> dependencyList = new List<Dependency>(); foreach (string dependency in dependencies) @@ -1515,14 +1550,14 @@ internal static Dependency[] ParseHttpDependencies(string dependencyString) The Element: "Az.Profile:[0.1.0, ):" Post 2nd Split: ["Az.Profile", "[0.1.0, )"] */ - string[] dependencyParts = dependency.Split(new char[]{':'}, StringSplitOptions.RemoveEmptyEntries); + string[] dependencyParts = dependency.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); VersionRange dependencyVersion; if (dependencyParts.Length == 1) { dependencyVersion = VersionRange.All; } - else + else { if (!Utils.TryParseVersionOrVersionRange(dependencyParts[1], out dependencyVersion)) { @@ -1532,7 +1567,7 @@ internal static Dependency[] ParseHttpDependencies(string dependencyString) dependencyList.Add(new Dependency(dependencyParts[0], dependencyVersion)); } - + return dependencyList.ToArray(); } @@ -1620,7 +1655,7 @@ private static ResourceType ParseHttpMetadataType( ResourceType pkgType = ResourceType.Module; foreach (string tag in tags) { - if(String.Equals(tag, "PSScript", StringComparison.InvariantCultureIgnoreCase)) + if (String.Equals(tag, "PSScript", StringComparison.InvariantCultureIgnoreCase)) { // clear default Module tag, because a Script resource cannot be a Module resource also pkgType = ResourceType.Script; @@ -1778,7 +1813,7 @@ private static Dependency[] GetDependenciesForPs1(ModuleSpecification[] required return deps.ToArray(); } - foreach(ModuleSpecification depModule in requiredModules) + foreach (ModuleSpecification depModule in requiredModules) { // ModuleSpecification has Version, RequiredVersion, MaximumVersion string depName = depModule.Name; @@ -1826,7 +1861,7 @@ private static Dependency[] GetDependenciesForPs1(ModuleSpecification[] required private static Dependency[] GetDependenciesForPsd1(Hashtable[] requiredModules) { List<Dependency> deps = new List<Dependency>(); - foreach(Hashtable depModule in requiredModules) + foreach (Hashtable depModule in requiredModules) { VersionRange depVersionRange = VersionRange.All; @@ -1835,18 +1870,18 @@ private static Dependency[] GetDependenciesForPsd1(Hashtable[] requiredModules) continue; } - String depName = (string) depModule["ModuleName"]; + String depName = (string)depModule["ModuleName"]; if (depModule.ContainsKey("RequiredVersion")) { // = 2.5.0 - Utils.TryParseVersionOrVersionRange((string) depModule["RequiredVersion"], out depVersionRange); + Utils.TryParseVersionOrVersionRange((string)depModule["RequiredVersion"], out depVersionRange); } else if (depModule.ContainsKey("ModuleVersion") || depModule.ContainsKey("MaximumVersion")) { if (depModule.ContainsKey("ModuleVersion") && depModule.ContainsKey("MaximumVersion")) { - NuGetVersion.TryParse((string) depModule["ModuleVersion"], out NuGetVersion minVersion); - NuGetVersion.TryParse((string) depModule["MaximumVersion"], out NuGetVersion maxVersion); + NuGetVersion.TryParse((string)depModule["ModuleVersion"], out NuGetVersion minVersion); + NuGetVersion.TryParse((string)depModule["MaximumVersion"], out NuGetVersion maxVersion); depVersionRange = new VersionRange( minVersion: minVersion, includeMinVersion: true, @@ -1855,7 +1890,7 @@ private static Dependency[] GetDependenciesForPsd1(Hashtable[] requiredModules) } else if (depModule.ContainsKey("ModuleVersion")) { - NuGetVersion.TryParse((string) depModule["ModuleVersion"], out NuGetVersion minVersion); + NuGetVersion.TryParse((string)depModule["ModuleVersion"], out NuGetVersion minVersion); depVersionRange = new VersionRange( minVersion: minVersion, includeMinVersion: true, @@ -1865,7 +1900,7 @@ private static Dependency[] GetDependenciesForPsd1(Hashtable[] requiredModules) else { // depModule has "MaximumVersion" key - NuGetVersion.TryParse((string) depModule["MaximumVersion"], out NuGetVersion maxVersion); + NuGetVersion.TryParse((string)depModule["MaximumVersion"], out NuGetVersion maxVersion); depVersionRange = new VersionRange( minVersion: null, includeMinVersion: true, diff --git a/test/FindPSResourceTests/FindPSResourceV3Server.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceV3Server.Tests.ps1 index dc1e46262..18f278002 100644 --- a/test/FindPSResourceTests/FindPSResourceV3Server.Tests.ps1 +++ b/test/FindPSResourceTests/FindPSResourceV3Server.Tests.ps1 @@ -11,7 +11,7 @@ Describe 'Test HTTP Find-PSResource for V3 Server Protocol' -tags 'CI' { BeforeAll{ $NuGetGalleryName = Get-NuGetGalleryName - $testModuleName = "test_module" + $testModuleName = 'test_module' Get-NewPSResourceRepositoryFile } @@ -19,44 +19,45 @@ Describe 'Test HTTP Find-PSResource for V3 Server Protocol' -tags 'CI' { Get-RevertPSResourceRepositoryFile } - It "find resource given specific Name, Version null" { + It 'find resource given specific Name, Version null' { # FindName() $res = Find-PSResource -Name $testModuleName -Repository $NuGetGalleryName $res.Name | Should -Be $testModuleName - $res.Version | Should -Be "5.0.0" + $res.Version | Should -Be '5.0.0' } - It "should not find resource given nonexistant Name" { + It 'should not find resource given nonexistant Name' { $res = Find-PSResource -Name NonExistantModule -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly 'PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource' $res | Should -BeNullOrEmpty } - It "find resource(s) given wildcard Name" { + It 'find resource(s) given wildcard Name' { # FindNameGlobbing - $wildcardName = "test_module*" + $wildcardName = 'test_module*' $res = Find-PSResource -Name $wildcardName -Repository $NuGetGalleryName $res.Count | Should -BeGreaterThan 1 - foreach ($item in $res) - { + foreach ($item in $res) { $item.Name | Should -BeLike $wildcardName } } - $testCases2 = @{Version="[5.0.0.0]"; ExpectedVersions=@("5.0.0"); Reason="validate version, exact match"}, - @{Version="5.0.0.0"; ExpectedVersions=@("5.0.0"); Reason="validate version, exact match without bracket syntax"}, - @{Version="[1.0.0.0, 5.0.0.0]"; ExpectedVersions=@("1.0.0", "3.0.0", "5.0.0"); Reason="validate version, exact range inclusive"}, - @{Version="(1.0.0.0, 5.0.0.0)"; ExpectedVersions=@("3.0.0"); Reason="validate version, exact range exclusive"}, - @{Version="(1.0.0.0,)"; ExpectedVersions=@("3.0.0", "5.0.0"); Reason="validate version, minimum version exclusive"}, - @{Version="[1.0.0.0,)"; ExpectedVersions=@("1.0.0", "3.0.0", "5.0.0"); Reason="validate version, minimum version inclusive"}, - @{Version="(,3.0.0.0)"; ExpectedVersions=@("1.0.0"); Reason="validate version, maximum version exclusive"}, - @{Version="(,3.0.0.0]"; ExpectedVersions=@("1.0.0", "3.0.0"); Reason="validate version, maximum version inclusive"}, - @{Version="[1.0.0.0, 5.0.0.0)"; ExpectedVersions=@("1.0.0", "3.0.0"); Reason="validate version, mixed inclusive minimum and exclusive maximum version"} - @{Version="(1.0.0.0, 5.0.0.0]"; ExpectedVersions=@("3.0.0", "5.0.0"); Reason="validate version, mixed exclusive minimum and inclusive maximum version"} - - It "find resource when given Name to <Reason> <Version>" -TestCases $testCases2{ + $testCases2 = [hashtable[]]( + @{Version='[5.0.0.0]'; ExpectedVersions=@('5.0.0'); Reason='validate version, exact match'}, + @{Version='5.0.0.0'; ExpectedVersions=@('5.0.0'); Reason='validate version, exact match without bracket syntax'}, + @{Version='[1.0.0.0, 5.0.0.0]'; ExpectedVersions=@('1.0.0', '3.0.0', '5.0.0'); Reason='validate version, exact range inclusive'}, + @{Version='(1.0.0.0, 5.0.0.0)'; ExpectedVersions=@('3.0.0'); Reason='validate version, exact range exclusive'}, + @{Version='(1.0.0.0,)'; ExpectedVersions=@('3.0.0', '5.0.0'); Reason='validate version, minimum version exclusive'}, + @{Version='[1.0.0.0,)'; ExpectedVersions=@('1.0.0', '3.0.0', '5.0.0'); Reason='validate version, minimum version inclusive'}, + @{Version='(,3.0.0.0)'; ExpectedVersions=@('1.0.0'); Reason='validate version, maximum version exclusive'}, + @{Version='(,3.0.0.0]'; ExpectedVersions=@('1.0.0', '3.0.0'); Reason='validate version, maximum version inclusive'}, + @{Version='[1.0.0.0, 5.0.0.0)'; ExpectedVersions=@('1.0.0', '3.0.0'); Reason='validate version, mixed inclusive minimum and exclusive maximum version'}, + @{Version='(1.0.0.0, 5.0.0.0]'; ExpectedVersions=@('3.0.0', '5.0.0'); Reason='validate version, mixed exclusive minimum and inclusive maximum version'} + ) + + It 'find resource when given Name to <Reason> <Version>' -TestCases $testCases2{ # FindVersionGlobbing() param($Version, $ExpectedVersions) $res = Find-PSResource -Name $testModuleName -Version $Version -Repository $NuGetGalleryName @@ -69,7 +70,7 @@ Describe 'Test HTTP Find-PSResource for V3 Server Protocol' -tags 'CI' { It "find all versions of resource when given specific Name, Version not null --> '*'" { # FindVersionGlobbing() - $res = Find-PSResource -Name $testModuleName -Version "*" -Repository $NuGetGalleryName + $res = Find-PSResource -Name $testModuleName -Version '*' -Repository $NuGetGalleryName $res | ForEach-Object { $_.Name | Should -Be $testModuleName } @@ -77,29 +78,28 @@ Describe 'Test HTTP Find-PSResource for V3 Server Protocol' -tags 'CI' { $res.Count | Should -BeGreaterOrEqual 1 } - It "find resource with latest (including prerelease) version given Prerelease parameter" { + It 'find resource with latest (including prerelease) version given Prerelease parameter' { # FindName() # test_module resource's latest version is a prerelease version, before that it has a non-prerelease version $res = Find-PSResource -Name $testModuleName -Repository $NuGetGalleryName - $res.Version | Should -Be "5.0.0" + $res.Version | Should -Be '5.0.0' $resPrerelease = Find-PSResource -Name $testModuleName -Prerelease -Repository $NuGetGalleryName - $resPrerelease.Version | Should -Be "5.2.5" - $resPrerelease.Prerelease | Should -Be "alpha001" + $resPrerelease.Version | Should -Be '5.2.5' + $resPrerelease.Prerelease | Should -Be 'alpha001' } - It "find resources, including Prerelease version resources, when given Prerelease parameter" { + It 'find resources, including Prerelease version resources, when given Prerelease parameter' { # FindVersionGlobbing() - $resWithoutPrerelease = Find-PSResource -Name $testModuleName -Version "*" -Repository $NuGetGalleryName - $resWithPrerelease = Find-PSResource -Name $testModuleName -Version "*" -Repository $NuGetGalleryName + $resWithoutPrerelease = Find-PSResource -Name $testModuleName -Version '*' -Repository $NuGetGalleryName + $resWithPrerelease = Find-PSResource -Name $testModuleName -Version '*' -Repository $NuGetGalleryName $resWithPrerelease.Count | Should -BeGreaterOrEqual $resWithoutPrerelease.Count } - It "find resource and its dependency resources with IncludeDependencies parameter" { - # find with dependencies is not yet supported for V3, so this should only install parent package - $pkg = Find-PSResource -Name "TestModuleWithDependencyE" -IncludeDependencies -Repository $NuGetGalleryName - $pkg.Name | Should -Be "TestModuleWithDependencyE" - $pkg | Should -HaveCount 1 + It 'find resource and its dependency resources with IncludeDependencies parameter' { + $pkg = [array](Find-PSResource -Name 'TestModuleWithDependencyE' -IncludeDependencies -Repository $NuGetGalleryName) + $pkg.Name | Should -Contain 'TestModuleWithDependencyE' + $pkg | Should -BeGreaterThan 1 } # It "find resources only with Tag parameter" { @@ -110,118 +110,116 @@ Describe 'Test HTTP Find-PSResource for V3 Server Protocol' -tags 'CI' { # } # } - It "find resource that satisfies given Name and Tag property (single tag)" { + It 'find resource that satisfies given Name and Tag property (single tag)' { # FindNameWithTag() - $requiredTag = "test" + $requiredTag = 'test' $res = Find-PSResource -Name $testModuleName -Tag $requiredTag -Repository $NuGetGalleryName $res.Name | Should -Be $testModuleName $res.Tags | Should -Contain $requiredTag } - It "should not find resource if Name and Tag are not both satisfied (single tag)" { + It 'should not find resource if Name and Tag are not both satisfied (single tag)' { # FindNameWithTag - $requiredTag = "Windows" # tag "windows" is not present for test_module package + $requiredTag = 'Windows' # tag "windows" is not present for test_module package $res = Find-PSResource -Name $testModuleName -Tag $requiredTag -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly 'PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource' } - It "find resource that satisfies given Name and Tag property (multiple tags)" { + It 'find resource that satisfies given Name and Tag property (multiple tags)' { # FindNameWithTag() - $requiredTags = @("test", "Tag2") + $requiredTags = @('test', 'Tag2') $res = Find-PSResource -Name $testModuleName -Tag $requiredTags -Repository $NuGetGalleryName $res.Name | Should -Be $testModuleName $res.Tags | Should -Contain $requiredTags[0] $res.Tags | Should -Contain $requiredTags[1] } - It "should not find resource if Name and Tag are not both satisfied (multiple tag)" { + It 'should not find resource if Name and Tag are not both satisfied (multiple tag)' { # FindNameWithTag - $requiredTags = @("test", "Windows") # tag "windows" is not present for test_module package + $requiredTags = @('test', 'Windows') # tag "windows" is not present for test_module package $res = Find-PSResource -Name $testModuleName -Tag $requiredTags -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly 'PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource' } - It "find all resources that satisfy Name pattern and have specified Tag (single tag)" { + It 'find all resources that satisfy Name pattern and have specified Tag (single tag)' { # FindNameGlobbingWithTag() - $requiredTag = "test" - $nameWithWildcard = "test_module*" + $requiredTag = 'test' + $nameWithWildcard = 'test_module*' $res = Find-PSResource -Name $nameWithWildcard -Tag $requiredTag -Repository $NuGetGalleryName $res.Count | Should -BeGreaterThan 1 - foreach ($pkg in $res) - { + foreach ($pkg in $res) { $pkg.Name | Should -BeLike $nameWithWildcard $pkg.Tags | Should -Contain $requiredTag } } - It "should not find resources if both Name pattern and Tags are not satisfied (single tag)" { + It 'should not find resources if both Name pattern and Tags are not satisfied (single tag)' { # FindNameGlobbingWithTag() - $requiredTag = "windows" # tag "windows" is not present for test_module package - $res = Find-PSResource -Name "test_module*" -Tag $requiredTag -Repository $NuGetGalleryName + $requiredTag = 'windows' # tag "windows" is not present for test_module package + $res = Find-PSResource -Name 'test_module*' -Tag $requiredTag -Repository $NuGetGalleryName $res | Should -BeNullOrEmpty } - It "find all resources that satisfy Name pattern and have specified Tag (multiple tags)" { + It 'find all resources that satisfy Name pattern and have specified Tag (multiple tags)' { # FindNameGlobbingWithTag() - $requiredTags = @("test", "Tag2") - $nameWithWildcard = "test_module*" + $requiredTags = @('test', 'Tag2') + $nameWithWildcard = 'test_module*' $res = Find-PSResource -Name $nameWithWildcard -Tag $requiredTags -Repository $NuGetGalleryName $res.Count | Should -BeGreaterThan 1 - foreach ($pkg in $res) - { + foreach ($pkg in $res) { $pkg.Name | Should -BeLike $nameWithWildcard $pkg.Tags | Should -Contain $requiredTags[0] $pkg.Tags | Should -Contain $requiredTags[1] } } - It "should not find resources if both Name pattern and Tags are not satisfied (multiple tags)" { + It 'should not find resources if both Name pattern and Tags are not satisfied (multiple tags)' { # FindNameGlobbingWithTag() # tag "windows" is not present for test_module package - $requiredTags = @("test", "windows") - $res = Find-PSResource -Name "test_module*" -Tag $requiredTags -Repository $NuGetGalleryName + $requiredTags = @('test', 'windows') + $res = Find-PSResource -Name 'test_module*' -Tag $requiredTags -Repository $NuGetGalleryName $res | Should -BeNullOrEmpty } - It "find resource that satisfies given Name, Version and Tag property (single tag)" { + It 'find resource that satisfies given Name, Version and Tag property (single tag)' { # FindVersionWithTag() - $requiredTag = "test" - $res = Find-PSResource -Name $testModuleName -Version "5.0.0.0" -Tag $requiredTag -Repository $NuGetGalleryName + $requiredTag = 'test' + $res = Find-PSResource -Name $testModuleName -Version '5.0.0.0' -Tag $requiredTag -Repository $NuGetGalleryName $res.Name | Should -Be $testModuleName - $res.Version | Should -Be "5.0.0" + $res.Version | Should -Be '5.0.0' $res.Tags | Should -Contain $requiredTag } - It "should not find resource if Name, Version and Tag property are not all satisfied (single tag)" { + It 'should not find resource if Name, Version and Tag property are not all satisfied (single tag)' { # FindVersionWithTag() - $requiredTag = "windows" # tag "windows" is not present for test_module package - $res = Find-PSResource -Name $testModuleName -Version "5.0.0.0" -Tag $requiredTag -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue + $requiredTag = 'windows' # tag "windows" is not present for test_module package + $res = Find-PSResource -Name $testModuleName -Version '5.0.0.0' -Tag $requiredTag -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly 'PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource' } - It "find resource that satisfies given Name, Version and Tag property (multiple tags)" { + It 'find resource that satisfies given Name, Version and Tag property (multiple tags)' { # FindVersionWithTag() - $requiredTags = @("test", "Tag2") - $res = Find-PSResource -Name $testModuleName -Version "5.0.0.0" -Tag $requiredTags -Repository $NuGetGalleryName + $requiredTags = @('test', 'Tag2') + $res = Find-PSResource -Name $testModuleName -Version '5.0.0.0' -Tag $requiredTags -Repository $NuGetGalleryName $res.Name | Should -Be $testModuleName - $res.Version | Should -Be "5.0.0" + $res.Version | Should -Be '5.0.0' $res.Tags | Should -Contain $requiredTags[0] $res.Tags | Should -Contain $requiredTags[1] } - It "should not find resource if Name, Version and Tag property are not all satisfied (multiple tags)" { + It 'should not find resource if Name, Version and Tag property are not all satisfied (multiple tags)' { # FindVersionWithTag() - $requiredTags = @("test", "windows") - $res = Find-PSResource -Name $testModuleName -Version "5.0.0.0" -Tag $requiredTags -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue + $requiredTags = @('test', 'windows') + $res = Find-PSResource -Name $testModuleName -Version '5.0.0.0' -Tag $requiredTags -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly 'PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource' } # It "find all resources with specified tag given Tag property" { @@ -248,50 +246,50 @@ Describe 'Test HTTP Find-PSResource for V3 Server Protocol' -tags 'CI' { # $foundTestScript | Should -Be $True # } - It "should not find resource given CommandName" { - $res = Find-PSResource -CommandName "command" -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue + It 'should not find resource given CommandName' { + $res = Find-PSResource -CommandName 'command' -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "FindCommandOrDscResourceFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly 'FindCommandOrDscResourceFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource' } - It "should not find resource given DscResourceName" { - $res = Find-PSResource -DscResourceName "dscResource" -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue + It 'should not find resource given DscResourceName' { + $res = Find-PSResource -DscResourceName 'dscResource' -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "FindCommandOrDscResourceFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly 'FindCommandOrDscResourceFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource' } It "should not find all resources given Name '*'" { - $res = Find-PSResource -Name "*" -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -Name '*' -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "FindAllFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly 'FindAllFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource' } - It "should not find an unlisted module" { - $res = Find-PSResource -Name "PMTestDependency1" -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue + It 'should not find an unlisted module' { + $res = Find-PSResource -Name 'PMTestDependency1' -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly 'PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource' } - + # "carb*" is intentionally chosen as a sequence that will trigger pagination (ie more than 100 results), # but is not too time consuming. # There are currently between 236 packages that should be returned It "Should find more than 100 packages that contain 'carb*' in the name" { # Tests pagination - $res = Find-PSResource -Name "carb*" -Repository $NuGetGalleryName + $res = Find-PSResource -Name 'carb*' -Repository $NuGetGalleryName $res | Should -Not -BeNullOrEmpty $res.Count | Should -BeGreaterOrEqual 236 } - It "should throw unauthorized exception if private repository with no credentials" { - Register-PSResourceRepository -Name "PrivateGallery" -Uri "https://gitlab.com/api/v4/projects/47456554/packages/nuget/index.json" - $res = Find-PSResource -Name $testModuleName -Repository "PrivateGallery" -ErrorVariable err -ErrorAction SilentlyContinue - Unregister-PSResourceRepository -Name "PrivateGallery" + It 'should throw unauthorized exception if private repository with no credentials' { + Register-PSResourceRepository -Name 'PrivateGallery' -Uri 'https://gitlab.com/api/v4/projects/47456554/packages/nuget/index.json' + $res = Find-PSResource -Name $testModuleName -Repository 'PrivateGallery' -ErrorVariable err -ErrorAction SilentlyContinue + Unregister-PSResourceRepository -Name 'PrivateGallery' $res | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "UnauthorizedRequest,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly 'UnauthorizedRequest,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource' } } diff --git a/test/InstallPSResourceTests/InstallPSResourceV3Server.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceV3Server.Tests.ps1 index 3e4f82823..c3934c100 100644 --- a/test/InstallPSResourceTests/InstallPSResourceV3Server.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceV3Server.Tests.ps1 @@ -4,7 +4,7 @@ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] Param() -$ProgressPreference = "SilentlyContinue" +$ProgressPreference = 'SilentlyContinue' $modPath = "$psscriptroot/../PSGetTestUtils.psm1" Import-Module $modPath -Force -Verbose @@ -16,29 +16,31 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { BeforeAll { $NuGetGalleryName = Get-NuGetGalleryName $NuGetGalleryUri = Get-NuGetGalleryLocation - $testModuleName = "test_module" - $testModuleName2 = "test_module2" - $testScriptName = "test_script" - $PackageManagement = "PackageManagement" - $RequiredResourceJSONFileName = "TestRequiredResourceFile.json" - $RequiredResourcePSD1FileName = "TestRequiredResourceFile.psd1" + $testModuleName = 'test_module' + $testModuleName2 = 'test_module2' + $testScriptName = 'test_script' + $PackageManagement = 'PackageManagement' + $RequiredResourceJSONFileName = 'TestRequiredResourceFile.json' + $RequiredResourcePSD1FileName = 'TestRequiredResourceFile.psd1' Get-NewPSResourceRepositoryFile Register-LocalRepos } AfterEach { - Uninstall-PSResource "test_module", "test_module2", "test_script", "TestModule99", "test_module_with_license", "TestFindModule", "PackageManagement" -SkipDependencyCheck -ErrorAction SilentlyContinue + Uninstall-PSResource 'test_module', 'test_module2', 'test_script', 'TestModule99', 'test_module_with_license', 'TestFindModule', 'PackageManagement' -SkipDependencyCheck -ErrorAction SilentlyContinue } AfterAll { Get-RevertPSResourceRepositoryFile } - $testCases = @{Name="*"; ErrorId="NameContainsWildcard"}, - @{Name="Test_Module*"; ErrorId="NameContainsWildcard"}, - @{Name="Test?Module","Test[Module"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"} + $testCases = [hashtable[]]( + @{Name='*'; ErrorId='NameContainsWildcard'}, + @{Name='Test_Module*'; ErrorId='NameContainsWildcard'}, + @{Name='Test?Module','Test[Module'; ErrorId='ErrorFilteringNamesForUnsupportedWildcards'} + ) - It "Should not install resource with wildcard in name" -TestCases $testCases { + It 'Should not install resource with wildcard in name' -TestCases $testCases { param($Name, $ErrorId) Install-PSResource -Name $Name -Repository $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $err.Count | Should -BeGreaterThan 0 @@ -47,36 +49,36 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { $res | Should -BeNullOrEmpty } - It "Install specific module resource by name" { + It 'Install specific module resource by name' { Install-PSResource -Name $testModuleName -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName - $pkg.Version | Should -Be "5.0.0" + $pkg.Version | Should -Be '5.0.0' } - It "Install specific script resource by name" { + It 'Install specific script resource by name' { Install-PSResource -Name $testScriptName -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testScriptName $pkg.Name | Should -Be $testScriptName - $pkg.Version | Should -Be "3.5.0" + $pkg.Version | Should -Be '3.5.0' } - It "Install multiple resources by name" { + It 'Install multiple resources by name' { $pkgNames = @($testModuleName, $testModuleName2) Install-PSResource -Name $pkgNames -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $pkgNames $pkg.Name | Should -Be $pkgNames } - It "Should not install resource given nonexistant name" { - Install-PSResource -Name "NonExistantModule" -Repository $NuGetGalleryName -TrustRepository -ErrorVariable err -ErrorAction SilentlyContinue - $pkg = Get-InstalledPSResource "NonExistantModule" -ErrorAction SilentlyContinue + It 'Should not install resource given nonexistant name' { + Install-PSResource -Name 'NonExistantModule' -Repository $NuGetGalleryName -TrustRepository -ErrorVariable err -ErrorAction SilentlyContinue + $pkg = Get-InstalledPSResource 'NonExistantModule' -ErrorAction SilentlyContinue $pkg.Name | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "InstallPackageFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly 'InstallPackageFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource' } - It "Install module using -WhatIf, should not install the module" { + It 'Install module using -WhatIf, should not install the module' { Install-PSResource -Name $testModuleName -Repository $NuGetGalleryName -TrustRepository -WhatIf $? | Should -BeTrue @@ -85,116 +87,116 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { } # Do some version testing, but Find-PSResource should be doing thorough testing - It "Should install resource given name and exact version" { - Install-PSResource -Name $testModuleName -Version "1.0.0" -Repository $NuGetGalleryName -TrustRepository + It 'Should install resource given name and exact version' { + Install-PSResource -Name $testModuleName -Version '1.0.0' -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName - $pkg.Version | Should -Be "1.0.0" + $pkg.Version | Should -Be '1.0.0' } - It "Should install resource given name and exact version with bracket syntax" { - Install-PSResource -Name $testModuleName -Version "[1.0.0]" -Repository $NuGetGalleryName -TrustRepository + It 'Should install resource given name and exact version with bracket syntax' { + Install-PSResource -Name $testModuleName -Version '[1.0.0]' -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName - $pkg.Version | Should -Be "1.0.0" + $pkg.Version | Should -Be '1.0.0' } - It "Should install resource given name and exact range inclusive [1.0.0, 5.0.0]" { - Install-PSResource -Name $testModuleName -Version "[1.0.0, 5.0.0]" -Repository $NuGetGalleryName -TrustRepository + It 'Should install resource given name and exact range inclusive [1.0.0, 5.0.0]' { + Install-PSResource -Name $testModuleName -Version '[1.0.0, 5.0.0]' -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName - $pkg.Version | Should -Be "5.0.0" + $pkg.Version | Should -Be '5.0.0' } - It "Should install resource given name and exact range exclusive (1.0.0, 5.0.0)" { - Install-PSResource -Name $testModuleName -Version "(1.0.0, 5.0.0)" -Repository $NuGetGalleryName -TrustRepository + It 'Should install resource given name and exact range exclusive (1.0.0, 5.0.0)' { + Install-PSResource -Name $testModuleName -Version '(1.0.0, 5.0.0)' -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName - $pkg.Version | Should -Be "3.0.0" + $pkg.Version | Should -Be '3.0.0' } # TODO: Update this test and others like it that use try/catch blocks instead of Should -Throw - It "Should not install resource with incorrectly formatted version such as exclusive version (1.0.0.0)" { - $Version = "(1.0.0.0)" + It 'Should not install resource with incorrectly formatted version such as exclusive version (1.0.0.0)' { + $Version = '(1.0.0.0)' try { Install-PSResource -Name $testModuleName -Version $Version -Repository $NuGetGalleryName -TrustRepository -ErrorAction SilentlyContinue } - catch - {} - $Error[0].FullyQualifiedErrorId | Should -Be "IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + catch { + } + $Error[0].FullyQualifiedErrorId | Should -Be 'IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource' $res = Get-InstalledPSResource $testModuleName -ErrorAction SilentlyContinue $res | Should -BeNullOrEmpty } It "Install resource when given Name, Version '*', should install the latest version" { - Install-PSResource -Name $testModuleName -Version "*" -Repository $NuGetGalleryName -TrustRepository + Install-PSResource -Name $testModuleName -Version '*' -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName - $pkg.Version | Should -Be "5.0.0" + $pkg.Version | Should -Be '5.0.0' } - It "Install resource with latest (including prerelease) version given Prerelease parameter" { + It 'Install resource with latest (including prerelease) version given Prerelease parameter' { Install-PSResource -Name $testModuleName -Prerelease -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName - $pkg.Version | Should -Be "5.2.5" - $pkg.Prerelease | Should -Be "alpha001" + $pkg.Version | Should -Be '5.2.5' + $pkg.Prerelease | Should -Be 'alpha001' } - It "Install resource via InputObject by piping from Find-PSresource" { + It 'Install resource via InputObject by piping from Find-PSresource' { Find-PSResource -Name $testModuleName -Repository $NuGetGalleryName | Install-PSResource -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName - $pkg.Version | Should -Be "5.0.0" + $pkg.Version | Should -Be '5.0.0' } - It "Install resource under specified in PSModulePath" { + It 'Install resource under specified in PSModulePath' { Install-PSResource -Name $testModuleName -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName ($env:PSModulePath).Contains($pkg.InstalledLocation) } - It "Install resource with companyname and repository source location and validate properties" { - Install-PSResource -Name $testModuleName -Version "5.2.5-alpha001" -Repository $NuGetGalleryName -TrustRepository + It 'Install resource with companyname and repository source location and validate properties' { + Install-PSResource -Name $testModuleName -Version '5.2.5-alpha001' -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName - $pkg.Version | Should -Be "5.2.5" - $pkg.Prerelease | Should -Be "alpha001" + $pkg.Version | Should -Be '5.2.5' + $pkg.Prerelease | Should -Be 'alpha001' - $pkg.CompanyName | Should -Be "Anam Navied" + $pkg.CompanyName | Should -Be 'Anam Navied' # Broken now, tracked in issue # $pkg.Copyright | Should -Be "(c) Anam Navied. All rights reserved." $pkg.RepositorySourceLocation | Should -Be $NuGetGalleryUri } # Windows only - It "Install resource under CurrentUser scope - Windows only" -Skip:(!(Get-IsWindows)) { + It 'Install resource under CurrentUser scope - Windows only' -Skip:(!(Get-IsWindows)) { Install-PSResource -Name $testModuleName -Repository $NuGetGalleryName -TrustRepository -Scope CurrentUser $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName - $pkg.InstalledLocation.ToString().Contains("Documents") | Should -Be $true + $pkg.InstalledLocation.ToString().Contains('Documents') | Should -Be $true } # Windows only - It "Install resource under AllUsers scope - Windows only" -Skip:(!((Get-IsWindows) -and (Test-IsAdmin))) { - Install-PSResource -Name "testmodule99" -Repository $NuGetGalleryName -TrustRepository -Scope AllUsers -Verbose - $pkg = Get-Module "testmodule99" -ListAvailable - $pkg.Name | Should -Be "testmodule99" - $pkg.Path.ToString().Contains("Program Files") + It 'Install resource under AllUsers scope - Windows only' -Skip:(!((Get-IsWindows) -and (Test-IsAdmin))) { + Install-PSResource -Name 'testmodule99' -Repository $NuGetGalleryName -TrustRepository -Scope AllUsers -Verbose + $pkg = Get-Module 'testmodule99' -ListAvailable + $pkg.Name | Should -Be 'testmodule99' + $pkg.Path.ToString().Contains('Program Files') } # Windows only - It "Install resource under no specified scope - Windows only" -Skip:(!(Get-IsWindows)) { + It 'Install resource under no specified scope - Windows only' -Skip:(!(Get-IsWindows)) { Install-PSResource -Name $testModuleName -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName - $pkg.InstalledLocation.ToString().Contains("Documents") | Should -Be $true + $pkg.InstalledLocation.ToString().Contains('Documents') | Should -Be $true } # Unix only # Expected path should be similar to: '/home/janelane/.local/share/powershell/Modules' - It "Install resource under CurrentUser scope - Unix only" -Skip:(Get-IsWindows) { + It 'Install resource under CurrentUser scope - Unix only' -Skip:(Get-IsWindows) { Install-PSResource -Name $testModuleName -Repository $NuGetGalleryName -TrustRepository -Scope CurrentUser $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName @@ -203,14 +205,14 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { # Unix only # Expected path should be similar to: '/home/janelane/.local/share/powershell/Modules' - It "Install resource under no specified scope - Unix only" -Skip:(Get-IsWindows) { + It 'Install resource under no specified scope - Unix only' -Skip:(Get-IsWindows) { Install-PSResource -Name $testModuleName -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.InstalledLocation.ToString().Contains("$env:HOME/.local") | Should -Be $true } - It "Should not install resource that is already installed" { + It 'Should not install resource that is already installed' { Install-PSResource -Name $testModuleName -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName @@ -218,15 +220,15 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { $WarningVar | Should -Not -BeNullOrEmpty } - It "Reinstall resource that is already installed with -Reinstall parameter" { + It 'Reinstall resource that is already installed with -Reinstall parameter' { Install-PSResource -Name $testModuleName -Repository $NuGetGalleryName -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName - $pkg.Version | Should -Be "5.0.0" + $pkg.Version | Should -Be '5.0.0' Install-PSResource -Name $testModuleName -Repository $NuGetGalleryName -Reinstall -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName - $pkg.Version | Should -Be "5.0.0" + $pkg.Version | Should -Be '5.0.0' } # It "Restore resource after reinstall fails" { @@ -255,36 +257,36 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { # (Get-ChildItem -Path $resourcePath -Recurse).Count | Should -BeExactly $resourceFiles.Count # } - It "Install resource that requires accept license with -AcceptLicense flag" { - Install-PSResource -Name "test_module_with_license" -Repository $NuGetGalleryName -AcceptLicense - $pkg = Get-InstalledPSResource "test_module_with_license" - $pkg.Name | Should -Be "test_module_with_license" - $pkg.Version | Should -Be "2.0.0" + It 'Install resource that requires accept license with -AcceptLicense flag' { + Install-PSResource -Name 'test_module_with_license' -Repository $NuGetGalleryName -AcceptLicense + $pkg = Get-InstalledPSResource 'test_module_with_license' + $pkg.Name | Should -Be 'test_module_with_license' + $pkg.Version | Should -Be '2.0.0' } - It "Install PSResourceInfo object piped in" { - Find-PSResource -Name $testModuleName -Version "1.0.0.0" -Repository $NuGetGalleryName | Install-PSResource -TrustRepository + It 'Install PSResourceInfo object piped in' { + Find-PSResource -Name $testModuleName -Version '1.0.0.0' -Repository $NuGetGalleryName | Install-PSResource -TrustRepository $res = Get-InstalledPSResource -Name $testModuleName $res.Name | Should -Be $testModuleName - $res.Version | Should -Be "1.0.0" + $res.Version | Should -Be '1.0.0' } - It "Install module using -PassThru" { + It 'Install module using -PassThru' { $res = Install-PSResource -Name $testModuleName -Repository $NuGetGalleryName -PassThru -TrustRepository $res.Name | Should -Contain $testModuleName } - It "Install modules using -RequiredResource with hashtable" { + It 'Install modules using -RequiredResource with hashtable' { $rrHash = @{ test_module = @{ - version = "[1.0.0,5.0.0)" + version = '[1.0.0,5.0.0)' repository = $NuGetGalleryName } test_module2 = @{ - version = "[1.0.0,5.0.0]" + version = '[1.0.0,5.0.0]' repository = $NuGetGalleryName - prerelease = "true" + prerelease = 'true' } TestModule99 = @{ @@ -296,92 +298,92 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { $res1 = Get-InstalledPSResource $testModuleName $res1.Name | Should -Be $testModuleName - $res1.Version | Should -Be "3.0.0" + $res1.Version | Should -Be '3.0.0' $res2 = Get-InstalledPSResource $testModuleName2 $res2.Name | Should -Be $testModuleName2 - $res2.Version | Should -Be "5.0.0" + $res2.Version | Should -Be '5.0.0' - $res3 = Get-InstalledPSResource "TestModule99" - $res3.Name | Should -Be "TestModule99" - $res3.Version | Should -Be "0.0.93" + $res3 = Get-InstalledPSResource 'TestModule99' + $res3.Name | Should -Be 'TestModule99' + $res3.Version | Should -Be '0.0.93' } - It "Install modules using -RequiredResource with JSON string" { + It 'Install modules using -RequiredResource with JSON string' { $rrJSON = "{ - 'test_module': { - 'version': '[1.0.0,5.0.0)', - 'repository': 'NuGetGallery' - }, - 'test_module2': { - 'version': '[1.0.0,5.0.0]', - 'repository': 'PSGallery', - 'prerelease': 'true' - }, - 'TestModule99': { - 'repository': 'NuGetGallery' - } - }" + 'test_module': { + 'version': '[1.0.0,5.0.0)', + 'repository': 'NuGetGallery' + }, + 'test_module2': { + 'version': '[1.0.0,5.0.0]', + 'repository': 'PSGallery', + 'prerelease': 'true' + }, + 'TestModule99': { + 'repository': 'NuGetGallery' + } + }" Install-PSResource -RequiredResource $rrJSON -TrustRepository $res1 = Get-InstalledPSResource $testModuleName $res1.Name | Should -Be $testModuleName - $res1.Version | Should -Be "3.0.0" + $res1.Version | Should -Be '3.0.0' $res2 = Get-InstalledPSResource $testModuleName2 $res2.Name | Should -Be $testModuleName2 - $res2.Version | Should -Be "5.0.0.0" + $res2.Version | Should -Be '5.0.0.0' - $res3 = Get-InstalledPSResource "testModule99" - $res3.Name | Should -Be "testModule99" - $res3.Version | Should -Be "0.0.93" + $res3 = Get-InstalledPSResource 'testModule99' + $res3.Name | Should -Be 'testModule99' + $res3.Version | Should -Be '0.0.93' } - It "Install modules using -RequiredResourceFile with PSD1 file" { + It 'Install modules using -RequiredResourceFile with PSD1 file' { $rrFilePSD1 = "$psscriptroot/../$RequiredResourcePSD1FileName" Install-PSResource -RequiredResourceFile $rrFilePSD1 -TrustRepository $res1 = Get-InstalledPSResource $testModuleName $res1.Name | Should -Be $testModuleName - $res1.Version | Should -Be "3.0.0.0" + $res1.Version | Should -Be '3.0.0.0' - $res2 = Get-InstalledPSResource $testModuleName2 -Version "2.5.0-beta" + $res2 = Get-InstalledPSResource $testModuleName2 -Version '2.5.0-beta' $res2.Name | Should -Be $testModuleName2 - $res2.Version | Should -Be "2.5.0" - $res2.Prerelease | Should -Be "beta" + $res2.Version | Should -Be '2.5.0' + $res2.Prerelease | Should -Be 'beta' - $res3 = Get-InstalledPSResource "testModule99" - $res3.Name | Should -Be "testModule99" - $res3.Version | Should -Be "0.0.93" + $res3 = Get-InstalledPSResource 'testModule99' + $res3.Name | Should -Be 'testModule99' + $res3.Version | Should -Be '0.0.93' } - It "Install modules using -RequiredResourceFile with JSON file" { + It 'Install modules using -RequiredResourceFile with JSON file' { $rrFileJSON = "$psscriptroot/../$RequiredResourceJSONFileName" Install-PSResource -RequiredResourceFile $rrFileJSON -TrustRepository $res1 = Get-InstalledPSResource $testModuleName $res1.Name | Should -Be $testModuleName - $res1.Version | Should -Be "3.0.0.0" + $res1.Version | Should -Be '3.0.0.0' - $res2 = Get-InstalledPSResource $testModuleName2 -Version "2.5.0-beta" + $res2 = Get-InstalledPSResource $testModuleName2 -Version '2.5.0-beta' $res2.Name | Should -Be $testModuleName2 - $res2.Version | Should -Be "2.5.0" - $res2.Prerelease | Should -Be "beta" + $res2.Version | Should -Be '2.5.0' + $res2.Prerelease | Should -Be 'beta' - $res3 = Get-InstalledPSResource "testModule99" - $res3.Name | Should -Be "testModule99" - $res3.Version | Should -Be "0.0.93" + $res3 = Get-InstalledPSResource 'testModule99' + $res3.Name | Should -Be 'testModule99' + $res3.Version | Should -Be '0.0.93' } } Describe 'Test Install-PSResource for V3Server scenarios' -tags 'ManualValidationOnly' { BeforeAll { - $testModuleName = "TestModule" - $testModuleName2 = "test_module_with_license" + $testModuleName = 'TestModule' + $testModuleName2 = 'test_module_with_license' Get-NewPSResourceRepositoryFile Register-LocalRepos } @@ -396,19 +398,19 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'ManualValidatio # Unix only manual test # Expected path should be similar to: '/usr/local/share/powershell/Modules' - It "Install resource under AllUsers scope - Unix only" -Skip:(Get-IsWindows) { + It 'Install resource under AllUsers scope - Unix only' -Skip:(Get-IsWindows) { Install-PSResource -Name $testModuleName -Repository $TestGalleryName -Scope AllUsers $pkg = Get-Module $testModuleName -ListAvailable $pkg.Name | Should -Be $testModuleName - $pkg.Path.Contains("/usr/") | Should -Be $true + $pkg.Path.Contains('/usr/') | Should -Be $true } # This needs to be manually tested due to prompt - It "Install resource that requires accept license without -AcceptLicense flag" { + It 'Install resource that requires accept license without -AcceptLicense flag' { Install-PSResource -Name $testModuleName2 -Repository $TestGalleryName $pkg = Get-InstalledPSResource $testModuleName2 $pkg.Name | Should -Be $testModuleName2 - $pkg.Version | Should -Be "2.0.0" + $pkg.Version | Should -Be '2.0.0' } # This needs to be manually tested due to prompt @@ -424,16 +426,16 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'ManualValidatio } It "Install package from NuGetGallery that has outer and inner 'items' elements only and has outer items element array length greater than 1" { - $res = Install-PSResource -Name "Microsoft.Extensions.DependencyInjection" -Repository $NuGetGalleryName -TrustRepository -PassThru -ErrorVariable err -ErrorAction SilentlyContinue + $res = Install-PSResource -Name 'Microsoft.Extensions.DependencyInjection' -Repository $NuGetGalleryName -TrustRepository -PassThru -ErrorVariable err -ErrorAction SilentlyContinue $err | Should -HaveCount 0 - $res.Name | Should -Be "Microsoft.Extensions.DependencyInjection" + $res.Name | Should -Be 'Microsoft.Extensions.DependencyInjection' } It "Install package from NuGetGallery that has outer 'items', '@id' and inner 'items' elements" { - $res = Install-PSResource -Name "MsgReader" -Repository $NuGetGalleryName -TrustRepository -PassThru -ErrorVariable err -ErrorAction SilentlyContinue + $res = Install-PSResource -Name 'MsgReader' -Repository $NuGetGalleryName -TrustRepository -PassThru -ErrorVariable err -ErrorAction SilentlyContinue $err | Should -HaveCount 0 - $res.Name | Should -Be "MsgReader" + $res.Name | Should -Be 'MsgReader' } } diff --git a/test/SavePSResourceTests/SavePSResourceV3Tests.ps1 b/test/SavePSResourceTests/SavePSResourceV3Tests.ps1 index cb414ce50..6f274ddad 100644 --- a/test/SavePSResourceTests/SavePSResourceV3Tests.ps1 +++ b/test/SavePSResourceTests/SavePSResourceV3Tests.ps1 @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -$ProgressPreference = "SilentlyContinue" +$ProgressPreference = 'SilentlyContinue' $modPath = "$psscriptroot/../PSGetTestUtils.psm1" Import-Module $modPath -Force -Verbose @@ -9,8 +9,8 @@ Describe 'Test HTTP Save-PSResource for V3 Server Protocol' -tags 'CI' { BeforeAll { $NuGetGalleryName = Get-NuGetGalleryName - $testModuleName = "test_module" - $testModuleName2 = "test_module2" + $testModuleName = 'test_module' + $testModuleName2 = 'test_module2' Get-NewPSResourceRepositoryFile $SaveDir = Join-Path $TestDrive 'SavedResources' @@ -26,14 +26,14 @@ Describe 'Test HTTP Save-PSResource for V3 Server Protocol' -tags 'CI' { Get-RevertPSResourceRepositoryFile } - It "Save specific module resource by name" { + It 'Save specific module resource by name' { Save-PSResource -Name $testModuleName -Repository $NuGetGalleryName -Path $SaveDir -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ $testModuleName $pkgDir | Should -Not -BeNullOrEmpty (Get-ChildItem $pkgDir.FullName) | Should -HaveCount 1 } - It "Save multiple resources by name" { + It 'Save multiple resources by name' { $pkgNames = @($testModuleName, $testModuleName2) Save-PSResource -Name $pkgNames -Repository $NuGetGalleryName -Path $SaveDir -TrustRepository $pkgDirs = Get-ChildItem -Path $SaveDir | Where-Object { $_.Name -eq $testModuleName -or $_.Name -eq $testModuleName2 } @@ -42,117 +42,117 @@ Describe 'Test HTTP Save-PSResource for V3 Server Protocol' -tags 'CI' { (Get-ChildItem $pkgDirs[1].FullName) | Should -HaveCount 1 } - It "Should not save resource given nonexistant name" { + It 'Should not save resource given nonexistant name' { Save-PSResource -Name NonExistentModule -Repository $NuGetGalleryName -Path $SaveDir -ErrorVariable err -ErrorAction SilentlyContinue -TrustRepository - $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ "NonExistentModule" + $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ 'NonExistentModule' $pkgDir.Name | Should -BeNullOrEmpty } - It "Not Save module with Name containing wildcard" { - Save-PSResource -Name "TestModule*" -Repository $NuGetGalleryName -Path $SaveDir -ErrorVariable err -ErrorAction SilentlyContinue -TrustRepository + It 'Not Save module with Name containing wildcard' { + Save-PSResource -Name 'TestModule*' -Repository $NuGetGalleryName -Path $SaveDir -ErrorVariable err -ErrorAction SilentlyContinue -TrustRepository $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "NameContainsWildcard,Microsoft.PowerShell.PSResourceGet.Cmdlets.SavePSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly 'NameContainsWildcard,Microsoft.PowerShell.PSResourceGet.Cmdlets.SavePSResource' } - It "Should save resource given name and exact version" { - Save-PSResource -Name $testModuleName -Version "1.0.0" -Repository $NuGetGalleryName -Path $SaveDir -TrustRepository + It 'Should save resource given name and exact version' { + Save-PSResource -Name $testModuleName -Version '1.0.0' -Repository $NuGetGalleryName -Path $SaveDir -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ $testModuleName $pkgDir | Should -Not -BeNullOrEmpty $pkgDirVersion = Get-ChildItem $pkgDir.FullName - $pkgDirVersion.Name | Should -Be "1.0.0" + $pkgDirVersion.Name | Should -Be '1.0.0' } - It "Should save resource given name and exact version with bracket syntax" { - Save-PSResource -Name $testModuleName -Version "[1.0.0]" -Repository $NuGetGalleryName -Path $SaveDir -TrustRepository + It 'Should save resource given name and exact version with bracket syntax' { + Save-PSResource -Name $testModuleName -Version '[1.0.0]' -Repository $NuGetGalleryName -Path $SaveDir -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ $testModuleName $pkgDir | Should -Not -BeNullOrEmpty $pkgDirVersion = Get-ChildItem -Path $pkgDir.FullName - $pkgDirVersion.Name | Should -Be "1.0.0" + $pkgDirVersion.Name | Should -Be '1.0.0' } - It "Should save resource given name and exact range inclusive [1.0.0, 3.0.0]" { - Save-PSResource -Name $testModuleName -Version "[1.0.0, 3.0.0]" -Repository $NuGetGalleryName -Path $SaveDir -TrustRepository + It 'Should save resource given name and exact range inclusive [1.0.0, 3.0.0]' { + Save-PSResource -Name $testModuleName -Version '[1.0.0, 3.0.0]' -Repository $NuGetGalleryName -Path $SaveDir -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ $testModuleName $pkgDir | Should -Not -BeNullOrEmpty $pkgDirVersion = Get-ChildItem -Path $pkgDir.FullName - $pkgDirVersion.Name | Should -Be "3.0.0" + $pkgDirVersion.Name | Should -Be '3.0.0' } - It "Should save resource given name and exact range exclusive (1.0.0, 5.0.0)" { - Save-PSResource -Name $testModuleName -Version "(1.0.0, 5.0.0)" -Repository $NuGetGalleryName -Path $SaveDir -TrustRepository + It 'Should save resource given name and exact range exclusive (1.0.0, 5.0.0)' { + Save-PSResource -Name $testModuleName -Version '(1.0.0, 5.0.0)' -Repository $NuGetGalleryName -Path $SaveDir -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ $testModuleName $pkgDir | Should -Not -BeNullOrEmpty $pkgDirVersion = Get-ChildItem -Path $pkgDir.FullName - $pkgDirVersion.Name | Should -Be "3.0.0" + $pkgDirVersion.Name | Should -Be '3.0.0' } - It "Should not save resource with incorrectly formatted version such as exclusive version (1.0.0.0)" { - $Version="(1.0.0.0)" + It 'Should not save resource with incorrectly formatted version such as exclusive version (1.0.0.0)' { + $Version='(1.0.0.0)' try { Save-PSResource -Name $testModuleName -Version $Version -Repository $NuGetGalleryName -Path $SaveDir -ErrorAction SilentlyContinue -TrustRepository } - catch - {} + catch { + } $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ $testModuleName $pkgDir | Should -BeNullOrEmpty $Error.Count | Should -BeGreaterThan 0 - $Error[0].FullyQualifiedErrorId | Should -Be "IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.SavePSResource" + $Error[0].FullyQualifiedErrorId | Should -Be 'IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.SavePSResource' } - It "Save resource with latest (including prerelease) version given Prerelease parameter" { + It 'Save resource with latest (including prerelease) version given Prerelease parameter' { Save-PSResource -Name $testModuleName -Prerelease -Repository $NuGetGalleryName -Path $SaveDir -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ $testModuleName $pkgDir | Should -Not -BeNullOrEmpty $pkgDirVersion = Get-ChildItem -Path $pkgDir.FullName - $pkgDirVersion.Name | Should -Be "5.2.5" + $pkgDirVersion.Name | Should -Be '5.2.5' } ### TODO: this is broken because the "Prerelease" parameter is a boolean, but the type from ### the input object is of type string (ie "true"). - It "Save PSResourceInfo object piped in for prerelease version object" -Pending{ - Find-PSResource -Name $testModuleName -Version "5.2.5-alpha001" -Repository $NuGetGalleryName | Save-PSResource -Path $SaveDir -TrustRepository + It 'Save PSResourceInfo object piped in for prerelease version object' -Pending{ + Find-PSResource -Name $testModuleName -Version '5.2.5-alpha001' -Repository $NuGetGalleryName | Save-PSResource -Path $SaveDir -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ $testModuleName $pkgDir | Should -Not -BeNullOrEmpty (Get-ChildItem -Path $pkgDir.FullName) | Should -HaveCount 1 } - It "Save module as a nupkg" { - Save-PSResource -Name $testModuleName -Version "1.0.0" -Repository $NuGetGalleryName -Path $SaveDir -AsNupkg -TrustRepository - $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ "test_module.1.0.0.nupkg" + It 'Save module as a nupkg' { + Save-PSResource -Name $testModuleName -Version '1.0.0' -Repository $NuGetGalleryName -Path $SaveDir -AsNupkg -TrustRepository + $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ 'test_module.1.0.0.nupkg' $pkgDir | Should -Not -BeNullOrEmpty } - It "Save module and include XML metadata file" { - Save-PSResource -Name $testModuleName -Version "1.0.0" -Repository $NuGetGalleryName -Path $SaveDir -IncludeXml -TrustRepository + It 'Save module and include XML metadata file' { + Save-PSResource -Name $testModuleName -Version '1.0.0' -Repository $NuGetGalleryName -Path $SaveDir -IncludeXml -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ $testModuleName $pkgDir | Should -Not -BeNullOrEmpty $pkgDirVersion = Get-ChildItem -Path $pkgDir.FullName - $pkgDirVersion.Name | Should -Be "1.0.0" - $xmlFile = Get-ChildItem -Path $pkgDirVersion.FullName | Where-Object Name -EQ "PSGetModuleInfo.xml" + $pkgDirVersion.Name | Should -Be '1.0.0' + $xmlFile = Get-ChildItem -Path $pkgDirVersion.FullName | Where-Object Name -EQ 'PSGetModuleInfo.xml' $xmlFile | Should -Not -BeNullOrEmpty } - It "Save module using -PassThru" { - $res = Save-PSResource -Name $testModuleName -Version "1.0.0" -Repository $NuGetGalleryName -Path $SaveDir -PassThru -TrustRepository + It 'Save module using -PassThru' { + $res = Save-PSResource -Name $testModuleName -Version '1.0.0' -Repository $NuGetGalleryName -Path $SaveDir -PassThru -TrustRepository $res.Name | Should -Be $testModuleName - $res.Version | Should -Be "1.0.0" + $res.Version | Should -Be '1.0.0' } # Save module that is not authenticode signed # Should FAIL to save the module - It "Save module that is not authenticode signed" -Skip:(!(Get-IsWindows)) { - Save-PSResource -Name $testModuleName -Version "5.0.0" -AuthenticodeCheck -Repository $NuGetGalleryName -TrustRepository -Path $SaveDir -ErrorVariable err -ErrorAction SilentlyContinue + It 'Save module that is not authenticode signed' -Skip:(!(Get-IsWindows)) { + Save-PSResource -Name $testModuleName -Version '5.0.0' -AuthenticodeCheck -Repository $NuGetGalleryName -TrustRepository -Path $SaveDir -ErrorVariable err -ErrorAction SilentlyContinue $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "InstallPackageFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.SavePSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly 'InstallPackageFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.SavePSResource' } # Save resource that requires license - It "Install resource that requires accept license with -AcceptLicense flag" { + It 'Install resource that requires accept license with -AcceptLicense flag' { Save-PSResource -Repository $NuGetGalleryName -TrustRepository -Path $SaveDir ` - -Name "test_module_with_license" -AcceptLicense - $pkg = Get-InstalledPSResource -Path $SaveDir "test_module_with_license" - $pkg.Name | Should -Be "test_module_with_license" - $pkg.Version | Should -Be "2.0.0" + -Name 'test_module_with_license' -AcceptLicense + $pkg = Get-InstalledPSResource -Path $SaveDir 'test_module_with_license' + $pkg.Name | Should -Be 'test_module_with_license' + $pkg.Version | Should -Be '2.0.0' } }