From 96a84b23c1750a5b228213c08c012cc17e28a5d8 Mon Sep 17 00:00:00 2001 From: Damon Tivel Date: Wed, 12 Jul 2017 09:16:49 -0700 Subject: [PATCH] Revert "Enable plugin package download (#1387)" --- NuGet.sln | 7 - .../OriginalCaseGlobalPackageFolder.cs | 76 +- .../RestoreCommand/ProjectRestoreCommand.cs | 22 +- .../SourceRepositoryDependencyProvider.cs | 214 +-- .../NuGet.Common/Logging/LoggerBase.cs | 2 +- src/NuGet.Core/NuGet.Common/Preprocessor.cs | 61 +- .../Providers/IRemoteDependencyProvider.cs | 84 +- .../Providers/LocalDependencyProvider.cs | 103 +- .../FileModifiers/IPackageFileTransformer.cs | 50 +- .../FileModifiers/PreProcessor.cs | 34 + .../FileModifiers/Preprocessor.cs | 108 -- .../FileModifiers/XdtTransformer.cs | 89 +- .../FileModifiers/XmlTransformer.cs | 136 +- .../IInstallationCompatibility.cs | 29 +- .../InstallationCompatibility.cs | 45 +- .../NuGetPackageManager.cs | 22 +- .../PackageDownloader.cs | 58 +- .../Projects/FolderNuGetProject.cs | 303 +--- .../Projects/MSBuildNuGetProject.cs | 53 +- .../Projects/PackagesConfigNuGetProject.cs | 33 +- .../Utility/FileSystemUtility.cs | 54 +- .../MSBuildNuGetProjectSystemUtility.cs | 127 +- .../IPackageCoreReader.cs | 35 +- .../PackagingCoreConstants.cs | 9 +- .../Definitions/IPackageDownloader.cs | 58 - .../LocalPackageArchiveDownloader.cs | 228 --- .../NuGet.Packaging/PackageExtractor.cs | 265 +-- .../NuGet.Packaging/PackagePathResolver.cs | 15 +- .../NuGet.Packaging/PackageReaderBase.cs | 131 +- .../VersionFolderPathResolver.cs | 96 +- .../Converters/SemanticVersionConverter.cs | 48 - .../NuGet.Protocol/DownloadResourceResult.cs | 78 +- .../DownloadResourceResultStatus.cs | 3 +- .../NuGet.Protocol/FactoryExtensionsV3.cs | 3 - .../LocalV2FindPackageByIdResource.cs | 209 +-- .../LocalV3FindPackageByIdResource.cs | 212 +-- .../NuGet.Protocol/NuGet.Protocol.csproj | 4 - .../Plugins/AutomaticProgressReporter.cs | 189 --- .../NuGet.Protocol/Plugins/Connection.cs | 268 --- .../Plugins/ConnectionOptions.cs | 139 -- .../NuGet.Protocol/Plugins/ConnectionState.cs | 22 - .../Plugins/EmbeddedSignatureVerifier.cs | 38 - .../FallbackEmbeddedSignatureVerifier.cs | 24 - .../NuGet.Protocol/Plugins/IConnection.cs | 80 - .../NuGet.Protocol/Plugins/IIdGenerator.cs | 17 - .../Plugins/IMessageDispatcher.cs | 107 -- .../NuGet.Protocol/Plugins/IPlugin.cs | 49 - .../Plugins/IPluginDiscoverer.cs | 27 - .../NuGet.Protocol/Plugins/IPluginFactory.cs | 46 - .../Plugins/IPluginMulticlientUtilities.cs | 30 - .../NuGet.Protocol/Plugins/IPluginProcess.cs | 44 - .../NuGet.Protocol/Plugins/IReceiver.cs | 37 - .../NuGet.Protocol/Plugins/IRequestHandler.cs | 63 - .../Plugins/IRequestHandlers.cs | 52 - .../Plugins/IResponseHandler.cs | 30 - .../NuGet.Protocol/Plugins/ISender.cs | 42 - .../Plugins/InboundRequestContext.cs | 233 --- .../Plugins/JsonSerializationUtilities.cs | 108 -- .../Plugins/LineReadEventArgs.cs | 27 - .../Plugins/MessageDispatcher.cs | 712 -------- .../Plugins/MessageEventArgs.cs | 33 - .../NuGet.Protocol/Plugins/MessageMethod.cs | 96 -- .../Plugins/MessageResponseCode.cs | 26 - .../NuGet.Protocol/Plugins/MessageType.cs | 36 - .../Plugins/MessageUtilities.cs | 92 -- .../Messages/CopyFilesInPackageRequest.cs | 104 -- .../Messages/CopyFilesInPackageResponse.cs | 60 - .../Plugins/Messages/CopyNupkgFileRequest.cs | 86 - .../Plugins/Messages/CopyNupkgFileResponse.cs | 43 - .../NuGet.Protocol/Plugins/Messages/Fault.cs | 37 - .../Plugins/Messages/GetCredentialsRequest.cs | 55 - .../Messages/GetCredentialsResponse.cs | 58 - .../Messages/GetFilesInPackageRequest.cs | 70 - .../Messages/GetFilesInPackageResponse.cs | 60 - .../Messages/GetOperationClaimsRequest.cs | 52 - .../Messages/GetOperationClaimsResponse.cs | 53 - .../Plugins/Messages/GetPackageHashRequest.cs | 86 - .../Messages/GetPackageHashResponse.cs | 57 - .../Messages/GetPackageVersionsRequest.cs | 54 - .../Messages/GetPackageVersionsResponse.cs | 60 - .../Messages/GetServiceIndexRequest.cs | 35 - .../Messages/GetServiceIndexResponse.cs | 59 - .../Plugins/Messages/HandshakeRequest.cs | 68 - .../Plugins/Messages/HandshakeResponse.cs | 73 - .../Plugins/Messages/InitializeRequest.cs | 71 - .../Plugins/Messages/InitializeResponse.cs | 43 - .../Plugins/Messages/LogRequest.cs | 59 - .../Plugins/Messages/LogResponse.cs | 43 - .../Plugins/Messages/Message.cs | 86 - .../MonitorNuGetProcessExitRequest.cs | 29 - .../MonitorNuGetProcessExitResponse.cs | 43 - .../Messages/PrefetchPackageRequest.cs | 70 - .../Messages/PrefetchPackageResponse.cs | 43 - .../Plugins/Messages/Progress.cs | 46 - .../Plugins/Messages/SetCredentialsRequest.cs | 67 - .../Messages/SetCredentialsResponse.cs | 43 - .../Plugins/Messages/SetLogLevelRequest.cs | 44 - .../Plugins/Messages/SetLogLevelResponse.cs | 43 - .../Plugins/NoOpDisposePlugin.cs | 97 -- .../NuGet.Protocol/Plugins/OperationClaim.cs | 16 - .../Plugins/OutboundRequestContext.cs | 55 - .../Plugins/OutboundRequestContext`1.cs | 202 --- .../NuGet.Protocol/Plugins/Plugin.cs | 229 --- .../NuGet.Protocol/Plugins/PluginConstants.cs | 40 - .../Plugins/PluginCreationResult.cs | 81 - .../Plugins/PluginDiscoverer.cs | 187 --- .../Plugins/PluginDiscoveryResult.cs | 43 - .../NuGet.Protocol/Plugins/PluginEventArgs.cs | 33 - .../NuGet.Protocol/Plugins/PluginException.cs | 32 - .../NuGet.Protocol/Plugins/PluginFactory.cs | 337 ---- .../NuGet.Protocol/Plugins/PluginFile.cs | 39 - .../NuGet.Protocol/Plugins/PluginFileState.cs | 31 - .../Plugins/PluginMulticlientUtilities.cs | 61 - .../Plugins/PluginPackageDownloader.cs | 194 --- .../Plugins/PluginPackageReader.cs | 1164 -------------- .../NuGet.Protocol/Plugins/PluginProcess.cs | 122 -- .../Plugins/ProtocolConstants.cs | 40 - .../Plugins/ProtocolErrorEventArgs.cs | 56 - .../Plugins/ProtocolException.cs | 32 - .../NuGet.Protocol/Plugins/Receiver.cs | 87 - .../NuGet.Protocol/Plugins/RequestHandlers.cs | 92 -- .../RequestHandlers/CloseRequestHandler.cs | 106 -- .../GetCredentialsRequestHandler.cs | 311 ---- .../GetServiceIndexRequestHandler.cs | 160 -- .../RequestHandlers/LogRequestHandler.cs | 192 --- .../MonitorNuGetProcessExitRequestHandler.cs | 148 -- .../RequestHandlers/SymmetricHandshake.cs | 230 --- .../Plugins/RequestIdGenerator.cs | 22 - .../NuGet.Protocol/Plugins/Sender.cs | 150 -- .../Plugins/StandardInputReceiver.cs | 135 -- .../Plugins/StandardOutputReceiver.cs | 117 -- .../Plugins/TimeoutUtilities.cs | 28 - .../WindowsEmbeddedSignatureVerifier.cs | 175 -- .../DownloadResourcePluginProvider.cs | 113 -- .../Providers/PluginResourceProvider.cs | 371 ----- .../RemotePackageArchiveDownloader.cs | 232 --- ...pFileSystemBasedFindPackageByIdResource.cs | 198 +-- .../PluginFindPackageByIdResource.cs | 416 ----- .../PluginFindPackageByIdResourceProvider.cs | 113 -- .../RemoteV2FindPackageByIdResource.cs | 210 +-- .../RemoteV3FindPackageByIdResource.cs | 205 +-- .../NuGet.Protocol/ResourceProvider.cs | 8 +- .../Resources/DownloadResourcePlugin.cs | 160 -- .../Resources/FindPackageByIdResource.cs | 98 +- .../Resources/PluginResource.cs | 167 -- .../Resources/ServiceIndexResourceV3.cs | 10 - .../NuGet.Protocol/Strings.Designer.cs | 227 +-- src/NuGet.Core/NuGet.Protocol/Strings.resx | 180 +-- .../Utility/GetDownloadResultUtility.cs | 7 +- .../Utility/OfflineFeedUtility.cs | 35 +- .../RestoreCommandTests.cs | 13 +- .../Helpers/PluginStub.cs | 111 -- .../NuGet.Protocol.FuncTest.csproj | 7 - .../NuGet.Protocol.FuncTest/PluginTests.cs | 202 --- .../NuGet.Protocol.FuncTest/ResponseSender.cs | 103 -- .../OriginalCaseGlobalPackageFolderTests.cs | 56 +- ...SourceRepositoryDependencyProviderTests.cs | 604 +------ .../NuGet.Common.Test/PreprocessorTests.cs | 180 --- .../LocalDependencyProviderTests.cs | 234 --- .../RemoteDependencyWalkerTests.cs | 10 +- .../ResolverFacts.cs | 32 +- .../FileModifiers/PreprocessorTests.cs | 201 --- .../FileModifiers/XdtTransformerTests.cs | 237 --- .../FileModifiers/XmlTransformerTests.cs | 251 --- .../InstallationCompatibilityTests.cs | 128 +- .../NuGetPackageManagerTests.cs | 29 +- .../PackageDownloaderTests.cs | 340 +--- .../FolderNuGetProjectTests.cs | 600 +------ .../Utility/FileSystemUtilityTests.cs | 136 -- .../LocalPackageArchiveDownloaderTests.cs | 311 ---- .../NugetPackageUtilTests.cs | 316 ++-- .../PackageArchiveReaderTests.cs | 36 +- .../PackageExtractorTests.cs | 955 ++--------- .../PackageFolderReaderTests.cs | 36 +- .../PackagePathResolverTests.cs | 99 +- .../VersionFolderPathResolverTests.cs | 40 +- .../SemanticVersionConverterTests.cs | 88 - .../DownloadResourceResultTests.cs | 261 --- ...SystemBasedFindPackageByIdResourceTests.cs | 79 + .../LocalV2FindPackageByIdResourceTests.cs | 531 ------ .../LocalV3FindPackageByIdResourceTests.cs | 562 ------- .../OffineFeedUtilityTests.cs | 69 + .../Plugins/AutomaticProgressReporterTests.cs | 229 --- .../Plugins/ConnectionOptionsTests.cs | 226 --- .../Plugins/ConnectionTests.cs | 639 -------- .../DownloadResourcePluginProviderTests.cs | 240 --- .../Plugins/DownloadResourcePluginTests.cs | 232 --- .../Plugins/EmbeddedSignatureVerifierTests.cs | 35 - .../FallbackEmbeddedSignatureVerifierTests.cs | 19 - .../Plugins/Helpers/SimulatedIpc.cs | 89 - .../Helpers/SimulatedReadOnlyFileStream.cs | 78 - .../Plugins/Helpers/SimulatedStreamReader.cs | 16 - .../Plugins/Helpers/SimulatedStreamWriter.cs | 17 - .../Helpers/SimulatedWriteOnlyFileStream.cs | 97 -- .../Plugins/Helpers/TestUtilities.cs | 22 - .../Plugins/InboundRequestContextTests.cs | 481 ------ .../JsonSerializationUtilitiesTests.cs | 128 -- .../Plugins/LineReadEventArgsTests.cs | 21 - .../Plugins/MessageDispatcherTests.cs | 925 ----------- .../Plugins/MessageEventArgsTests.cs | 28 - .../Plugins/MessageUtilitiesTests.cs | 156 -- .../CopyFilesInPackageRequestTests.cs | 174 -- .../CopyFilesInPackageResponseTests.cs | 101 -- .../Messages/CopyNupkgFileRequestTests.cs | 134 -- .../Messages/CopyNupkgFileResponseTests.cs | 59 - .../Plugins/Messages/FaultTests.cs | 59 - .../Messages/GetCredentialsRequestTests.cs | 102 -- .../Messages/GetCredentialsResponseTests.cs | 101 -- .../Messages/GetFilesInPackageRequestTests.cs | 109 -- .../GetFilesInPackageResponseTests.cs | 101 -- .../GetOperationClaimsRequestTests.cs | 105 -- .../GetOperationClaimsResponseTests.cs | 94 -- .../Messages/GetPackageHashRequestTests.cs | 134 -- .../Messages/GetPackageHashResponseTests.cs | 95 -- .../GetPackageVersionsRequestTests.cs | 86 - .../GetPackageVersionsResponseTests.cs | 101 -- .../Messages/GetServiceIndexRequestTests.cs | 61 - .../Messages/GetServiceIndexResponseTests.cs | 100 -- .../Plugins/Messages/HandshakeRequestTests.cs | 105 -- .../Messages/HandshakeResponseTests.cs | 99 -- .../Messages/InitializeRequestTests.cs | 158 -- .../Messages/InitializeResponseTests.cs | 60 - .../Plugins/Messages/LogRequestTests.cs | 78 - .../Plugins/Messages/LogResponseTests.cs | 58 - .../Plugins/Messages/MessageTests.cs | 127 -- .../MonitorNuGetProcessExitRequestTests.cs | 59 - .../MonitorNuGetProcessExitResponseTests.cs | 61 - .../Messages/PrefetchPackageRequestTests.cs | 108 -- .../Messages/PrefetchPackageResponseTests.cs | 61 - .../Plugins/Messages/ProgressTests.cs | 61 - .../Messages/SetCredentialsRequestTests.cs | 102 -- .../Messages/SetCredentialsResponseTests.cs | 60 - .../Messages/SetLogLevelRequestTests.cs | 63 - .../Messages/SetLogLevelResponseTests.cs | 60 - .../Plugins/NoOpDisposePluginTests.cs | 183 --- .../Plugins/OutboundRequestContextTests.cs | 256 --- .../Plugins/PluginCreationResultTests.cs | 86 - .../Plugins/PluginDiscovererTests.cs | 236 --- .../Plugins/PluginDiscoveryResultTests.cs | 31 - .../Plugins/PluginEventArgsTests.cs | 29 - .../Plugins/PluginFactoryTests.cs | 172 -- .../Plugins/PluginFileTests.cs | 30 - ...ginFindPackageByIdResourceProviderTests.cs | 234 --- .../PluginFindPackageByIdResourceTests.cs | 546 ------- .../PluginMulticlientUtilitiesTests.cs | 86 - .../Plugins/PluginPackageDownloaderTests.cs | 442 ----- .../Plugins/PluginPackageReaderTests.cs | 1430 ----------------- .../Plugins/PluginProcessTests.cs | 19 - .../Plugins/PluginResourceProviderTests.cs | 482 ------ .../Plugins/PluginResourceTests.cs | 233 --- .../Plugins/PluginTests.cs | 337 ---- .../Plugins/ProtocolErrorEventArgsTests.cs | 28 - .../CloseRequestHandlerTests.cs | 186 --- .../GetCredentialsRequestHandlerTests.cs | 599 ------- .../GetServiceIndexRequestHandlerTests.cs | 312 ---- .../RequestHandlers/LogRequestHandlerTests.cs | 301 ---- ...itorNuGetProcessExitRequestHandlerTests.cs | 202 --- .../SymmetricHandshakeTests.cs | 304 ---- .../Plugins/RequestHandlersTests.cs | 141 -- .../Plugins/RequestIdGeneratorTests.cs | 27 - .../Plugins/SenderTests.cs | 246 --- .../Plugins/StandardInputReceiverTests.cs | 438 ----- .../Plugins/StandardOutputReceiverTests.cs | 339 ---- .../Plugins/TimeoutUtilitiesTests.cs | 43 - .../WindowsEmbeddedSignatureVerifierTests.cs | 72 - .../RemotePackageArchiveDownloaderTests.cs | 403 ----- ...SystemBasedFindPackageByIdResourceTests.cs | 663 -------- .../RemoteV2FindPackageByIdResourceTests.cs | 800 --------- .../RemoteV3FindPackageByIdResourceTests.cs | 727 --------- .../RemoteV2FindPackageByIdResourceTests.cs | 169 ++ .../RemoteV3FindPackageByIdResourceTests.cs | 77 + .../ServiceIndexResourceV3Tests.cs | 44 - .../Utility/OfflineFeedUtilityTests.cs | 165 -- .../resources/DefaultClassLibrary.dll | Bin 4096 -> 0 bytes .../TestablePlugin/Arguments.cs | 80 - test/TestExtensions/TestablePlugin/Program.cs | 123 -- .../TestExtensions/TestablePlugin/Response.cs | 20 - .../TestablePlugin/ResponseReceiver.cs | 55 - .../TestablePlugin/TestablePlugin.cs | 123 -- .../TestablePlugin/TestablePlugin.csproj | 18 - .../Test.Utility/ResourceTestUtility.cs | 17 +- 281 files changed, 1374 insertions(+), 39216 deletions(-) create mode 100644 src/NuGet.Core/NuGet.PackageManagement/FileModifiers/PreProcessor.cs delete mode 100644 src/NuGet.Core/NuGet.PackageManagement/FileModifiers/Preprocessor.cs delete mode 100644 src/NuGet.Core/NuGet.Packaging/Definitions/IPackageDownloader.cs delete mode 100644 src/NuGet.Core/NuGet.Packaging/LocalPackageArchiveDownloader.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Converters/SemanticVersionConverter.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/AutomaticProgressReporter.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Connection.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/ConnectionOptions.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/ConnectionState.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/EmbeddedSignatureVerifier.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/FallbackEmbeddedSignatureVerifier.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/IConnection.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/IIdGenerator.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/IMessageDispatcher.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/IPlugin.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/IPluginDiscoverer.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/IPluginFactory.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/IPluginMulticlientUtilities.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/IPluginProcess.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/IReceiver.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/IRequestHandler.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/IRequestHandlers.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/IResponseHandler.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/ISender.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/InboundRequestContext.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/JsonSerializationUtilities.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/LineReadEventArgs.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/MessageDispatcher.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/MessageEventArgs.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/MessageMethod.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/MessageResponseCode.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/MessageType.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/MessageUtilities.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyFilesInPackageRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyFilesInPackageResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyNupkgFileRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyNupkgFileResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/Fault.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetCredentialsRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetCredentialsResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetFilesInPackageRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetFilesInPackageResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetOperationClaimsRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetOperationClaimsResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageHashRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageHashResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageVersionsRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageVersionsResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetServiceIndexRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetServiceIndexResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/HandshakeRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/HandshakeResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/InitializeRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/InitializeResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/LogRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/LogResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/Message.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/MonitorNuGetProcessExitRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/MonitorNuGetProcessExitResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/PrefetchPackageRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/PrefetchPackageResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/Progress.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetCredentialsRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetCredentialsResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetLogLevelRequest.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetLogLevelResponse.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/NoOpDisposePlugin.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/OperationClaim.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/OutboundRequestContext.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/OutboundRequestContext`1.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Plugin.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/PluginConstants.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/PluginCreationResult.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/PluginDiscoverer.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/PluginDiscoveryResult.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/PluginEventArgs.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/PluginException.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/PluginFactory.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/PluginFile.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/PluginFileState.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/PluginMulticlientUtilities.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/PluginPackageDownloader.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/PluginPackageReader.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/PluginProcess.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/ProtocolConstants.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/ProtocolErrorEventArgs.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/ProtocolException.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Receiver.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/CloseRequestHandler.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetCredentialsRequestHandler.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetServiceIndexRequestHandler.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/LogRequestHandler.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/MonitorNuGetProcessExitRequestHandler.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/SymmetricHandshake.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/RequestIdGenerator.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/Sender.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/StandardInputReceiver.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/StandardOutputReceiver.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/TimeoutUtilities.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Plugins/WindowsEmbeddedSignatureVerifier.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Providers/DownloadResourcePluginProvider.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Providers/PluginResourceProvider.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/RemotePackageArchiveDownloader.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/RemoteRepositories/PluginFindPackageByIdResource.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/RemoteRepositories/PluginFindPackageByIdResourceProvider.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Resources/DownloadResourcePlugin.cs delete mode 100644 src/NuGet.Core/NuGet.Protocol/Resources/PluginResource.cs delete mode 100644 test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/Helpers/PluginStub.cs delete mode 100644 test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/PluginTests.cs delete mode 100644 test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/ResponseSender.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Common.Test/PreprocessorTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.DependencyResolver.Core.Tests/LocalDependencyProviderTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.PackageManagement.Test/FileModifiers/PreprocessorTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.PackageManagement.Test/FileModifiers/XdtTransformerTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.PackageManagement.Test/FileModifiers/XmlTransformerTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.PackageManagement.Test/Utility/FileSystemUtilityTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Packaging.Test/LocalPackageArchiveDownloaderTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Converters/SemanticVersionConverterTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/DownloadResourceResultTests.cs create mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/HttpFileSystemBasedFindPackageByIdResourceTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/LocalRepositories/LocalV2FindPackageByIdResourceTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/LocalRepositories/LocalV3FindPackageByIdResourceTests.cs create mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/OffineFeedUtilityTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/AutomaticProgressReporterTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/ConnectionOptionsTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/ConnectionTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/DownloadResourcePluginProviderTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/DownloadResourcePluginTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/EmbeddedSignatureVerifierTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/FallbackEmbeddedSignatureVerifierTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedIpc.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedReadOnlyFileStream.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedStreamReader.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedStreamWriter.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedWriteOnlyFileStream.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/TestUtilities.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/InboundRequestContextTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/JsonSerializationUtilitiesTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/LineReadEventArgsTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/MessageDispatcherTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/MessageEventArgsTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/MessageUtilitiesTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyFilesInPackageRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyFilesInPackageResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyNupkgFileRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyNupkgFileResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/FaultTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetCredentialsRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetCredentialsResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetFilesInPackageRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetFilesInPackageResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetOperationClaimsRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetOperationClaimsResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageHashRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageHashResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageVersionsRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageVersionsResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetServiceIndexRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetServiceIndexResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/HandshakeRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/HandshakeResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/InitializeRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/InitializeResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/LogRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/LogResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/MessageTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/MonitorNuGetProcessExitRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/MonitorNuGetProcessExitResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/PrefetchPackageRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/PrefetchPackageResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/ProgressTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetCredentialsRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetCredentialsResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetLogLevelRequestTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetLogLevelResponseTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/NoOpDisposePluginTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/OutboundRequestContextTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginCreationResultTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginDiscovererTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginDiscoveryResultTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginEventArgsTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFactoryTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFileTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFindPackageByIdResourceProviderTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFindPackageByIdResourceTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginMulticlientUtilitiesTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginPackageDownloaderTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginPackageReaderTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginProcessTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginResourceProviderTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginResourceTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/ProtocolErrorEventArgsTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/CloseRequestHandlerTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/GetCredentialsRequestHandlerTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/GetServiceIndexRequestHandlerTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/LogRequestHandlerTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/MonitorNuGetProcessExitRequestHandlerTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/SymmetricHandshakeTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlersTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestIdGeneratorTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/SenderTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/StandardInputReceiverTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/StandardOutputReceiverTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/TimeoutUtilitiesTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/WindowsEmbeddedSignatureVerifierTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemotePackageArchiveDownloaderTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteRepositories/HttpFileSystemBasedFindPackageByIdResourceTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteRepositories/RemoteV2FindPackageByIdResourceTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteRepositories/RemoteV3FindPackageByIdResourceTests.cs create mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteV2FindPackageByIdResourceTests.cs create mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteV3FindPackageByIdResourceTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/ServiceIndexResourceV3Tests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/Utility/OfflineFeedUtilityTests.cs delete mode 100644 test/NuGet.Core.Tests/NuGet.Protocol.Tests/compiler/resources/DefaultClassLibrary.dll delete mode 100644 test/TestExtensions/TestablePlugin/Arguments.cs delete mode 100644 test/TestExtensions/TestablePlugin/Program.cs delete mode 100644 test/TestExtensions/TestablePlugin/Response.cs delete mode 100644 test/TestExtensions/TestablePlugin/ResponseReceiver.cs delete mode 100644 test/TestExtensions/TestablePlugin/TestablePlugin.cs delete mode 100644 test/TestExtensions/TestablePlugin/TestablePlugin.csproj diff --git a/NuGet.sln b/NuGet.sln index 8b7c160705b..c2228fdd65d 100644 --- a/NuGet.sln +++ b/NuGet.sln @@ -195,8 +195,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{96255044 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "TestUtilities", "TestUtilities", "{79266117-FEDD-45B3-B603-33A4B6E9F12F}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestablePlugin", "test\TestExtensions\TestablePlugin\TestablePlugin.csproj", "{F4CA95DA-0045-4AC4-ABA0-560008CEB963}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NuGet.Core.FuncTest", "test\NuGet.Core.FuncTests\NuGet.Core.FuncTest\NuGet.Core.FuncTest.csproj", "{34750BB3-4A21-433A-9C55-C051CA70C4AE}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet.Clients", "NuGet.Clients", "{08F523EC-3C2A-4A00-A54C-2E54C5AC856B}" @@ -475,10 +473,6 @@ Global {F813268A-1EA1-41E6-A42C-01E7F937E257}.Debug|Any CPU.Build.0 = Debug|Any CPU {F813268A-1EA1-41E6-A42C-01E7F937E257}.Release|Any CPU.ActiveCfg = Release|Any CPU {F813268A-1EA1-41E6-A42C-01E7F937E257}.Release|Any CPU.Build.0 = Release|Any CPU - {F4CA95DA-0045-4AC4-ABA0-560008CEB963}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F4CA95DA-0045-4AC4-ABA0-560008CEB963}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F4CA95DA-0045-4AC4-ABA0-560008CEB963}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F4CA95DA-0045-4AC4-ABA0-560008CEB963}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -560,6 +554,5 @@ Global {08F523EC-3C2A-4A00-A54C-2E54C5AC856B} = {BD1946CE-5544-4F28-A04A-9C3D51113E1A} {506AF844-92E0-4404-BBFC-0AB073890A72} = {BD1946CE-5544-4F28-A04A-9C3D51113E1A} {F813268A-1EA1-41E6-A42C-01E7F937E257} = {7323F93B-D141-4001-BB9E-7AF14031143E} - {F4CA95DA-0045-4AC4-ABA0-560008CEB963} = {23CEFC88-9365-4464-A517-700224ECA033} EndGlobalSection EndGlobal diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/OriginalCaseGlobalPackageFolder.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/OriginalCaseGlobalPackageFolder.cs index b99383b41cb..cc67fdbccec 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/OriginalCaseGlobalPackageFolder.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/OriginalCaseGlobalPackageFolder.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -14,7 +14,6 @@ using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.ProjectModel; -using NuGet.Protocol; using NuGet.Repositories; namespace NuGet.Commands @@ -74,41 +73,19 @@ public async Task CopyPackagesToOriginalCaseAsync(IEnumerable CopyToAsync(remoteMatch, destination, token), + originalCaseContext, + token); + + if (installed) { - var installed = await PackageExtractor.InstallFromSourceAsync( - packageDependency, - originalCaseContext, - token); - - if (installed) - { - _request.Log.LogMinimal(string.Format( - CultureInfo.CurrentCulture, - Strings.Log_ConvertedPackageToOriginalCase, - identity)); - } + _request.Log.LogMinimal(string.Format( + CultureInfo.CurrentCulture, + Strings.Log_ConvertedPackageToOriginalCase, + identity)); } } } @@ -145,11 +122,11 @@ private static PackageIdentity GetPackageIdentity(RemoteMatch remoteMatch) remoteMatch.Library.Version); } - private string GetLocalPackageFilePath(RemoteMatch remoteMatch) + private async Task CopyToAsync(RemoteMatch remoteMatch, Stream destination, CancellationToken token) { var library = remoteMatch.Library; - - // Try to get the package from the local repositories first. + + // Try to get the package from the local repositories first. var localPackage = NuGetv3LocalRepositoryUtility.GetPackage( _localRepositories, library.Name, @@ -157,10 +134,27 @@ private string GetLocalPackageFilePath(RemoteMatch remoteMatch) if (localPackage != null && File.Exists(localPackage.Package.ZipPath)) { - return localPackage.Package.ZipPath; + using (var stream = new FileStream( + localPackage.Package.ZipPath, + FileMode.Open, + FileAccess.Read, + FileShare.Read, + bufferSize: 4096, + useAsync: true)) + { + await stream.CopyToAsync(destination, bufferSize: 4096, cancellationToken: token); + } + } + else + { + // Otherwise, get it from the provider. + await remoteMatch.Provider.CopyToAsync( + remoteMatch.Library, + destination, + _request.CacheContext, + _request.Log, + token); } - - return null; } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/ProjectRestoreCommand.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/ProjectRestoreCommand.cs index eb99abdd92c..ee091a28b87 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/ProjectRestoreCommand.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/ProjectRestoreCommand.cs @@ -234,7 +234,7 @@ private async Task InstallPackagesAsync(IEnumerable graphs, } } - private async Task InstallPackageAsync(RemoteMatch installItem, CancellationToken token) + private Task InstallPackageAsync(RemoteMatch installItem, CancellationToken token) { var packageIdentity = new PackageIdentity(installItem.Library.Name, installItem.Library.Version); @@ -245,17 +245,15 @@ private async Task InstallPackageAsync(RemoteMatch installItem, CancellationToke _request.PackageSaveMode, _request.XmlDocFileSaveMode); - using (var packageDependency = await installItem.Provider.GetPackageDownloaderAsync( - packageIdentity, - _request.CacheContext, - _logger, - token)) - { - await PackageExtractor.InstallFromSourceAsync( - packageDependency, - versionFolderPathContext, - token); - } + return PackageExtractor.InstallFromSourceAsync( + stream => installItem.Provider.CopyToAsync( + installItem.Library, + stream, + _request.CacheContext, + _logger, + token), + versionFolderPathContext, + token); } private Task WalkRuntimeDependenciesAsync(LibraryRange projectRange, diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/SourceRepositoryDependencyProvider.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/SourceRepositoryDependencyProvider.cs index 86e462306fb..52fead975fa 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/SourceRepositoryDependencyProvider.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/SourceRepositoryDependencyProvider.cs @@ -1,9 +1,10 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -13,16 +14,12 @@ using NuGet.Frameworks; using NuGet.LibraryModel; using NuGet.Packaging; -using NuGet.Packaging.Core; using NuGet.Protocol; using NuGet.Protocol.Core.Types; using NuGet.Versioning; namespace NuGet.Commands { - /// - /// A source repository dependency provider. - /// public class SourceRepositoryDependencyProvider : IRemoteDependencyProvider { private readonly object _lock = new object(); @@ -49,18 +46,6 @@ private readonly ConcurrentDictionary> // In order to avoid too many open files error, set concurrent requests number to 16 on Mac private const int ConcurrencyLimit = 16; - /// - /// Initializes a new class. - /// - /// A source repository. - /// A logger. - /// A source cache context. - /// true to ignore failed sources; otherwise false. - /// true to ignore warnings; otherwise false. - /// Thrown if - /// is null. - /// Thrown if is null. - /// Thrown if is null. public SourceRepositoryDependencyProvider( SourceRepository sourceRepository, ILogger logger, @@ -68,21 +53,6 @@ public SourceRepositoryDependencyProvider( bool ignoreFailedSources, bool ignoreWarning) { - if (sourceRepository == null) - { - throw new ArgumentNullException(nameof(sourceRepository)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - _sourceRepository = sourceRepository; _logger = logger; _cacheContext = cacheContext; @@ -90,39 +60,14 @@ public SourceRepositoryDependencyProvider( _ignoreWarning = ignoreWarning; } - /// - /// Gets a flag indicating whether or not the provider source is HTTP or HTTPS. - /// public bool IsHttp => _sourceRepository.PackageSource.IsHttp; - /// - /// Gets the package source. - /// - /// Optional. This will be null for project providers. public PackageSource Source => _sourceRepository.PackageSource; /// - /// Asynchronously discovers all versions of a package from a source and selects the best match. + /// Discovers all versions of a package from a source and selects the best match. + /// This does not download the package. /// - /// This does not download the package. - /// A library range. - /// A target framework. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. public async Task FindLibraryAsync( LibraryRange libraryRange, NuGetFramework targetFramework, @@ -130,28 +75,6 @@ public async Task FindLibraryAsync( ILogger logger, CancellationToken cancellationToken) { - if (libraryRange == null) - { - throw new ArgumentNullException(nameof(libraryRange)); - } - - if (targetFramework == null) - { - throw new ArgumentNullException(nameof(targetFramework)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - AsyncLazy result = null; var action = new AsyncLazy(async () => @@ -169,7 +92,7 @@ public async Task FindLibraryAsync( return await result; } - private async Task FindLibraryCoreAsync( + public async Task FindLibraryCoreAsync( LibraryRange libraryRange, NuGetFramework targetFramework, SourceCacheContext cacheContext, @@ -197,62 +120,19 @@ private async Task FindLibraryCoreAsync( return null; } - /// - /// Asynchronously gets package dependencies. - /// - /// A library identity. - /// A target framework. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. public async Task GetDependenciesAsync( - LibraryIdentity libraryIdentity, + LibraryIdentity match, NuGetFramework targetFramework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken) { - if (libraryIdentity == null) - { - throw new ArgumentNullException(nameof(libraryIdentity)); - } - - if (targetFramework == null) - { - throw new ArgumentNullException(nameof(targetFramework)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - AsyncLazy result = null; var action = new AsyncLazy(async () => - await GetDependenciesCoreAsync(libraryIdentity, targetFramework, cacheContext, logger, cancellationToken)); + await GetDependenciesCoreAsync(match, targetFramework, cacheContext, logger, cancellationToken)); - var key = new LibraryRangeCacheKey(libraryIdentity, targetFramework); + var key = new LibraryRangeCacheKey(match, targetFramework); if (cacheContext.RefreshMemoryCache) { @@ -322,47 +202,13 @@ private async Task GetDependenciesCoreAsync( } } - /// - /// Asynchronously gets a package downloader. - /// - /// A package identity. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. - public async Task GetPackageDownloaderAsync( - PackageIdentity packageIdentity, + public async Task CopyToAsync( + LibraryIdentity identity, + Stream stream, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken) { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - await EnsureResource(); try @@ -374,30 +220,30 @@ public async Task GetPackageDownloaderAsync( cancellationToken.ThrowIfCancellationRequested(); - return await _findPackagesByIdResource.GetPackageDownloaderAsync( - packageIdentity, + // If the stream is already available, do not stop in the middle of copying the stream + // Pass in CancellationToken.None + await _findPackagesByIdResource.CopyNupkgToStreamAsync( + identity.Name, + identity.Version, + stream, cacheContext, logger, - cancellationToken); + CancellationToken.None); } catch (FatalProtocolException e) when (_ignoreFailedSources) { if (!_ignoreWarning) { - await _logger.LogAsync(RestoreLogMessage.CreateWarning(NuGetLogCode.NU1801, e.Message, packageIdentity.Id)); + await _logger.LogAsync(RestoreLogMessage.CreateWarning(NuGetLogCode.NU1801, e.Message, identity.Name)); } } finally { _throttle?.Release(); } - - return null; } - private IEnumerable GetDependencies( - FindPackageByIdDependencyInfo packageInfo, - NuGetFramework targetFramework) + private IEnumerable GetDependencies(FindPackageByIdDependencyInfo packageInfo, NuGetFramework targetFramework) { if (packageInfo == null) { @@ -439,20 +285,12 @@ private async Task EnsureResource() } /// - /// Asynchronously discover all package versions from a feed. + /// Discover all package versions from a feed. /// - /// A package ID. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - public async Task> GetAllVersionsAsync( - string id, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken) + public async Task> GetAllVersionsAsync(string id, + SourceCacheContext cacheContext, + ILogger logger, + CancellationToken cancellationToken) { IEnumerable packageVersions = null; try @@ -483,4 +321,4 @@ public async Task> GetAllVersionsAsync( return packageVersions; } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.Common/Logging/LoggerBase.cs b/src/NuGet.Core/NuGet.Common/Logging/LoggerBase.cs index 340bb86069c..88fd2389b16 100644 --- a/src/NuGet.Core/NuGet.Common/Logging/LoggerBase.cs +++ b/src/NuGet.Core/NuGet.Common/Logging/LoggerBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; diff --git a/src/NuGet.Core/NuGet.Common/Preprocessor.cs b/src/NuGet.Core/NuGet.Common/Preprocessor.cs index b93e9450fc3..d4d61efc74b 100644 --- a/src/NuGet.Core/NuGet.Common/Preprocessor.cs +++ b/src/NuGet.Core/NuGet.Common/Preprocessor.cs @@ -4,8 +4,6 @@ using System; using System.IO; using System.Text; -using System.Threading; -using System.Threading.Tasks; namespace NuGet.Common { @@ -14,65 +12,16 @@ namespace NuGet.Common /// public class Preprocessor { - /// - /// Asynchronously performs token replacement on a file stream. - /// - /// A stream task factory. - /// A token replacement function. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a . - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public static async Task ProcessAsync( - Func> streamTaskFactory, - Func tokenReplacement, - CancellationToken cancellationToken) + public static string Process(Func fileStreamFactory, Func tokenReplacement) { - if (streamTaskFactory == null) - { - throw new ArgumentNullException(nameof(streamTaskFactory)); - } - - if (tokenReplacement == null) - { - throw new ArgumentNullException(nameof(tokenReplacement)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - using (var stream = await streamTaskFactory()) + using (var stream = fileStreamFactory()) { return Process(stream, tokenReplacement); } } - /// - /// Performs token replacement on a stream and returns the result. - /// - /// A stream. - /// A token replacement funciton. - /// The token-replaced stream content. - /// Thrown if - /// is null. - /// Thrown if - /// is null. public static string Process(Stream stream, Func tokenReplacement) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (tokenReplacement == null) - { - throw new ArgumentNullException(nameof(tokenReplacement)); - } - string text; using (var streamReader = new StreamReader(stream)) { @@ -80,10 +29,10 @@ public static string Process(Stream stream, Func tokenReplacemen } var tokenizer = new Tokenizer(text); - var result = new StringBuilder(); + StringBuilder result = new StringBuilder(); for (; ; ) { - var token = tokenizer.Read(); + Token token = tokenizer.Read(); if (token == null) { break; @@ -103,4 +52,4 @@ public static string Process(Stream stream, Func tokenReplacemen return result.ToString(); } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.DependencyResolver.Core/Providers/IRemoteDependencyProvider.cs b/src/NuGet.Core/NuGet.DependencyResolver.Core/Providers/IRemoteDependencyProvider.cs index 38953b8dff4..06ff42e8182 100644 --- a/src/NuGet.Core/NuGet.DependencyResolver.Core/Providers/IRemoteDependencyProvider.cs +++ b/src/NuGet.Core/NuGet.DependencyResolver.Core/Providers/IRemoteDependencyProvider.cs @@ -1,58 +1,30 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; +using System.IO; using System.Threading; using System.Threading.Tasks; using NuGet.Common; using NuGet.Configuration; using NuGet.Frameworks; using NuGet.LibraryModel; -using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Protocol.Core.Types; using NuGet.Versioning; namespace NuGet.DependencyResolver { - /// - /// A remote dependency provider. - /// public interface IRemoteDependencyProvider { - /// - /// Gets a flag indicating whether or not the provider source is HTTP or HTTPS. - /// bool IsHttp { get; } /// - /// Gets the package source. + /// Feed package source. /// - /// Optional. This will be null for project providers. + /// Optional. This will be null for project providers. PackageSource Source { get; } - /// - /// Asynchronously discovers all versions of a package from a source and selects the best match. - /// - /// This does not download the package. - /// A library range. - /// A target framework. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. Task FindLibraryAsync( LibraryRange libraryRange, NuGetFramework targetFramework, @@ -60,54 +32,16 @@ Task FindLibraryAsync( ILogger logger, CancellationToken cancellationToken); - /// - /// Asynchronously gets package dependencies. - /// - /// A library identity. - /// A target framework. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. Task GetDependenciesAsync( - LibraryIdentity libraryIdentity, + LibraryIdentity match, NuGetFramework targetFramework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken); - /// - /// Asynchronously gets a package downloader. - /// - /// A package identity. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. - Task GetPackageDownloaderAsync( - PackageIdentity packageIdentity, + Task CopyToAsync( + LibraryIdentity match, + Stream stream, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken); @@ -118,4 +52,4 @@ Task> GetAllVersionsAsync( ILogger logger, CancellationToken token); } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.DependencyResolver.Core/Providers/LocalDependencyProvider.cs b/src/NuGet.Core/NuGet.DependencyResolver.Core/Providers/LocalDependencyProvider.cs index e2b61f6bdd8..5d5498583e4 100644 --- a/src/NuGet.Core/NuGet.DependencyResolver.Core/Providers/LocalDependencyProvider.cs +++ b/src/NuGet.Core/NuGet.DependencyResolver.Core/Providers/LocalDependencyProvider.cs @@ -1,71 +1,33 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; +using System.IO; using System.Threading; using System.Threading.Tasks; using NuGet.Common; using NuGet.Configuration; using NuGet.Frameworks; using NuGet.LibraryModel; -using NuGet.Packaging; -using NuGet.Packaging.Core; using NuGet.Protocol.Core.Types; using NuGet.Versioning; namespace NuGet.DependencyResolver { - /// - /// A local dependency provider. - /// public class LocalDependencyProvider : IRemoteDependencyProvider { private readonly IDependencyProvider _dependencyProvider; - /// - /// Initializes a new class. - /// - /// - /// Thrown if - /// is null. public LocalDependencyProvider(IDependencyProvider dependencyProvider) { - if (dependencyProvider == null) - { - throw new ArgumentNullException(nameof(dependencyProvider)); - } - _dependencyProvider = dependencyProvider; } - /// - /// Gets a flag indicating whether or not the provider source is HTTP or HTTPS. - /// public bool IsHttp { get; private set; } - /// - /// Gets the package source. - /// - /// Optional. This will be null for project providers. public PackageSource Source { get; private set; } - /// - /// Asynchronously discovers all versions of a package from a source and selects the best match. - /// - /// This does not download the package. - /// A library range. - /// A target framework. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. public Task FindLibraryAsync( LibraryRange libraryRange, NuGetFramework targetFramework, @@ -73,16 +35,6 @@ public Task FindLibraryAsync( ILogger logger, CancellationToken cancellationToken) { - if (libraryRange == null) - { - throw new ArgumentNullException(nameof(libraryRange)); - } - - if (targetFramework == null) - { - throw new ArgumentNullException(nameof(targetFramework)); - } - var library = _dependencyProvider.GetLibrary(libraryRange, targetFramework); if (library == null) @@ -93,61 +45,26 @@ public Task FindLibraryAsync( return Task.FromResult(library.Identity); } - /// - /// Asynchronously gets package dependencies. - /// - /// A library identity. - /// A target framework. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. public Task GetDependenciesAsync( - LibraryIdentity libraryIdentity, + LibraryIdentity library, NuGetFramework targetFramework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken) { - if (libraryIdentity == null) - { - throw new ArgumentNullException(nameof(libraryIdentity)); - } - - if (targetFramework == null) - { - throw new ArgumentNullException(nameof(targetFramework)); - } - - var library = _dependencyProvider.GetLibrary(libraryIdentity, targetFramework); + var description = _dependencyProvider.GetLibrary(library, targetFramework); var dependencyInfo = LibraryDependencyInfo.Create( - library.Identity, + description.Identity, targetFramework, - library.Dependencies); + description.Dependencies); return Task.FromResult(dependencyInfo); } - /// - /// Asynchronously gets a package downloader. - /// - /// A package identity. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown always. - public Task GetPackageDownloaderAsync( - PackageIdentity packageIdentity, + public Task CopyToAsync( + LibraryIdentity match, + Stream stream, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken) @@ -164,4 +81,4 @@ public Task> GetAllVersionsAsync( throw new NotImplementedException(); } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/IPackageFileTransformer.cs b/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/IPackageFileTransformer.cs index 27caf69a20d..3e799b4e2d4 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/IPackageFileTransformer.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/IPackageFileTransformer.cs @@ -1,61 +1,29 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; -using System.Threading; -using System.Threading.Tasks; namespace NuGet.ProjectManagement { - /// - /// Represents a package file transformer. - /// public interface IPackageFileTransformer { /// - /// Asynchronously transforms a file. + /// Transforms the file /// - /// A stream task factory. - /// A path to the file to be transformed. - /// The project where this change is taking place. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - Task TransformFileAsync( - Func> streamTaskFactory, - string targetPath, - IMSBuildProjectSystem projectSystem, - CancellationToken cancellationToken); + void TransformFile(Func fileStreamFactory, string targetPath, IMSBuildProjectSystem projectSystem); /// - /// Asynchronously reverses the transform on the targetPath, using all the potential source of change. + /// Reverses the transform on the targetPath, using all the potential source of change /// - /// A factory for accessing the file to be reverted from the nupkg being uninstalled. + /// A factory for accessing the file to be reverted from the nupkg being uninstalled. /// A path to the file to be reverted. - /// Other files in other packages that may have changed the . + /// Other files in other packages that may have changed the . /// The project where this change is taking place. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - Task RevertFileAsync( - Func> streamTaskFactory, + void RevertFile(Func fileStreamFactory, string targetPath, IEnumerable matchingFiles, - IMSBuildProjectSystem projectSystem, - CancellationToken cancellationToken); + IMSBuildProjectSystem projectSystem); } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/PreProcessor.cs b/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/PreProcessor.cs new file mode 100644 index 00000000000..a451941e1e4 --- /dev/null +++ b/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/PreProcessor.cs @@ -0,0 +1,34 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.IO; +using NuGet.Configuration; + +namespace NuGet.ProjectManagement +{ + /// + /// Simple token replacement system for content files. + /// + public class Preprocessor : IPackageFileTransformer + { + public void TransformFile(Func fileStreamFactory, string targetPath, IMSBuildProjectSystem msBuildNuGetProjectSystem) + { + MSBuildNuGetProjectSystemUtility.TryAddFile(msBuildNuGetProjectSystem, targetPath, + () => StreamUtility.StreamFromString(Process(fileStreamFactory, msBuildNuGetProjectSystem))); + } + + public void RevertFile(Func fileStreamFactory, string targetPath, IEnumerable matchingFiles, IMSBuildProjectSystem msBuildNuGetProjectSystem) + { + MSBuildNuGetProjectSystemUtility.DeleteFileSafe(targetPath, + () => StreamUtility.StreamFromString(Process(fileStreamFactory, msBuildNuGetProjectSystem)), + msBuildNuGetProjectSystem); + } + + internal static string Process(Func fileStreamFactory, IMSBuildProjectSystem msBuildNuGetProjectSystem) + { + return NuGet.Common.Preprocessor.Process(fileStreamFactory, propName => msBuildNuGetProjectSystem.GetPropertyValue(propName)); + } + } +} diff --git a/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/Preprocessor.cs b/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/Preprocessor.cs deleted file mode 100644 index eaf271cb600..00000000000 --- a/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/Preprocessor.cs +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.ProjectManagement -{ - /// - /// Simple token replacement system for content files. - /// - public class Preprocessor : IPackageFileTransformer - { - /// - /// Asynchronously transforms a file. - /// - /// A stream task factory. - /// A path to the file to be transformed. - /// The project where this change is taking place. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public async Task TransformFileAsync( - Func> streamTaskFactory, - string targetPath, - IMSBuildProjectSystem projectSystem, - CancellationToken cancellationToken) - { - if (streamTaskFactory == null) - { - throw new ArgumentNullException(nameof(streamTaskFactory)); - } - - if (projectSystem == null) - { - throw new ArgumentNullException(nameof(projectSystem)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - await MSBuildNuGetProjectSystemUtility.TryAddFileAsync( - projectSystem, - targetPath, - async () => StreamUtility.StreamFromString(await ProcessAsync(streamTaskFactory, projectSystem, cancellationToken)), - cancellationToken); - } - - /// - /// Asynchronously reverses the transform on the targetPath, using all the potential source of change. - /// - /// A factory for accessing the file to be reverted from the nupkg being uninstalled. - /// A path to the file to be reverted. - /// Other files in other packages that may have changed the . - /// The project where this change is taking place. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public async Task RevertFileAsync( - Func> streamTaskFactory, - string targetPath, - IEnumerable matchingFiles, - IMSBuildProjectSystem projectSystem, - CancellationToken cancellationToken) - { - if (streamTaskFactory == null) - { - throw new ArgumentNullException(nameof(streamTaskFactory)); - } - - if (projectSystem == null) - { - throw new ArgumentNullException(nameof(projectSystem)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - await MSBuildNuGetProjectSystemUtility.DeleteFileSafeAsync( - targetPath, - async () => StreamUtility.StreamFromString(await ProcessAsync(streamTaskFactory, projectSystem, cancellationToken)), - projectSystem, - cancellationToken); - } - - internal static Task ProcessAsync( - Func> streamTaskFactory, - IMSBuildProjectSystem projectSystem, - CancellationToken cancellationToken) - { - return Common.Preprocessor.ProcessAsync( - streamTaskFactory, - propName => projectSystem.GetPropertyValue(propName), - cancellationToken); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/XdtTransformer.cs b/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/XdtTransformer.cs index 27294d0ecdd..816d3f45bb9 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/XdtTransformer.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/XdtTransformer.cs @@ -1,105 +1,32 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Web.XmlTransform; using NuGet.PackageManagement; namespace NuGet.ProjectManagement { - /// - /// An XDT project file transformer. - /// public class XdtTransformer : IPackageFileTransformer { - /// - /// Asynchronously transforms a file. - /// - /// A stream task factory. - /// A path to the file to be transformed. - /// The project where this change is taking place. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public async Task TransformFileAsync( - Func> streamTaskFactory, - string targetPath, - IMSBuildProjectSystem projectSystem, - CancellationToken cancellationToken) + public void TransformFile(Func fileStreamFactory, string targetPath, IMSBuildProjectSystem msBuildNuGetProjectSystem) { - if (streamTaskFactory == null) - { - throw new ArgumentNullException(nameof(streamTaskFactory)); - } - - if (projectSystem == null) - { - throw new ArgumentNullException(nameof(projectSystem)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - await PerformXdtTransformAsync(streamTaskFactory, targetPath, projectSystem, cancellationToken); + PerformXdtTransform(fileStreamFactory, targetPath, msBuildNuGetProjectSystem); } - /// - /// Asynchronously reverses the transform on the targetPath, using all the potential source of change. - /// - /// A factory for accessing the file to be reverted from the nupkg being uninstalled. - /// A path to the file to be reverted. - /// Other files in other packages that may have changed the . - /// The project where this change is taking place. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public async Task RevertFileAsync( - Func> streamTaskFactory, - string targetPath, - IEnumerable matchingFiles, - IMSBuildProjectSystem projectSystem, - CancellationToken cancellationToken) + public void RevertFile(Func fileStreamFactory, string targetPath, IEnumerable matchingFiles, IMSBuildProjectSystem msBuildNuGetProjectSystem) { - if (streamTaskFactory == null) - { - throw new ArgumentNullException(nameof(streamTaskFactory)); - } - - if (projectSystem == null) - { - throw new ArgumentNullException(nameof(projectSystem)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - await PerformXdtTransformAsync(streamTaskFactory, targetPath, projectSystem, cancellationToken); + PerformXdtTransform(fileStreamFactory, targetPath, msBuildNuGetProjectSystem); } - private static async Task PerformXdtTransformAsync( - Func> streamTaskFactory, - string targetPath, - IMSBuildProjectSystem msBuildNuGetProjectSystem, - CancellationToken cancellationToken) + private static void PerformXdtTransform(Func fileStreamFactory, string targetPath, IMSBuildProjectSystem msBuildNuGetProjectSystem) { if (FileSystemUtility.FileExists(msBuildNuGetProjectSystem.ProjectFullPath, targetPath)) { - var content = await Preprocessor.ProcessAsync(streamTaskFactory, msBuildNuGetProjectSystem, cancellationToken); + var content = Preprocessor.Process(fileStreamFactory, msBuildNuGetProjectSystem); try { @@ -139,4 +66,4 @@ private static async Task PerformXdtTransformAsync( } } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/XmlTransformer.cs b/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/XmlTransformer.cs index 6c1a8bfe968..cd499501e14 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/XmlTransformer.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/FileModifiers/XmlTransformer.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using NuGet.Common; @@ -8,178 +8,80 @@ using System.IO.Compression; using System.Linq; using System.Xml.Linq; -using System.Threading.Tasks; -using System.Threading; namespace NuGet.ProjectManagement { - /// - /// An XML project file transformer. - /// public class XmlTransformer : IPackageFileTransformer { private readonly IDictionary> _nodeActions; - /// - /// Initializes a new class. - /// - /// A dictionary of XML node names to node actions. - /// Thrown if - /// is null. public XmlTransformer(IDictionary> nodeActions) { - if (nodeActions == null) - { - throw new ArgumentNullException(nameof(nodeActions)); - } - _nodeActions = nodeActions; } - /// - /// Asynchronously transforms a file. - /// - /// A stream task factory. - /// A path to the file to be transformed. - /// The project where this change is taking place. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public async Task TransformFileAsync( - Func> streamTaskFactory, - string targetPath, - IMSBuildProjectSystem projectSystem, - CancellationToken cancellationToken) + public void TransformFile(Func fileStreamFactory, string targetPath, IMSBuildProjectSystem msBuildNuGetProjectSystem) { - if (streamTaskFactory == null) - { - throw new ArgumentNullException(nameof(streamTaskFactory)); - } - - if (projectSystem == null) - { - throw new ArgumentNullException(nameof(projectSystem)); - } - - cancellationToken.ThrowIfCancellationRequested(); - // Get the xml fragment - var xmlFragment = await GetXmlAsync(streamTaskFactory, projectSystem, cancellationToken); + var xmlFragment = GetXml(fileStreamFactory, msBuildNuGetProjectSystem); - var transformDocument = XmlUtility.GetOrCreateDocument(xmlFragment.Name, targetPath, projectSystem); + var transformDocument = XmlUtility.GetOrCreateDocument(xmlFragment.Name, targetPath, msBuildNuGetProjectSystem); // Do a merge transformDocument.Root.MergeWith(xmlFragment, _nodeActions); - MSBuildNuGetProjectSystemUtility.AddFile(projectSystem, targetPath, transformDocument.Save); + MSBuildNuGetProjectSystemUtility.AddFile(msBuildNuGetProjectSystem, targetPath, transformDocument.Save); } - /// - /// Asynchronously reverses the transform on the targetPath, using all the potential source of change. - /// - /// A factory for accessing the file to be reverted from the nupkg being uninstalled. - /// A path to the file to be reverted. - /// Other files in other packages that may have changed the . - /// The project where this change is taking place. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public async Task RevertFileAsync( - Func> streamTaskFactory, + public void RevertFile(Func fileStreamFactory, string targetPath, IEnumerable matchingFiles, - IMSBuildProjectSystem projectSystem, - CancellationToken cancellationToken) + IMSBuildProjectSystem msBuildNuGetProjectSystem) { - if (streamTaskFactory == null) - { - throw new ArgumentNullException(nameof(streamTaskFactory)); - } - - if (projectSystem == null) - { - throw new ArgumentNullException(nameof(projectSystem)); - } - - cancellationToken.ThrowIfCancellationRequested(); - // Get the xml snippet - var xmlFragment = await GetXmlAsync(streamTaskFactory, projectSystem, cancellationToken); + var xmlFragment = GetXml(fileStreamFactory, msBuildNuGetProjectSystem); var document = XmlUtility.GetOrCreateDocument(xmlFragment.Name, - projectSystem.ProjectFullPath, + msBuildNuGetProjectSystem.ProjectFullPath, targetPath, - projectSystem.NuGetProjectContext); + msBuildNuGetProjectSystem.NuGetProjectContext); // Merge the other xml elements into one element within this xml hierarchy (matching the config file path) - var elements = new List(); - - foreach (var matchingFile in matchingFiles) - { - elements.Add(await GetXmlAsync(matchingFile, projectSystem, cancellationToken)); - } - - var mergedFragments = elements.Aggregate( - new XElement(xmlFragment.Name), - (left, right) => left.MergeWith(right, _nodeActions)); + var mergedFragments = matchingFiles.Select(f => GetXml(f, msBuildNuGetProjectSystem)) + .Aggregate(new XElement(xmlFragment.Name), (left, right) => left.MergeWith(right, _nodeActions)); // Take the difference of the xml and remove it from the main xml file document.Root.Except(xmlFragment.Except(mergedFragments)); // Save the new content to the file system - using (var fileStream = FileSystemUtility.CreateFile( - projectSystem.ProjectFullPath, - targetPath, - projectSystem.NuGetProjectContext)) + using (var fileStream = FileSystemUtility.CreateFile(msBuildNuGetProjectSystem.ProjectFullPath, + targetPath, msBuildNuGetProjectSystem.NuGetProjectContext)) { document.Save(fileStream); } } - private static async Task GetXmlAsync( - InternalZipFileInfo packageFileInfo, - IMSBuildProjectSystem projectSystem, - CancellationToken cancellationToken) + private static XElement GetXml(InternalZipFileInfo packageFileInfo, IMSBuildProjectSystem msBuildNuGetProjectSystem) { string content; - using (var packageStream = File.OpenRead(packageFileInfo.ZipArchivePath)) { var zipArchive = new ZipArchive(packageStream); var zipArchivePackageEntry = PathUtility.GetEntry(zipArchive, packageFileInfo.ZipArchiveEntryFullName); - if (zipArchivePackageEntry == null) { throw new ArgumentException("internalZipFileInfo"); } - content = await Preprocessor.ProcessAsync( - () => Task.FromResult(zipArchivePackageEntry.Open()), - projectSystem, - cancellationToken); + content = Preprocessor.Process(zipArchivePackageEntry.Open, msBuildNuGetProjectSystem); } - return XElement.Parse(content, LoadOptions.PreserveWhitespace); } - private static async Task GetXmlAsync( - Func> streamTaskFactory, - IMSBuildProjectSystem projectSystem, - CancellationToken cancellationToken) + private static XElement GetXml(Func fileStreamFactory, IMSBuildProjectSystem msBuildNuGetProjectSystem) { - var content = await Preprocessor.ProcessAsync(streamTaskFactory, projectSystem, cancellationToken); - + var content = Preprocessor.Process(fileStreamFactory, msBuildNuGetProjectSystem); return XElement.Parse(content, LoadOptions.PreserveWhitespace); } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.PackageManagement/IInstallationCompatibility.cs b/src/NuGet.Core/NuGet.PackageManagement/IInstallationCompatibility.cs index 5a861ac5cd0..cb78fe5b8a8 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/IInstallationCompatibility.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/IInstallationCompatibility.cs @@ -1,10 +1,7 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using NuGet.Commands; using NuGet.Common; using NuGet.Packaging.Core; @@ -38,26 +35,16 @@ void EnsurePackageCompatibility( RestoreResult restoreResult); /// - /// Asynchronously validates the compatibility of a single downloaded package. + /// Validates the compatibility of a single downloaded package. /// - /// The NuGet project. The type of the NuGet project determines the sorts or - /// validations that are done. + /// + /// The NuGet project. The type of the NuGet project determines the sorts or validations that are done. + /// /// The identity of that package contained in the download result. /// The downloaded package. - /// A cancellation token.. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - Task EnsurePackageCompatibilityAsync( + void EnsurePackageCompatibility( NuGetProject nuGetProject, PackageIdentity packageIdentity, - DownloadResourceResult resourceResult, - CancellationToken cancellationToken); + DownloadResourceResult resourceResult); } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.PackageManagement/InstallationCompatibility.cs b/src/NuGet.Core/NuGet.PackageManagement/InstallationCompatibility.cs index f0802055c2b..de480ac037b 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/InstallationCompatibility.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/InstallationCompatibility.cs @@ -1,12 +1,10 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Threading; -using System.Threading.Tasks; using NuGet.Commands; using NuGet.Common; using NuGet.LibraryModel; @@ -79,50 +77,15 @@ public void EnsurePackageCompatibility( } } - /// - /// Asynchronously validates the compatibility of a single downloaded package. - /// - /// The NuGet project. The type of the NuGet project determines the sorts or - /// validations that are done. - /// The identity of that package contained in the download result. - /// The downloaded package. - /// A cancellation token.. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public async Task EnsurePackageCompatibilityAsync( + public void EnsurePackageCompatibility( NuGetProject nuGetProject, PackageIdentity packageIdentity, - DownloadResourceResult resourceResult, - CancellationToken cancellationToken) + DownloadResourceResult resourceResult) { - if (nuGetProject == null) - { - throw new ArgumentNullException(nameof(nuGetProject)); - } - - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (resourceResult == null) - { - throw new ArgumentNullException(nameof(resourceResult)); - } - - cancellationToken.ThrowIfCancellationRequested(); - NuspecReader nuspecReader; if (resourceResult.PackageReader != null) { - nuspecReader = await resourceResult.PackageReader.GetNuspecReaderAsync(cancellationToken); + nuspecReader = resourceResult.PackageReader.NuspecReader; } else { diff --git a/src/NuGet.Core/NuGet.PackageManagement/NuGetPackageManager.cs b/src/NuGet.Core/NuGet.PackageManagement/NuGetPackageManager.cs index 9ef336fab07..61b1cfb1d87 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/NuGetPackageManager.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/NuGetPackageManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -189,9 +189,8 @@ private void InitializePackagesFolderInfo(string packagesFolderPath, bool exclud { // FileSystemPackagesConfig supports id.version formats, if the version is excluded use the normal v2 format var feedType = excludeVersion ? FeedType.FileSystemV2 : FeedType.FileSystemPackagesConfig; - var resolver = new PackagePathResolver(packagesFolderPath, !excludeVersion); - PackagesFolderNuGetProject = new FolderNuGetProject(packagesFolderPath, resolver); + PackagesFolderNuGetProject = new FolderNuGetProject(packagesFolderPath, excludeVersion); // Capturing it locally is important since it allows for the instance to cache packages for the lifetime // of the closure \ NuGetPackageManager. PackagesFolderSourceRepository = SourceRepositoryProvider.CreateRepository( @@ -894,7 +893,7 @@ private async Task> PreviewUpdatePackagesForClas var projectInstalledPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token); var oldListOfInstalledPackages = projectInstalledPackageReferences.Select(p => p.PackageIdentity); - var isUpdateAll = (packageId == null && packageIdentities.Count == 0); + bool isUpdateAll = (packageId == null && packageIdentities.Count == 0); var preferredVersions = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -1052,7 +1051,7 @@ private async Task> PreviewUpdatePackagesForClas { // BUG #1181 VS2015 : Updating from one feed fails for packages from different feed. - var packagesFolderResource = await PackagesFolderSourceRepository.GetResourceAsync(token); + DependencyInfoResource packagesFolderResource = await PackagesFolderSourceRepository.GetResourceAsync(token); var packages = new List(); foreach (var installedPackage in projectInstalledPackageReferences) { @@ -1127,7 +1126,7 @@ private async Task> PreviewUpdatePackagesForClas } // if we have been asked for exact versions of packages then we should also force the uninstall/install of those packages (this corresponds to a -Reinstall) - var isReinstall = PrunePackageTree.IsExactVersion(resolutionContext.VersionConstraints); + bool isReinstall = PrunePackageTree.IsExactVersion(resolutionContext.VersionConstraints); var targetIds = Enumerable.Empty(); if (!isUpdateAll) @@ -2134,7 +2133,7 @@ await ExecuteUninstallAsync(nuGetProject, using (var downloadPackageResult = await preFetchResult.GetResultAsync()) { // use the version exactly as specified in the nuspec file - var packageIdentity = await downloadPackageResult.PackageReader.GetIdentityAsync(token); + var packageIdentity = downloadPackageResult.PackageReader.GetIdentity(); await ExecuteInstallAsync( nuGetProject, @@ -2336,7 +2335,7 @@ public async Task PreviewBuildIntegratedProjectAct } var logger = new ProjectContextLogger(nuGetProjectContext); - var dependencyGraphContext = new DependencyGraphCacheContext(logger, Settings ); + var dependencyGraphContext = new DependencyGraphCacheContext(logger, Settings); // Get Package Spec as json object var originalPackageSpec = await DependencyGraphRestoreUtility.GetProjectSpec(buildIntegratedProject, dependencyGraphContext); @@ -2853,7 +2852,7 @@ public bool PackageExistsInPackagesFolder(PackageIdentity packageIdentity) return PackagesFolderNuGetProject.PackageExists(packageIdentity); } - private async Task ExecuteInstallAsync( + private Task ExecuteInstallAsync( NuGetProject nuGetProject, PackageIdentity packageIdentity, DownloadResourceResult resourceResult, @@ -2862,11 +2861,10 @@ private async Task ExecuteInstallAsync( CancellationToken token) { // TODO: EnsurePackageCompatibility check should be performed in preview. Can easily avoid a lot of rollback - await InstallationCompatibility.EnsurePackageCompatibilityAsync(nuGetProject, packageIdentity, resourceResult, token); + InstallationCompatibility.EnsurePackageCompatibility(nuGetProject, packageIdentity, resourceResult); packageWithDirectoriesToBeDeleted.Remove(packageIdentity); - - await nuGetProject.InstallPackageAsync(packageIdentity, resourceResult, nuGetProjectContext, token); + return nuGetProject.InstallPackageAsync(packageIdentity, resourceResult, nuGetProjectContext, token); } private async Task ExecuteUninstallAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity, HashSet packageWithDirectoriesToBeDeleted, diff --git a/src/NuGet.Core/NuGet.PackageManagement/PackageDownloader.cs b/src/NuGet.Core/NuGet.PackageManagement/PackageDownloader.cs index 9bf9c1d0c08..eaec5a65cc4 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/PackageDownloader.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/PackageDownloader.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -22,28 +22,9 @@ namespace NuGet.PackageManagement public static class PackageDownloader { /// - /// Asynchronously returns a for a given package identity - /// and enumerable of source repositories. + /// Returns the for a given + /// from the given . /// - /// An enumerable of source repositories. - /// A package identity. - /// A package download context. - /// A global packages folder path. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. public static async Task GetDownloadResourceResultAsync( IEnumerable sources, PackageIdentity packageIdentity, @@ -195,28 +176,9 @@ public static async Task GetDownloadResourceResultAsync( } /// - /// Asynchronously returns a for a given package identity - /// and source repository. + /// Returns the for a given from the given + /// . /// - /// A source repository. - /// A package identity. - /// A package download context. - /// A global packages folder path. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. public static async Task GetDownloadResourceResultAsync( SourceRepository sourceRepository, PackageIdentity packageIdentity, @@ -249,11 +211,7 @@ public static async Task GetDownloadResourceResultAsync( if (downloadResource == null) { - throw new InvalidOperationException( - string.Format( - CultureInfo.CurrentCulture, - Strings.DownloadResourceNotFound, - sourceRepository.PackageSource.Source)); + throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.DownloadResourceNotFound, sourceRepository.PackageSource.Source)); } token.ThrowIfCancellationRequested(); @@ -307,7 +265,7 @@ public static async Task GetDownloadResourceResultAsync( result.PackageStream.Seek(0, SeekOrigin.Begin); result = new DownloadResourceResult(result.PackageStream, packageReader, sourceRepository.PackageSource.Source); } - else if (result.Status != DownloadResourceResultStatus.AvailableWithoutStream) + else { // bind the source result = new DownloadResourceResult(result.PackageStream, result.PackageReader, sourceRepository.PackageSource.Source); @@ -316,4 +274,4 @@ public static async Task GetDownloadResourceResultAsync( return result; } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.PackageManagement/Projects/FolderNuGetProject.cs b/src/NuGet.Core/NuGet.PackageManagement/Projects/FolderNuGetProject.cs index 255180e9ee0..202198e00e8 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Projects/FolderNuGetProject.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Projects/FolderNuGetProject.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -22,81 +22,36 @@ namespace NuGet.ProjectManagement /// public class FolderNuGetProject : NuGetProject { - /// - /// Gets the folder project's root path. - /// public string Root { get; set; } - - private PackagePathResolver PackagePathResolver { get; set; } - - /// - /// Initializes a new class. - /// - /// The folder project root path. - /// Thrown if is null. + private PackagePathResolver PackagePathResolver { get; } + public FolderNuGetProject(string root) + : this(root, new PackagePathResolver(root)) { - if (root == null) - { - throw new ArgumentNullException(nameof(root)); - } + } - Initialize(root, new PackagePathResolver(root)); + public FolderNuGetProject(string root, bool excludeVersion) + : this(root, new PackagePathResolver(root, !excludeVersion)) + { } - /// - /// Initializes a new class. - /// - /// The folder project root path. - /// A package path resolver. - /// Thrown if is null. - /// Thrown if - /// is null. public FolderNuGetProject(string root, PackagePathResolver packagePathResolver) { if (root == null) { throw new ArgumentNullException(nameof(root)); } - - if (packagePathResolver == null) - { - throw new ArgumentNullException(nameof(packagePathResolver)); - } - - Initialize(root, packagePathResolver); + Root = root; + PackagePathResolver = packagePathResolver; + InternalMetadata.Add(NuGetProjectMetadataKeys.Name, root); + InternalMetadata.Add(NuGetProjectMetadataKeys.TargetFramework, NuGetFramework.AnyFramework); } - /// - /// Asynchronously gets installed packages. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . public override Task> GetInstalledPackagesAsync(CancellationToken token) { return Task.FromResult(Enumerable.Empty()); } - /// - /// Asynchronously installs a package. - /// - /// A package identity. - /// A download resource result. - /// A NuGet project context. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// indication successfulness of the operation. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if the package stream for - /// is not seekable. public override Task InstallPackageAsync( PackageIdentity packageIdentity, DownloadResourceResult downloadResourceResult, @@ -118,10 +73,9 @@ public override Task InstallPackageAsync( throw new ArgumentNullException(nameof(nuGetProjectContext)); } - if (downloadResourceResult.Status == DownloadResourceResultStatus.Available && - !downloadResourceResult.PackageStream.CanSeek) + if (!downloadResourceResult.PackageStream.CanSeek) { - throw new ArgumentException(Strings.PackageStreamShouldBeSeekable, nameof(downloadResourceResult)); + throw new ArgumentException(Strings.PackageStreamShouldBeSeekable); } var packageDirectory = PackagePathResolver.GetInstallPath(packageIdentity); @@ -147,33 +101,18 @@ public override Task InstallPackageAsync( nuGetProjectContext.Log(MessageLevel.Info, Strings.AddingPackageToFolder, packageIdentity, Path.GetFullPath(Root)); // 3. Call PackageExtractor to extract the package into the root directory of this FileSystemNuGetProject - if (downloadResourceResult.Status == DownloadResourceResultStatus.Available) - { - downloadResourceResult.PackageStream.Seek(0, SeekOrigin.Begin); - } + downloadResourceResult.PackageStream.Seek(0, SeekOrigin.Begin); var addedPackageFilesList = new List(); - + if (downloadResourceResult.PackageReader != null) { - if (downloadResourceResult.Status == DownloadResourceResultStatus.AvailableWithoutStream) - { - addedPackageFilesList.AddRange( - await PackageExtractor.ExtractPackageAsync( - downloadResourceResult.PackageReader, - PackagePathResolver, - packageExtractionContext, - cancellationToken)); - } - else - { - addedPackageFilesList.AddRange( - await PackageExtractor.ExtractPackageAsync( - downloadResourceResult.PackageReader, - downloadResourceResult.PackageStream, - PackagePathResolver, - packageExtractionContext, - cancellationToken)); - } + addedPackageFilesList.AddRange( + await PackageExtractor.ExtractPackageAsync( + downloadResourceResult.PackageReader, + downloadResourceResult.PackageStream, + PackagePathResolver, + packageExtractionContext, + cancellationToken)); } else { @@ -212,73 +151,34 @@ await PackageExtractor.ExtractPackageAsync( token: token); } - /// - /// Asynchronously uninstalls a package. - /// - /// A package identity. - /// A NuGet project context. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// indication successfulness of the operation. - public override Task UninstallPackageAsync( - PackageIdentity packageIdentity, - INuGetProjectContext nuGetProjectContext, - CancellationToken token) + public override Task UninstallPackageAsync(PackageIdentity packageIdentity, INuGetProjectContext nuGetProjectContext, CancellationToken token) { // Do nothing. Return true return Task.FromResult(true); } /// - /// Determines if a package is installed based on the presence of a .nupkg file. + /// A package is considered to exist in FileSystemNuGetProject, if the .nupkg file is present where expected /// - /// A package identity. - /// A flag indicating whether or not the package is installed. - /// Thrown if - /// is null. public bool PackageExists(PackageIdentity packageIdentity) { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - return PackageExists(packageIdentity, PackageSaveMode.Nupkg); } - /// - /// Determines if a package is installed based on the provided package save mode. - /// - /// A package identity. - /// A package save mode. - /// A flag indicating whether or not the package is installed. - /// Thrown if - /// is null. public bool PackageExists(PackageIdentity packageIdentity, PackageSaveMode packageSaveMode) { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - var packageExists = !string.IsNullOrEmpty(GetInstalledPackageFilePath(packageIdentity)); var manifestExists = !string.IsNullOrEmpty(GetInstalledManifestFilePath(packageIdentity)); - if (!packageExists) - { - packageExists |= !string.IsNullOrEmpty(GetPackageDownloadMarkerFilePath(packageIdentity)); - } - // A package must have either a nupkg or a nuspec to be valid var result = packageExists || manifestExists; - + // Verify nupkg present if specified if ((packageSaveMode & PackageSaveMode.Nupkg) == PackageSaveMode.Nupkg) { result &= packageExists; } - + // Verify nuspec present if specified if ((packageSaveMode & PackageSaveMode.Nuspec) == PackageSaveMode.Nuspec) { @@ -288,70 +188,19 @@ public bool PackageExists(PackageIdentity packageIdentity, PackageSaveMode packa return result; } - /// - /// Determines if a manifest is installed. - /// - /// A package identity. - /// A flag indicating whether or not the package is installed. - /// Thrown if - /// is null. public bool ManifestExists(PackageIdentity packageIdentity) { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - return !string.IsNullOrEmpty(GetInstalledManifestFilePath(packageIdentity)); } - /// - /// Determines if a manifest is installed. - /// - /// A package identity. - /// A flag indicating whether or not the package is installed. - /// Thrown if - /// is null. public bool PackageAndManifestExists(PackageIdentity packageIdentity) { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - return !string.IsNullOrEmpty(GetInstalledPackageFilePath(packageIdentity)) && !string.IsNullOrEmpty(GetInstalledManifestFilePath(packageIdentity)); } - /// - /// Asynchronously copies satellite files. - /// - /// A package identity. - /// A NuGet project context. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// indication successfulness of the operation. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public async Task CopySatelliteFilesAsync( - PackageIdentity packageIdentity, - INuGetProjectContext nuGetProjectContext, - CancellationToken token) + public async Task CopySatelliteFilesAsync(PackageIdentity packageIdentity, + INuGetProjectContext nuGetProjectContext, CancellationToken token) { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (nuGetProjectContext == null) - { - throw new ArgumentNullException(nameof(nuGetProjectContext)); - } - token.ThrowIfCancellationRequested(); var packageExtractionContext = nuGetProjectContext.PackageExtractionContext; @@ -373,19 +222,10 @@ public async Task CopySatelliteFilesAsync( } /// - /// Gets the package .nupkg file path if it exists; otherwise, null. + /// Get the path to the package nupkg. /// - /// A package identity. - /// The package .nupkg file path if it exists; otherwise, null. - /// Thrown if - /// is null. public string GetInstalledPackageFilePath(PackageIdentity packageIdentity) { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - // Check the expected location before searching all directories var packageDirectory = PackagePathResolver.GetInstallPath(packageIdentity); var packageName = PackagePathResolver.GetPackageFileName(packageIdentity); @@ -428,19 +268,10 @@ public string GetInstalledPackageFilePath(PackageIdentity packageIdentity) } /// - /// Gets the package .nuspec file path if it exists; otherwise, null. + /// Get the path to the package nuspec. /// - /// A package identity. - /// The package .nuspec file path if it exists; otherwise, null. - /// Thrown if - /// is null. public string GetInstalledManifestFilePath(PackageIdentity packageIdentity) { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - // Check the expected location before searching all directories var packageDirectory = PackagePathResolver.GetInstallPath(packageIdentity); var manifestName = PackagePathResolver.GetManifestFileName(packageIdentity); @@ -458,47 +289,10 @@ public string GetInstalledManifestFilePath(PackageIdentity packageIdentity) } /// - /// Gets the package download marker file path if it exists; otherwise, null. + /// Get the root directory of an installed package. /// - /// A package identity. - /// The package download marker file path if it exists; otherwise, null. - /// Thrown if - /// is null. - public string GetPackageDownloadMarkerFilePath(PackageIdentity packageIdentity) - { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - var packageDirectory = PackagePathResolver.GetInstallPath(packageIdentity); - var fileName = PackagePathResolver.GetPackageDownloadMarkerFileName(packageIdentity); - - var filePath = Path.GetFullPath(Path.Combine(packageDirectory, fileName)); - - // Keep the previous optimization of just going by the existance of the file if we find it. - if (File.Exists(filePath)) - { - return filePath; - } - - return null; - } - - /// - /// Gets the package directory path if the package exists; otherwise, null. - /// - /// A package identity. - /// The package directory path if the package exists; otherwise, null. - /// Thrown if - /// is null. public string GetInstalledPath(PackageIdentity packageIdentity) { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - var installFilePath = GetInstalledPackageFilePath(packageIdentity); if (!string.IsNullOrEmpty(installFilePath)) @@ -510,33 +304,10 @@ public string GetInstalledPath(PackageIdentity packageIdentity) return string.Empty; } - /// - /// Asynchronously deletes a package. - /// - /// A package identity. - /// A NuGet project context. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// indication successfulness of the operation. - /// Thrown if - /// is null. - /// Thrown if - /// is null. public async Task DeletePackage(PackageIdentity packageIdentity, INuGetProjectContext nuGetProjectContext, CancellationToken token) { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (nuGetProjectContext == null) - { - throw new ArgumentNullException(nameof(nuGetProjectContext)); - } - var packageFilePath = GetInstalledPackageFilePath(packageIdentity); if (File.Exists(packageFilePath)) { @@ -606,13 +377,5 @@ private PackageSaveMode GetPackageSaveMode(INuGetProjectContext nuGetProjectCont { return nuGetProjectContext.PackageExtractionContext?.PackageSaveMode ?? PackageSaveMode.Defaultv2; } - - private void Initialize(string root, PackagePathResolver resolver) - { - Root = root; - PackagePathResolver = resolver; - InternalMetadata.Add(NuGetProjectMetadataKeys.Name, root); - InternalMetadata.Add(NuGetProjectMetadataKeys.TargetFramework, NuGetFramework.AnyFramework); - } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.PackageManagement/Projects/MSBuildNuGetProject.cs b/src/NuGet.Core/NuGet.PackageManagement/Projects/MSBuildNuGetProject.cs index eae4021c18f..aef02ab61fe 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Projects/MSBuildNuGetProject.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Projects/MSBuildNuGetProject.cs @@ -153,8 +153,7 @@ public override async Task InstallPackageAsync( throw new ArgumentNullException(nameof(nuGetProjectContext)); } - if (downloadResourceResult.Status != DownloadResourceResultStatus.AvailableWithoutStream && - !downloadResourceResult.PackageStream.CanSeek) + if (!downloadResourceResult.PackageStream.CanSeek) { throw new ArgumentException(Strings.PackageStreamShouldBeSeekable); } @@ -172,23 +171,15 @@ public override async Task InstallPackageAsync( } // Step-2: Create PackageArchiveReader using the PackageStream and obtain the various item groups - if (downloadResourceResult.Status != DownloadResourceResultStatus.AvailableWithoutStream) - { - downloadResourceResult.PackageStream.Seek(0, SeekOrigin.Begin); - } - - // These casts enforce use of -Async(...) methods. - var packageReader = downloadResourceResult.PackageReader - ?? new PackageArchiveReader(downloadResourceResult.PackageStream, leaveStreamOpen: true); - IAsyncPackageContentReader packageContentReader = packageReader; - IAsyncPackageCoreReader packageCoreReader = packageReader; + downloadResourceResult.PackageStream.Seek(0, SeekOrigin.Begin); + var packageReader = downloadResourceResult.PackageReader ?? new PackageArchiveReader(downloadResourceResult.PackageStream, leaveStreamOpen: true); - var libItemGroups = await packageContentReader.GetLibItemsAsync(token); - var referenceItemGroups = await packageContentReader.GetReferenceItemsAsync(token); - var frameworkReferenceGroups = await packageContentReader.GetFrameworkItemsAsync(token); - var contentFileGroups = await packageContentReader.GetContentItemsAsync(token); - var buildFileGroups = await packageContentReader.GetBuildItemsAsync(token); - var toolItemGroups = await packageContentReader.GetToolItemsAsync(token); + var libItemGroups = packageReader.GetLibItems(); + var referenceItemGroups = packageReader.GetReferenceItems(); + var frameworkReferenceGroups = packageReader.GetFrameworkItems(); + var contentFileGroups = packageReader.GetContentItems(); + var buildFileGroups = packageReader.GetBuildItems(); + var toolItemGroups = packageReader.GetToolItems(); // Step-3: Get the most compatible items groups for all items groups var hasCompatibleProjectLevelContent = false; @@ -241,7 +232,7 @@ public override async Task InstallPackageAsync( if (!onlyHasCompatibleTools) { // If it does not have compatible tool items either, check if it at least has dependencies - onlyHasDependencies = (await packageContentReader.GetPackageDependenciesAsync(token)).Any(); + onlyHasDependencies = packageReader.GetPackageDependencies().Any(); } } else @@ -336,15 +327,11 @@ public override async Task InstallPackageAsync( } } - // Step-8.3: Add Content Files + // Step-8.3: Add Content Files if (MSBuildNuGetProjectSystemUtility.IsValid(compatibleContentFilesGroup)) { - await MSBuildNuGetProjectSystemUtility.AddFilesAsync( - ProjectSystem, - packageCoreReader, - compatibleContentFilesGroup, - FileTransformers, - token); + MSBuildNuGetProjectSystemUtility.AddFiles(ProjectSystem, + packageReader, compatibleContentFilesGroup, FileTransformers); } // Step-8.4: Add Build imports @@ -531,14 +518,12 @@ await ProjectServices.ScriptService.ExecutePackageScriptAsync( var packagesPaths = (await GetInstalledPackagesAsync(token)) .Select(pr => FolderNuGetProject.GetInstalledPackageFilePath(pr.PackageIdentity)); - await MSBuildNuGetProjectSystemUtility.DeleteFilesAsync( - ProjectSystem, - zipArchive, - packagesPaths, - compatibleContentFilesGroup, - FileTransformers, - token); - } + MSBuildNuGetProjectSystemUtility.DeleteFiles(ProjectSystem, + zipArchive, + packagesPaths, + compatibleContentFilesGroup, + FileTransformers); + } // Step-7.4: Remove build imports if (MSBuildNuGetProjectSystemUtility.IsValid(compatibleBuildFilesGroup)) diff --git a/src/NuGet.Core/NuGet.PackageManagement/Projects/PackagesConfigNuGetProject.cs b/src/NuGet.Core/NuGet.PackageManagement/Projects/PackagesConfigNuGetProject.cs index f50702334b5..a1cf950b78a 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Projects/PackagesConfigNuGetProject.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Projects/PackagesConfigNuGetProject.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -69,7 +69,7 @@ public PackagesConfigNuGetProject(string folderPath, Dictionary } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] - public override async Task InstallPackageAsync( + public override Task InstallPackageAsync( PackageIdentity packageIdentity, DownloadResourceResult downloadResourceResult, INuGetProjectContext nuGetProjectContext, @@ -85,13 +85,8 @@ public override async Task InstallPackageAsync( throw new ArgumentNullException("nuGetProjectContext"); } - var isDevelopmentDependency = await CheckDevelopmentDependencyAsync(downloadResourceResult, token); - var newPackageReference = new PackageReference( - packageIdentity, - TargetFramework, - userInstalled: true, - developmentDependency: isDevelopmentDependency, - requireReinstallation: false); + var isDevelopmentDependency = CheckDevelopmentDependency(downloadResourceResult); + var newPackageReference = new PackageReference(packageIdentity, TargetFramework, userInstalled: true, developmentDependency: isDevelopmentDependency, requireReinstallation: false); var installedPackagesList = GetInstalledPackagesList(); try @@ -112,7 +107,7 @@ public override async Task InstallPackageAsync( if (packageReferenceWithSameId.PackageIdentity.Equals(packageIdentity)) { nuGetProjectContext.Log(MessageLevel.Warning, Strings.PackageAlreadyExistsInPackagesConfig, packageIdentity, Path.GetFileName(FullPath)); - return false; + return Task.FromResult(false); } // Higher version of an installed package is being installed. Remove old and add new @@ -168,7 +163,7 @@ public override async Task InstallPackageAsync( } nuGetProjectContext.Log(MessageLevel.Info, Strings.AddedPackageToPackagesConfig, packageIdentity, Path.GetFileName(FullPath)); - return true; + return Task.FromResult(true); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] @@ -253,7 +248,7 @@ public XDocument GetPackagesConfig() var share = FileShare.ReadWrite | FileShare.Delete; // Try to read the config file up to 3 times - for (var i = 0; i < FileUtility.MaxTries; i++) + for (int i = 0; i < FileUtility.MaxTries; i++) { try { @@ -336,11 +331,9 @@ private List GetInstalledPackagesList() return new List(); } - private static async Task CheckDevelopmentDependencyAsync( - DownloadResourceResult downloadResourceResult, - CancellationToken token) + private static bool CheckDevelopmentDependency(DownloadResourceResult downloadResourceResult) { - var isDevelopmentDependency = false; + bool isDevelopmentDependency = false; // Catch any exceptions while fetching DevelopmentDependency element from nuspec file. // So it can continue to write the packages.config file. @@ -348,13 +341,11 @@ private static async Task CheckDevelopmentDependencyAsync( { if (downloadResourceResult.PackageReader != null) { - isDevelopmentDependency = await downloadResourceResult.PackageReader.GetDevelopmentDependencyAsync(token); + isDevelopmentDependency = downloadResourceResult.PackageReader.GetDevelopmentDependency(); } else { - using (var packageReader = new PackageArchiveReader( - downloadResourceResult.PackageStream, - leaveStreamOpen: true)) + using (var packageReader = new PackageArchiveReader(downloadResourceResult.PackageStream, leaveStreamOpen: true)) { var nuspecReader = new NuspecReader(packageReader.GetNuspec()); isDevelopmentDependency = nuspecReader.GetDevelopmentDependency(); @@ -366,4 +357,4 @@ private static async Task CheckDevelopmentDependencyAsync( return isDevelopmentDependency; } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.PackageManagement/Utility/FileSystemUtility.cs b/src/NuGet.Core/NuGet.PackageManagement/Utility/FileSystemUtility.cs index 1ad0b346865..5fd463ef7ee 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Utility/FileSystemUtility.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Utility/FileSystemUtility.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -7,7 +7,6 @@ using System.IO; using System.Linq; using System.Threading; -using System.Threading.Tasks; using NuGet.Common; using NuGet.PackageManagement; using NuGet.Packaging; @@ -304,28 +303,8 @@ orderby directory.Length descending } } - /// - /// Determines if the contents of a file and stream are equal. - /// - /// The path to a file. - /// A stream task factory. - /// true if contents are equal; otherwise, false. - /// Thrown if is either - /// null or an empty string. - /// Thrown if - /// is null. public static bool ContentEquals(string path, Func streamFactory) { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentException(Strings.Argument_Cannot_Be_Null_Or_Empty, nameof(path)); - } - - if (streamFactory == null) - { - throw new ArgumentNullException(nameof(streamFactory)); - } - using (Stream stream = streamFactory(), fileStream = File.OpenRead(path)) { @@ -333,37 +312,6 @@ public static bool ContentEquals(string path, Func streamFactory) } } - /// - /// Asynchronously determines if the contents of a file and stream are equal. - /// - /// The path to a file. - /// A stream task factory. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// which is true if contents are equal; otherwise, false. - /// Thrown if is either - /// null or an empty string. - /// Thrown if - /// is null. - public static async Task ContentEqualsAsync(string path, Func> streamTaskFactory) - { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentException(Strings.Argument_Cannot_Be_Null_Or_Empty, nameof(path)); - } - - if (streamTaskFactory == null) - { - throw new ArgumentNullException(nameof(streamTaskFactory)); - } - - using (Stream stream = await streamTaskFactory(), - fileStream = File.OpenRead(path)) - { - return StreamUtility.ContentEquals(stream, fileStream); - } - } - // PendAddFiles method here is called after addition of files during package extraction // whereas, delete files performs necessary pending followed by the deletion of files in a single method public static void PendAddFiles( diff --git a/src/NuGet.Core/NuGet.PackageManagement/Utility/MSBuildNuGetProjectSystemUtility.cs b/src/NuGet.Core/NuGet.PackageManagement/Utility/MSBuildNuGetProjectSystemUtility.cs index 0af00c62836..aa652a8d194 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Utility/MSBuildNuGetProjectSystemUtility.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Utility/MSBuildNuGetProjectSystemUtility.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -8,7 +8,6 @@ using System.IO.Compression; using System.Linq; using System.Threading; -using System.Threading.Tasks; using NuGet.Common; using NuGet.Frameworks; using NuGet.PackageManagement; @@ -78,46 +77,40 @@ internal static bool IsValid(FrameworkSpecificGroup frameworkSpecificGroup) return false; } - internal static async Task TryAddFileAsync( - IMSBuildProjectSystem projectSystem, - string path, - Func> streamTaskFactory, - CancellationToken cancellationToken) + internal static void TryAddFile(IMSBuildProjectSystem msBuildNuGetProjectSystem, string path, Func content) { - if (projectSystem.FileExistsInProject(path)) + if (msBuildNuGetProjectSystem.FileExistsInProject(path)) { // file exists in project, ask user if he wants to overwrite or ignore var conflictMessage = string.Format(CultureInfo.CurrentCulture, - Strings.FileConflictMessage, path, projectSystem.ProjectName); - var fileConflictAction = projectSystem.NuGetProjectContext.ResolveFileConflict(conflictMessage); + Strings.FileConflictMessage, path, msBuildNuGetProjectSystem.ProjectName); + var fileConflictAction = msBuildNuGetProjectSystem.NuGetProjectContext.ResolveFileConflict(conflictMessage); if (fileConflictAction == FileConflictAction.Overwrite || fileConflictAction == FileConflictAction.OverwriteAll) { // overwrite - projectSystem.NuGetProjectContext.Log(MessageLevel.Info, Strings.Info_OverwritingExistingFile, path); - using (var stream = await streamTaskFactory()) + msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Info, Strings.Info_OverwritingExistingFile, path); + using (var stream = content()) { - projectSystem.AddFile(path, stream); + msBuildNuGetProjectSystem.AddFile(path, stream); } } else { // ignore - projectSystem.NuGetProjectContext.Log(MessageLevel.Warning, Strings.Warning_FileAlreadyExists, path); + msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, Strings.Warning_FileAlreadyExists, path); } } else { - projectSystem.AddFile(path, await streamTaskFactory()); + msBuildNuGetProjectSystem.AddFile(path, content()); } } - internal static async Task AddFilesAsync( - IMSBuildProjectSystem projectSystem, - IAsyncPackageCoreReader packageReader, + internal static void AddFiles(IMSBuildProjectSystem msBuildNuGetProjectSystem, + IPackageCoreReader packageReader, FrameworkSpecificGroup frameworkSpecificGroup, - IDictionary fileTransformers, - CancellationToken cancellationToken) + IDictionary fileTransformers) { var packageTargetFramework = frameworkSpecificGroup.TargetFramework; @@ -132,7 +125,7 @@ internal static async Task AddFilesAsync( GetEffectivePathForContentFile(packageTargetFramework, file))); paths = paths.Where(p => !string.IsNullOrEmpty(p)); - projectSystem.RegisterProcessedFiles(paths); + msBuildNuGetProjectSystem.RegisterProcessedFiles(paths); } catch (Exception) { @@ -150,19 +143,16 @@ internal static async Task AddFilesAsync( // Resolve the target path IPackageFileTransformer installTransformer; - var path = ResolveTargetPath(projectSystem, + var path = ResolveTargetPath(msBuildNuGetProjectSystem, fileTransformers, fte => fte.InstallExtension, effectivePathForContentFile, out installTransformer); - if (projectSystem.IsSupportedFile(path)) + if (msBuildNuGetProjectSystem.IsSupportedFile(path)) { if (installTransformer != null) { - await installTransformer.TransformFileAsync( - () => packageReader.GetStreamAsync(file, cancellationToken), - path, - projectSystem, - cancellationToken); + installTransformer.TransformFile(() => packageReader.GetStream(file), path, + msBuildNuGetProjectSystem); } else { @@ -175,25 +165,18 @@ await installTransformer.TransformFileAsync( { continue; } - - await TryAddFileAsync( - projectSystem, - path, - () => packageReader.GetStreamAsync(file, cancellationToken), - cancellationToken); + TryAddFile(msBuildNuGetProjectSystem, path, () => packageReader.GetStream(file)); } } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] - internal static async Task DeleteFilesAsync( - IMSBuildProjectSystem projectSystem, + internal static void DeleteFiles(IMSBuildProjectSystem projectSystem, ZipArchive zipArchive, IEnumerable otherPackagesPath, FrameworkSpecificGroup frameworkSpecificGroup, - IDictionary fileTransformers, - CancellationToken cancellationToken) + IDictionary fileTransformers) { var packageTargetFramework = frameworkSpecificGroup.TargetFramework; IPackageFileTransformer transformer; @@ -211,7 +194,7 @@ from directory in FileSystemUtility.GetDirectories(grouping.Key, altDirectorySep orderby directory.Length descending select directory; - var projectFullPath = projectSystem.ProjectFullPath; + string projectFullPath = projectSystem.ProjectFullPath; // Remove files from every directory foreach (var directory in directories) @@ -285,11 +268,8 @@ orderby directory.Length descending var zipArchiveFileEntry = PathUtility.GetEntry(zipArchive, file); if (zipArchiveFileEntry != null) { - await transformer.RevertFileAsync( - () => Task.FromResult(zipArchiveFileEntry.Open()), - path, matchingFiles, - projectSystem, - cancellationToken); + transformer.RevertFile(zipArchiveFileEntry.Open, path, matchingFiles, + projectSystem); } } catch (Exception e) @@ -304,11 +284,7 @@ await transformer.RevertFileAsync( var zipArchiveFileEntry = PathUtility.GetEntry(zipArchive, file); if (zipArchiveFileEntry != null) { - await DeleteFileSafeAsync( - path, - () => Task.FromResult(zipArchiveFileEntry.Open()), - projectSystem, - cancellationToken); + DeleteFileSafe(path, zipArchiveFileEntry.Open, projectSystem); } } catch (Exception e) @@ -329,73 +305,65 @@ await DeleteFileSafeAsync( } } - internal static IEnumerable GetFilesSafe(IMSBuildProjectSystem projectSystem, string path) + internal static IEnumerable GetFilesSafe(IMSBuildProjectSystem msBuildNuGetProjectSystem, string path) { - return GetFilesSafe(projectSystem, path, "*.*"); + return GetFilesSafe(msBuildNuGetProjectSystem, path, "*.*"); } - internal static IEnumerable GetFilesSafe(IMSBuildProjectSystem projectSystem, string path, string filter) + internal static IEnumerable GetFilesSafe(IMSBuildProjectSystem msBuildNuGetProjectSystem, string path, string filter) { try { - return GetFiles(projectSystem, path, filter, recursive: false); + return GetFiles(msBuildNuGetProjectSystem, path, filter, recursive: false); } catch (Exception e) { - projectSystem.NuGetProjectContext.Log(MessageLevel.Warning, e.Message); + msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, e.Message); } return Enumerable.Empty(); } - internal static IEnumerable GetFiles( - IMSBuildProjectSystem projectSystem, - string path, - string filter, - bool recursive) + internal static IEnumerable GetFiles(IMSBuildProjectSystem msBuildNuGetProjectSystem, string path, string filter, bool recursive) { - return projectSystem.GetFiles(path, filter, recursive); + return msBuildNuGetProjectSystem.GetFiles(path, filter, recursive); } - internal static async Task DeleteFileSafeAsync( - string path, - Func> streamFactory, - IMSBuildProjectSystem projectSystem, - CancellationToken cancellationToken) + internal static void DeleteFileSafe(string path, Func streamFactory, IMSBuildProjectSystem msBuildNuGetProjectSystem) { // Only delete the file if it exists and the checksum is the same - if (projectSystem.FileExistsInProject(path)) + if (msBuildNuGetProjectSystem.FileExistsInProject(path)) { - var fullPath = Path.Combine(projectSystem.ProjectFullPath, path); - if (await FileSystemUtility.ContentEqualsAsync(fullPath, streamFactory)) + var fullPath = Path.Combine(msBuildNuGetProjectSystem.ProjectFullPath, path); + if (FileSystemUtility.ContentEquals(fullPath, streamFactory)) { - PerformSafeAction(() => projectSystem.RemoveFile(path), projectSystem.NuGetProjectContext); + PerformSafeAction(() => msBuildNuGetProjectSystem.RemoveFile(path), msBuildNuGetProjectSystem.NuGetProjectContext); } else { // This package installed a file that was modified so warn the user - projectSystem.NuGetProjectContext.Log(MessageLevel.Warning, Strings.Warning_FileModified, fullPath); + msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, Strings.Warning_FileModified, fullPath); } } } - internal static IEnumerable GetDirectoriesSafe(IMSBuildProjectSystem projectSystem, string path) + internal static IEnumerable GetDirectoriesSafe(IMSBuildProjectSystem msBuildNuGetProjectSystem, string path) { try { - return GetDirectories(projectSystem, path); + return GetDirectories(msBuildNuGetProjectSystem, path); } catch (Exception e) { - projectSystem.NuGetProjectContext.Log(MessageLevel.Warning, e.Message); + msBuildNuGetProjectSystem.NuGetProjectContext.Log(MessageLevel.Warning, e.Message); } return Enumerable.Empty(); } - internal static IEnumerable GetDirectories(IMSBuildProjectSystem projectSystem, string path) + internal static IEnumerable GetDirectories(IMSBuildProjectSystem msBuildNuGetProjectSystem, string path) { - return projectSystem.GetDirectories(path); + return msBuildNuGetProjectSystem.GetDirectories(path); } internal static void DeleteDirectorySafe(IMSBuildProjectSystem projectSystem, string path) @@ -508,8 +476,7 @@ private static string ResolvePath( return effectivePath; } - private static string ResolveTargetPath( - IMSBuildProjectSystem projectSystem, + private static string ResolveTargetPath(IMSBuildProjectSystem msBuildNuGetProjectSystem, IDictionary fileTransformers, Func extensionSelector, string effectivePath, @@ -524,7 +491,7 @@ private static string ResolveTargetPath( effectivePath = truncatedPath; } - return projectSystem.ResolvePath(effectivePath); + return msBuildNuGetProjectSystem.ResolvePath(effectivePath); } private static IPackageFileTransformer FindFileTransformer( @@ -594,13 +561,13 @@ internal static IEnumerable GetValidPackageItems(IEnumerable ite return items.Where(i => PackageHelper.IsPackageFile(i, PackageSaveMode.Defaultv3)); } - internal static void AddFile(IMSBuildProjectSystem projectSystem, string path, Action writeToStream) + internal static void AddFile(IMSBuildProjectSystem msBuildNuGetProjectSystem, string path, Action writeToStream) { using (var memoryStream = new MemoryStream()) { writeToStream(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); - projectSystem.AddFile(path, memoryStream); + msBuildNuGetProjectSystem.AddFile(path, memoryStream); } } diff --git a/src/NuGet.Core/NuGet.Packaging.Core/IPackageCoreReader.cs b/src/NuGet.Core/NuGet.Packaging.Core/IPackageCoreReader.cs index 6fd4235f910..f5a548cd3fd 100644 --- a/src/NuGet.Core/NuGet.Packaging.Core/IPackageCoreReader.cs +++ b/src/NuGet.Core/NuGet.Packaging.Core/IPackageCoreReader.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -17,63 +17,48 @@ namespace NuGet.Packaging.Core public interface IPackageCoreReader : IDisposable { /// - /// Gets the package identity. + /// Identity of the package /// - /// A package identity. + /// PackageIdentity GetIdentity(); /// - /// Gets the minimum client version needed to consume the package. + /// Minimum client version needed to consume the package. /// - /// A NuGet version. NuGetVersion GetMinClientVersion(); /// /// Gets zero or more package types from the .nuspec. /// - /// A readonly list of package types. IReadOnlyList GetPackageTypes(); /// - /// Gets a file stream from the package. + /// Returns a file stream from the package. /// - /// A stream for a file in the package. Stream GetStream(string path); /// - /// Gets all files in the package. + /// All files in the nupkg /// - /// An enumerable of files in the package. IEnumerable GetFiles(); /// - /// Gets files in a folder in the package. + /// Files in a folder /// /// Folder path - /// An enumerable of files under specified folder. + /// A collection of files under specified folder IEnumerable GetFiles(string folder); /// - /// Gets a nuspec stream. + /// Nuspec stream /// - /// A stream for the nuspec. Stream GetNuspec(); /// - /// Gets a nuspec file path. + /// Nuspec path /// - /// The nuspec file path. string GetNuspecFile(); - /// - /// Copies files from a package to a new location. - /// - /// The destination folder path. - /// The package files to copy. - /// A package file extraction delegate. - /// A logger. - /// A cancellation token. - /// An enumerable of paths of files copied to the destination. IEnumerable CopyFiles( string destination, IEnumerable packageFiles, diff --git a/src/NuGet.Core/NuGet.Packaging.Core/PackagingCoreConstants.cs b/src/NuGet.Core/NuGet.Packaging.Core/PackagingCoreConstants.cs index 44366addfa2..3519bfe5f93 100644 --- a/src/NuGet.Core/NuGet.Packaging.Core/PackagingCoreConstants.cs +++ b/src/NuGet.Core/NuGet.Packaging.Core/PackagingCoreConstants.cs @@ -1,14 +1,9 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace NuGet.Packaging.Core +namespace NuGet.Packaging.Core { public static class PackagingCoreConstants { - public static readonly string HashFileExtension = ".nupkg.sha512"; public static readonly string NupkgExtension = ".nupkg"; public static readonly string NuspecExtension = ".nuspec"; - public static readonly string PackageDownloadMarkerFileExtension = ".packagedownload.marker"; /// /// _._ denotes an empty folder since OPC does not allow an @@ -21,4 +16,4 @@ public static class PackagingCoreConstants /// public static readonly string ForwardSlashEmptyFolder = "/" + EmptyFolder; } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.Packaging/Definitions/IPackageDownloader.cs b/src/NuGet.Core/NuGet.Packaging/Definitions/IPackageDownloader.cs deleted file mode 100644 index b372d27290e..00000000000 --- a/src/NuGet.Core/NuGet.Packaging/Definitions/IPackageDownloader.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Packaging.Core; - -namespace NuGet.Packaging -{ - /// - /// A package downloader. - /// - public interface IPackageDownloader : IDisposable - { - /// - /// Gets an asynchronous package content reader. - /// - /// Thrown if this object is disposed. - IAsyncPackageContentReader ContentReader { get; } - - /// - /// Gets an asynchronous package core reader. - /// - /// Thrown if this object is disposed. - IAsyncPackageCoreReader CoreReader { get; } - - /// - /// Asynchronously copies a .nupkg to a target file path. - /// - /// The destination file path. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// indicating whether or not the copy was successful. - /// Thrown if this object is disposed. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. - Task CopyNupkgFileToAsync(string destinationFilePath, CancellationToken cancellationToken); - - /// - /// Asynchronously gets a package hash. - /// - /// The hash algorithm. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// representing the package hash. - /// Thrown if this object is disposed. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. - Task GetPackageHashAsync(string hashAlgorithm, CancellationToken cancellationToken); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Packaging/LocalPackageArchiveDownloader.cs b/src/NuGet.Core/NuGet.Packaging/LocalPackageArchiveDownloader.cs deleted file mode 100644 index 0857f56d687..00000000000 --- a/src/NuGet.Core/NuGet.Packaging/LocalPackageArchiveDownloader.cs +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Common; -using NuGet.Packaging.Core; - -namespace NuGet.Packaging -{ - /// - /// A package downloader for local archive packages. - /// - public sealed class LocalPackageArchiveDownloader : IPackageDownloader - { - private bool _isDisposed; - private readonly ILogger _logger; - private readonly string _packageFilePath; - private readonly PackageIdentity _packageIdentity; - private Lazy _packageReader; - private Lazy _sourceStream; - - /// - /// Gets an asynchronous package content reader. - /// - /// Thrown if this object is disposed. - public IAsyncPackageContentReader ContentReader - { - get - { - ThrowIfDisposed(); - - return _packageReader.Value; - } - } - - /// - /// Gets an asynchronous package core reader. - /// - /// Thrown if this object is disposed. - public IAsyncPackageCoreReader CoreReader - { - get - { - ThrowIfDisposed(); - - return _packageReader.Value; - } - } - - /// - /// Initializes a new class. - /// - /// A source package archive file path. - /// A package identity. - /// A logger. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - public LocalPackageArchiveDownloader( - string packageFilePath, - PackageIdentity packageIdentity, - ILogger logger) - { - if (string.IsNullOrEmpty(packageFilePath)) - { - throw new ArgumentException( - string.Format(CultureInfo.CurrentCulture, Strings.StringCannotBeNullOrEmpty, nameof(packageFilePath)), - nameof(packageFilePath)); - } - - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - _packageFilePath = packageFilePath; - _packageIdentity = packageIdentity; - _logger = logger; - _packageReader = new Lazy(GetPackageReader); - _sourceStream = new Lazy(GetSourceStream); - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (!_isDisposed) - { - if (_packageReader.IsValueCreated) - { - _packageReader.Value.Dispose(); - } - - if (_sourceStream.IsValueCreated) - { - _sourceStream.Value.Dispose(); - } - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - /// - /// Asynchronously copies a .nupkg to a target file path. - /// - /// The destination file path. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// indicating whether or not the copy was successful. - /// Thrown if this object is disposed. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. - public async Task CopyNupkgFileToAsync(string destinationFilePath, CancellationToken cancellationToken) - { - ThrowIfDisposed(); - - if (string.IsNullOrEmpty(destinationFilePath)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.StringCannotBeNullOrEmpty, - nameof(destinationFilePath)), - nameof(destinationFilePath)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - using (var destination = new FileStream( - destinationFilePath, - FileMode.Create, - FileAccess.ReadWrite, - FileShare.ReadWrite | FileShare.Delete, - bufferSize: 4096, - useAsync: true)) - { - await _sourceStream.Value.CopyToAsync( - destination, - bufferSize: 4096, - cancellationToken: cancellationToken); - } - - return true; - } - - /// - /// Asynchronously gets a package hash. - /// - /// The hash algorithm. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// representing the package hash. - /// Thrown if this object is disposed. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. - public Task GetPackageHashAsync(string hashAlgorithm, CancellationToken cancellationToken) - { - ThrowIfDisposed(); - - if (string.IsNullOrEmpty(hashAlgorithm)) - { - throw new ArgumentException( - string.Format(CultureInfo.CurrentCulture, Strings.StringCannotBeNullOrEmpty, nameof(hashAlgorithm)), - nameof(hashAlgorithm)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - _sourceStream.Value.Seek(0, SeekOrigin.Begin); - - var bytes = new CryptoHashProvider(hashAlgorithm).CalculateHash(_sourceStream.Value); - var packageHash = Convert.ToBase64String(bytes); - - return Task.FromResult(packageHash); - } - - private PackageArchiveReader GetPackageReader() - { - ThrowIfDisposed(); - - _sourceStream.Value.Seek(0, SeekOrigin.Begin); - - return new PackageArchiveReader(_sourceStream.Value); - } - - private FileStream GetSourceStream() - { - ThrowIfDisposed(); - - return new FileStream( - _packageFilePath, - FileMode.Open, - FileAccess.Read, - FileShare.Read, - bufferSize: 4096, - useAsync: true); - } - - private void ThrowIfDisposed() - { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(LocalPackageArchiveDownloader)); - } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Packaging/PackageExtractor.cs b/src/NuGet.Core/NuGet.Packaging/PackageExtractor.cs index d510e7feb17..c7adccfee6d 100644 --- a/src/NuGet.Core/NuGet.Packaging/PackageExtractor.cs +++ b/src/NuGet.Core/NuGet.Packaging/PackageExtractor.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -185,73 +185,6 @@ public static async Task> ExtractPackageAsync( return filesAdded; } - public static async Task> ExtractPackageAsync( - PackageReaderBase packageReader, - PackagePathResolver packagePathResolver, - PackageExtractionContext packageExtractionContext, - CancellationToken token) - { - if (packageReader == null) - { - throw new ArgumentNullException(nameof(packageReader)); - } - - if (packagePathResolver == null) - { - throw new ArgumentNullException(nameof(packagePathResolver)); - } - - if (packageExtractionContext == null) - { - throw new ArgumentNullException(nameof(packageExtractionContext)); - } - - token.ThrowIfCancellationRequested(); - - var packageSaveMode = packageExtractionContext.PackageSaveMode; - - var filesAdded = new List(); - - var packageIdentityFromNuspec = await packageReader.GetIdentityAsync(token); - - var packageDirectoryInfo = Directory.CreateDirectory(packagePathResolver.GetInstallPath(packageIdentityFromNuspec)); - var packageDirectory = packageDirectoryInfo.FullName; - - var packageFiles = await packageReader.GetPackageFilesAsync(packageSaveMode, token); - var packageFileExtractor = new PackageFileExtractor(packageFiles, packageExtractionContext.XmlDocFileSaveMode); - - filesAdded.AddRange(await packageReader.CopyFilesAsync( - packageDirectory, - packageFiles, - packageFileExtractor.ExtractPackageFile, - packageExtractionContext.Logger, - token)); - - if (packageSaveMode.HasFlag(PackageSaveMode.Nupkg)) - { - var nupkgFilePath = Path.Combine(packageDirectory, packagePathResolver.GetPackageFileName(packageIdentityFromNuspec)); - var filePath = await packageReader.CopyNupkgAsync(nupkgFilePath, token); - - if (!string.IsNullOrEmpty(filePath)) - { - filesAdded.Add(filePath); - } - } - - // Now, copy satellite files unless requested to not copy them - if (packageExtractionContext.CopySatelliteFiles) - { - filesAdded.AddRange(await CopySatelliteFilesAsync( - packageReader, - packagePathResolver, - packageSaveMode, - packageExtractionContext, - token)); - } - - return filesAdded; - } - /// /// Uses a copy function to install a package to a global packages directory. /// @@ -282,17 +215,17 @@ public static async Task InstallFromSourceAsync( throw new ArgumentNullException(nameof(versionFolderPathContext)); } - var versionFolderPathResolver = new VersionFolderPathResolver( + var packagePathResolver = new VersionFolderPathResolver( versionFolderPathContext.PackagesDirectory, versionFolderPathContext.IsLowercasePackagesDirectory); var packageIdentity = versionFolderPathContext.Package; var logger = versionFolderPathContext.Logger; - var targetPath = versionFolderPathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version); - var targetNuspec = versionFolderPathResolver.GetManifestFilePath(packageIdentity.Id, packageIdentity.Version); - var targetNupkg = versionFolderPathResolver.GetPackageFilePath(packageIdentity.Id, packageIdentity.Version); - var hashPath = versionFolderPathResolver.GetHashPath(packageIdentity.Id, packageIdentity.Version); + var targetPath = packagePathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version); + var targetNuspec = packagePathResolver.GetManifestFilePath(packageIdentity.Id, packageIdentity.Version); + var targetNupkg = packagePathResolver.GetPackageFilePath(packageIdentity.Id, packageIdentity.Version); + var hashPath = packagePathResolver.GetHashPath(packageIdentity.Id, packageIdentity.Version); logger.LogVerbose( $"Acquiring lock for the installation of {packageIdentity.Id} {packageIdentity.Version}"); @@ -430,192 +363,6 @@ public static async Task InstallFromSourceAsync( token: token); } - public static async Task InstallFromSourceAsync( - IPackageDownloader packageDownloader, - VersionFolderPathContext versionFolderPathContext, - CancellationToken token) - { - if (packageDownloader == null) - { - throw new ArgumentNullException(nameof(packageDownloader)); - } - - if (versionFolderPathContext == null) - { - throw new ArgumentNullException(nameof(versionFolderPathContext)); - } - - var versionFolderPathResolver = new VersionFolderPathResolver( - versionFolderPathContext.PackagesDirectory, - versionFolderPathContext.IsLowercasePackagesDirectory); - - var packageIdentity = versionFolderPathContext.Package; - var logger = versionFolderPathContext.Logger; - - var targetPath = versionFolderPathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version); - var targetNuspec = versionFolderPathResolver.GetManifestFilePath(packageIdentity.Id, packageIdentity.Version); - var targetNupkg = versionFolderPathResolver.GetPackageFilePath(packageIdentity.Id, packageIdentity.Version); - var hashPath = versionFolderPathResolver.GetHashPath(packageIdentity.Id, packageIdentity.Version); - - logger.LogVerbose( - $"Acquiring lock for the installation of {packageIdentity.Id} {packageIdentity.Version}"); - - // Acquire the lock on a nukpg before we extract it to prevent the race condition when multiple - // processes are extracting to the same destination simultaneously - return await ConcurrencyUtilities.ExecuteWithFileLockedAsync(targetNupkg, - action: async cancellationToken => - { - // If this is the first process trying to install the target nupkg, go ahead - // After this process successfully installs the package, all other processes - // waiting on this lock don't need to install it again. - if (!File.Exists(hashPath)) - { - logger.LogVerbose( - $"Acquired lock for the installation of {packageIdentity.Id} {packageIdentity.Version}"); - - logger.LogMinimal(string.Format( - CultureInfo.CurrentCulture, - Strings.Log_InstallingPackage, - packageIdentity.Id, - packageIdentity.Version)); - - cancellationToken.ThrowIfCancellationRequested(); - - // We do not stop the package extraction after this point - // based on CancellationToken, but things can still be stopped if the process is killed. - if (Directory.Exists(targetPath)) - { - // If we had a broken restore, clean out the files first - var info = new DirectoryInfo(targetPath); - - foreach (var file in info.GetFiles()) - { - file.Delete(); - } - - foreach (var dir in info.GetDirectories()) - { - dir.Delete(true); - } - } - else - { - Directory.CreateDirectory(targetPath); - } - - var targetTempNupkg = Path.Combine(targetPath, Path.GetRandomFileName()); - var tempHashPath = Path.Combine(targetPath, Path.GetRandomFileName()); - var packageSaveMode = versionFolderPathContext.PackageSaveMode; - - // Extract the nupkg - var copiedNupkg = await packageDownloader.CopyNupkgFileToAsync(targetTempNupkg, cancellationToken); - - if (packageSaveMode.HasFlag(PackageSaveMode.Nuspec)) - { - var nuspecFileNameFromReader = await packageDownloader.CoreReader.GetNuspecFileAsync(cancellationToken); - var packageFiles = new[] { nuspecFileNameFromReader }; - var packageFileExtractor = new PackageFileExtractor( - packageFiles, - XmlDocFileSaveMode.None); - var packageDirectoryPath = Path.GetDirectoryName(targetNuspec); - - var extractedNuspecFilePath = (await packageDownloader.CoreReader.CopyFilesAsync( - packageDirectoryPath, - packageFiles, - packageFileExtractor.ExtractPackageFile, - logger, - cancellationToken)) - .SingleOrDefault(); - - // CopyFilesAsync(...) just extracts files to a directory. - // We may have to fix up the casing of the .nuspec file name. - if (!string.IsNullOrEmpty(extractedNuspecFilePath)) - { - if (PathUtility.IsFileSystemCaseInsensitive) - { - var nuspecFileName = Path.GetFileName(targetNuspec); - var actualNuspecFileName = Path.GetFileName(extractedNuspecFilePath); - - if (!string.Equals(nuspecFileName, actualNuspecFileName, StringComparison.Ordinal)) - { - var tempNuspecFilePath = Path.Combine(packageDirectoryPath, Path.GetRandomFileName()); - - File.Move(extractedNuspecFilePath, tempNuspecFilePath); - File.Move(tempNuspecFilePath, targetNuspec); - } - } - else if (!File.Exists(targetNuspec)) - { - File.Move(extractedNuspecFilePath, targetNuspec); - } - } - } - - if (packageSaveMode.HasFlag(PackageSaveMode.Files)) - { - var hashFileName = Path.GetFileName(hashPath); - var packageFiles = (await packageDownloader.CoreReader.GetFilesAsync(cancellationToken)) - .Where(file => ShouldInclude(file, hashFileName)); - var packageFileExtractor = new PackageFileExtractor( - packageFiles, - versionFolderPathContext.XmlDocFileSaveMode); - await packageDownloader.CoreReader.CopyFilesAsync( - targetPath, - packageFiles, - packageFileExtractor.ExtractPackageFile, - logger, - token); - } - - var packageHash = await packageDownloader.GetPackageHashAsync("SHA512", cancellationToken); - - File.WriteAllText(tempHashPath, packageHash); - - // Now rename the tmp file - if (versionFolderPathContext.PackageSaveMode.HasFlag(PackageSaveMode.Nupkg)) - { - if (copiedNupkg) - { - // Dispose of it now because it is holding a lock on the temporary .nupkg file. - packageDownloader.Dispose(); - - File.Move(targetTempNupkg, targetNupkg); - } - } - else - { - try - { - File.Delete(targetTempNupkg); - } - catch (IOException ex) - { - logger.LogWarning(string.Format( - CultureInfo.CurrentCulture, - Strings.ErrorUnableToDeleteFile, - targetTempNupkg, - ex.Message)); - } - } - - // Note: PackageRepository relies on the hash file being written out as the - // final operation as part of a package install to assume a package was fully installed. - // Rename the tmp hash file - File.Move(tempHashPath, hashPath); - - logger.LogVerbose($"Completed installation of {packageIdentity.Id} {packageIdentity.Version}"); - return true; - } - else - { - logger.LogVerbose("Lock not required - Package already installed " - + $"{packageIdentity.Id} {packageIdentity.Version}"); - return false; - } - }, - token: token); - } - private static bool ShouldInclude( string fullName, string hashFileName) diff --git a/src/NuGet.Core/NuGet.Packaging/PackagePathResolver.cs b/src/NuGet.Core/NuGet.Packaging/PackagePathResolver.cs index 4bf26910d62..3e43076e6cd 100644 --- a/src/NuGet.Core/NuGet.Packaging/PackagePathResolver.cs +++ b/src/NuGet.Core/NuGet.Packaging/PackagePathResolver.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -8,9 +8,6 @@ namespace NuGet.Packaging { - /// - /// A V2 path resolver. - /// public class PackagePathResolver { private readonly string _rootDirectory; @@ -50,16 +47,6 @@ public string GetPackageFileName(PackageIdentity packageIdentity) return fileNameBase.ToString(); } - public string GetPackageDownloadMarkerFileName(PackageIdentity packageIdentity) - { - var builder = new StringBuilder(); - - builder.Append(GetId(packageIdentity)); - builder.Append(PackagingCoreConstants.PackageDownloadMarkerFileExtension); - - return builder.ToString(); - } - public string GetManifestFileName(PackageIdentity packageIdentity) { return GetId(packageIdentity) + PackagingCoreConstants.NuspecExtension; diff --git a/src/NuGet.Core/NuGet.Packaging/PackageReaderBase.cs b/src/NuGet.Core/NuGet.Packaging/PackageReaderBase.cs index d4e997e2d79..be444cb0c62 100644 --- a/src/NuGet.Core/NuGet.Packaging/PackageReaderBase.cs +++ b/src/NuGet.Core/NuGet.Packaging/PackageReaderBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -22,9 +22,8 @@ namespace NuGet.Packaging public abstract class PackageReaderBase : IPackageCoreReader, IPackageContentReader, IAsyncPackageCoreReader, IAsyncPackageContentReader { private NuspecReader _nuspecReader; - - protected IFrameworkNameProvider FrameworkProvider { get; set; } - protected IFrameworkCompatibilityProvider CompatibilityProvider { get; set; } + private readonly IFrameworkNameProvider _frameworkProvider; + private readonly IFrameworkCompatibilityProvider _compatibilityProvider; /// /// Instantiates a new class. @@ -55,8 +54,8 @@ public PackageReaderBase(IFrameworkNameProvider frameworkProvider, IFrameworkCom throw new ArgumentNullException(nameof(compatibilityProvider)); } - FrameworkProvider = frameworkProvider; - CompatibilityProvider = compatibilityProvider; + _frameworkProvider = frameworkProvider; + _compatibilityProvider = compatibilityProvider; } #region IPackageCoreReader implementation @@ -98,9 +97,21 @@ public virtual Stream GetNuspec() public virtual string GetNuspecFile() { - var files = GetFiles(); + // Find all nuspecs in the root folder. + var nuspecPaths = GetFiles() + .Where(entryPath => PackageHelper.IsManifest(entryPath)) + .ToList(); + + if (nuspecPaths.Count == 0) + { + throw new PackagingException(Strings.MissingNuspec); + } + else if (nuspecPaths.Count > 1) + { + throw new PackagingException(Strings.MultipleNuspecFiles); + } - return GetNuspecFile(files); + return nuspecPaths.Single(); } /// @@ -123,47 +134,47 @@ public virtual NuspecReader NuspecReader #region IAsyncPackageCoreReader implementation - public virtual Task GetIdentityAsync(CancellationToken cancellationToken) + public Task GetIdentityAsync(CancellationToken cancellationToken) { return Task.FromResult(GetIdentity()); } - public virtual Task GetMinClientVersionAsync(CancellationToken cancellationToken) + public Task GetMinClientVersionAsync(CancellationToken cancellationToken) { return Task.FromResult(GetMinClientVersion()); } - public virtual Task> GetPackageTypesAsync(CancellationToken cancellationToken) + public Task> GetPackageTypesAsync(CancellationToken cancellationToken) { return Task.FromResult(GetPackageTypes()); } - public virtual Task GetStreamAsync(string path, CancellationToken cancellationToken) + public Task GetStreamAsync(string path, CancellationToken cancellationToken) { return Task.FromResult(GetStream(path)); } - public virtual Task> GetFilesAsync(CancellationToken cancellationToken) + public Task> GetFilesAsync(CancellationToken cancellationToken) { return Task.FromResult(GetFiles()); } - public virtual Task> GetFilesAsync(string folder, CancellationToken cancellationToken) + public Task> GetFilesAsync(string folder, CancellationToken cancellationToken) { return Task.FromResult(GetFiles(folder)); } - public virtual Task GetNuspecAsync(CancellationToken cancellationToken) + public Task GetNuspecAsync(CancellationToken cancellationToken) { return Task.FromResult(GetNuspec()); } - public virtual Task GetNuspecFileAsync(CancellationToken cancellationToken) + public Task GetNuspecFileAsync(CancellationToken cancellationToken) { return Task.FromResult(GetNuspecFile()); } - public virtual Task> CopyFilesAsync( + public Task> CopyFilesAsync( string destination, IEnumerable packageFiles, ExtractPackageFileDelegate extractFile, @@ -189,6 +200,26 @@ public void Dispose() #region IPackageContentReader implementation + /// + /// Frameworks mentioned in the package. + /// + public virtual IEnumerable GetSupportedFrameworks() + { + var frameworks = new HashSet(new NuGetFrameworkFullComparer()); + + frameworks.UnionWith(GetLibItems().Select(g => g.TargetFramework)); + + frameworks.UnionWith(GetBuildItems().Select(g => g.TargetFramework)); + + frameworks.UnionWith(GetContentItems().Select(g => g.TargetFramework)); + + frameworks.UnionWith(GetToolItems().Select(g => g.TargetFramework)); + + frameworks.UnionWith(GetFrameworkItems().Select(g => g.TargetFramework)); + + return frameworks.Where(f => !f.IsUnsupported).OrderBy(f => f, new NuGetFrameworkSorter()); + } + public virtual IEnumerable GetFrameworkItems() { return NuspecReader.GetFrameworkReferenceGroups(); @@ -270,8 +301,8 @@ public virtual IEnumerable GetReferenceItems() var referenceGroup = NuGetFrameworkUtility.GetNearest( items: referenceGroups, framework: fileGroup.TargetFramework, - frameworkMappings: FrameworkProvider, - compatibilityProvider: CompatibilityProvider); + frameworkMappings: _frameworkProvider, + compatibilityProvider: _compatibilityProvider); if (referenceGroup == null) { @@ -354,31 +385,6 @@ public virtual Task> GetPackageDependenciesA #endregion - /// - /// Frameworks mentioned in the package. - /// - public virtual IEnumerable GetSupportedFrameworks() - { - var frameworks = new HashSet(new NuGetFrameworkFullComparer()); - - frameworks.UnionWith(GetLibItems().Select(g => g.TargetFramework)); - - frameworks.UnionWith(GetBuildItems().Select(g => g.TargetFramework)); - - frameworks.UnionWith(GetContentItems().Select(g => g.TargetFramework)); - - frameworks.UnionWith(GetToolItems().Select(g => g.TargetFramework)); - - frameworks.UnionWith(GetFrameworkItems().Select(g => g.TargetFramework)); - - return frameworks.Where(f => !f.IsUnsupported).OrderBy(f => f, new NuGetFrameworkSorter()); - } - - public virtual Task> GetSupportedFrameworksAsync(CancellationToken cancellationToken) - { - return Task.FromResult(GetSupportedFrameworks()); - } - public virtual bool IsServiceable() { return NuspecReader.IsServiceable(); @@ -436,7 +442,7 @@ protected IEnumerable GetFileGroups(string folder) } } - protected NuGetFramework GetFrameworkFromPath(string path, bool allowSubFolders = false) + private NuGetFramework GetFrameworkFromPath(string path, bool allowSubFolders = false) { var framework = NuGetFramework.AnyFramework; @@ -451,7 +457,7 @@ protected NuGetFramework GetFrameworkFromPath(string path, bool allowSubFolders NuGetFramework parsedFramework; try { - parsedFramework = NuGetFramework.ParseFolder(folderName, FrameworkProvider); + parsedFramework = NuGetFramework.ParseFolder(folderName, _frameworkProvider); } catch (ArgumentException e) { @@ -478,7 +484,7 @@ protected NuGetFramework GetFrameworkFromPath(string path, bool allowSubFolders /// /// only packageId.targets and packageId.props should be used from the build folder /// - protected static bool IsAllowedBuildFile(string packageId, string path) + private static bool IsAllowedBuildFile(string packageId, string path) { var file = Path.GetFileName(path); @@ -489,7 +495,7 @@ protected static bool IsAllowedBuildFile(string packageId, string path) /// /// True only for assemblies that should be added as references to msbuild projects /// - protected static bool IsReferenceAssembly(string path) + private static bool IsReferenceAssembly(string path) { var result = false; @@ -513,34 +519,5 @@ protected static bool IsReferenceAssembly(string path) return result; } - - protected static string GetNuspecFile(IEnumerable files) - { - // Find all nuspecs in the root folder. - var nuspecPaths = files - .Where(entryPath => PackageHelper.IsManifest(entryPath)) - .ToList(); - - if (nuspecPaths.Count == 0) - { - throw new PackagingException(Strings.MissingNuspec); - } - else if (nuspecPaths.Count > 1) - { - throw new PackagingException(Strings.MultipleNuspecFiles); - } - - return nuspecPaths.Single(); - } - - public virtual Task GetNuspecReaderAsync(CancellationToken cancellationToken) - { - return Task.FromResult(NuspecReader); - } - - public virtual Task CopyNupkgAsync(string nupkgFilePath, CancellationToken cancellationToken) - { - throw new NotImplementedException(); - } } } \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Packaging/VersionFolderPathResolver.cs b/src/NuGet.Core/NuGet.Packaging/VersionFolderPathResolver.cs index 23d97a42cef..95484df01c7 100644 --- a/src/NuGet.Core/NuGet.Packaging/VersionFolderPathResolver.cs +++ b/src/NuGet.Core/NuGet.Packaging/VersionFolderPathResolver.cs @@ -1,53 +1,43 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; using System.IO; -using NuGet.Packaging.Core; using NuGet.Versioning; namespace NuGet.Packaging { - /// - /// A V3 path resolver. - /// public class VersionFolderPathResolver { /// - /// Gets the packages directory root folder. + /// Packages directory root folder. /// public string RootPath { get; } /// - /// Gets a flag indicating whether or not package ID's and versions are made lowercase. + /// True if package id and versions are made lowercase. /// public bool IsLowerCase { get; } /// - /// Initializes a new class. + /// VersionFolderPathResolver /// - /// The packages directory root folder. + /// Packages directory root folder. public VersionFolderPathResolver(string rootPath) : this(rootPath, isLowercase: true) { } /// - /// Initializes a new class. + /// VersionFolderPathResolver /// - /// The packages directory root folder. - /// true if package ID's and versions are made lowercase; - /// otherwise false. + /// Packages directory root folder. + /// True if package id and versions are made lowercase. public VersionFolderPathResolver(string rootPath, bool isLowercase) { RootPath = rootPath; IsLowerCase = isLowercase; } - /// - /// Gets the package install path. - /// - /// The package ID. - /// The package version. - /// The package install path. public string GetInstallPath(string packageId, NuGetVersion version) { return Path.Combine( @@ -55,11 +45,6 @@ public string GetInstallPath(string packageId, NuGetVersion version) GetPackageDirectory(packageId, version)); } - /// - /// Gets the package version list path. - /// - /// The package ID. - /// The package version list path. public string GetVersionListPath(string packageId) { return Path.Combine( @@ -67,12 +52,6 @@ public string GetVersionListPath(string packageId) GetVersionListDirectory(packageId)); } - /// - /// Gets the package file path. - /// - /// The package ID. - /// The package version. - /// The package file path. public string GetPackageFilePath(string packageId, NuGetVersion version) { return Path.Combine( @@ -80,12 +59,6 @@ public string GetPackageFilePath(string packageId, NuGetVersion version) GetPackageFileName(packageId, version)); } - /// - /// Gets the manifest file path. - /// - /// The package ID. - /// The package version. - /// The manifest file path. public string GetManifestFilePath(string packageId, NuGetVersion version) { packageId = Normalize(packageId); @@ -94,12 +67,6 @@ public string GetManifestFilePath(string packageId, NuGetVersion version) GetManifestFileName(packageId, version)); } - /// - /// Gets the hash file path. - /// - /// The package ID. - /// The package version. - /// The hash file path. public string GetHashPath(string packageId, NuGetVersion version) { return Path.Combine( @@ -107,33 +74,16 @@ public string GetHashPath(string packageId, NuGetVersion version) GetHashFileName(packageId, version)); } - /// - /// Gets the hash file name. - /// - /// The package ID. - /// The package version. - /// The hash file name. public string GetHashFileName(string packageId, NuGetVersion version) { - return $"{Normalize(packageId)}.{Normalize(version)}{PackagingCoreConstants.HashFileExtension}"; + return $"{Normalize(packageId)}.{Normalize(version)}.nupkg.sha512"; } - /// - /// Gets the version list directory. - /// - /// The package ID. - /// The version list directory. public string GetVersionListDirectory(string packageId) { return Normalize(packageId); } - /// - /// Gets the package directory. - /// - /// The package ID. - /// The package version. - /// The package directory. public string GetPackageDirectory(string packageId, NuGetVersion version) { return Path.Combine( @@ -141,36 +91,14 @@ public string GetPackageDirectory(string packageId, NuGetVersion version) Normalize(version)); } - /// - /// Gets the package file name. - /// - /// The package ID. - /// The package version. - /// The package file name. public string GetPackageFileName(string packageId, NuGetVersion version) { - return $"{Normalize(packageId)}.{Normalize(version)}{PackagingCoreConstants.NupkgExtension}"; - } - - /// - /// Gets the package download marker file name. - /// - /// The package ID. - /// The package download marker file name. - public string GetPackageDownloadMarkerFileName(string packageId) - { - return $"{Normalize(packageId)}{PackagingCoreConstants.PackageDownloadMarkerFileExtension}"; + return $"{Normalize(packageId)}.{Normalize(version)}.nupkg"; } - /// - /// Gets the manifest file name. - /// - /// The package ID. - /// The package version. - /// The manifest file name. public string GetManifestFileName(string packageId, NuGetVersion version) { - return $"{Normalize(packageId)}{PackagingCoreConstants.NuspecExtension}"; + return $"{Normalize(packageId)}.nuspec"; } private string Normalize(NuGetVersion version) @@ -195,4 +123,4 @@ private string Normalize(string packageId) return packageId; } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.Protocol/Converters/SemanticVersionConverter.cs b/src/NuGet.Core/NuGet.Protocol/Converters/SemanticVersionConverter.cs deleted file mode 100644 index 209e4e25eb3..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Converters/SemanticVersionConverter.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using NuGet.Versioning; - -namespace NuGet.Protocol -{ - /// - /// A SemanticVersion JSON converter. - /// - public sealed class SemanticVersionConverter : JsonConverter - { - /// - /// Gets a flag indicating whether or not a type is convertible. - /// - /// An object type to check. - /// true if is convertible; otherwise false. - public override bool CanConvert(Type objectType) => objectType == typeof(SemanticVersion); - - /// - /// Reads the JSON representation of the object. - /// - /// A JSON reader. - /// The type of the object. - /// The existing value of the object. - /// A serializer. - /// A object. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - return reader.TokenType != JsonToken.Null ? SemanticVersion.Parse(serializer.Deserialize(reader)) : null; - } - - /// - /// Writes the JSON representation of the object. - /// - /// A JSON writer. - /// A value to serialize. - /// A serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - var semanticVersion = (SemanticVersion)value; - - serializer.Serialize(writer, semanticVersion.ToString()); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/DownloadResourceResult.cs b/src/NuGet.Core/NuGet.Protocol/DownloadResourceResult.cs index 5808e005789..351c8b3f932 100644 --- a/src/NuGet.Core/NuGet.Protocol/DownloadResourceResult.cs +++ b/src/NuGet.Core/NuGet.Protocol/DownloadResourceResult.cs @@ -10,38 +10,22 @@ namespace NuGet.Protocol.Core.Types /// /// The result of . /// - public sealed class DownloadResourceResult : IDisposable + public class DownloadResourceResult : IDisposable { - private bool _isDisposed; private readonly Stream _stream; private readonly PackageReaderBase _packageReader; private readonly string _packageSource; - /// - /// Initializes a new class. - /// - /// A download resource result status. - /// Thrown if - /// is either or - /// . public DownloadResourceResult(DownloadResourceResultStatus status) { - if (status == DownloadResourceResultStatus.Available || - status == DownloadResourceResultStatus.AvailableWithoutStream) + if (status == DownloadResourceResultStatus.Available) { - throw new ArgumentException("A stream should be provided when the result is available.", - nameof(status)); + throw new ArgumentException("A stream should be provided when the result is available."); } Status = status; } - /// - /// Initializes a new class. - /// - /// A package stream. - /// A package source. - /// Thrown if is null. public DownloadResourceResult(Stream stream, string source) { if (stream == null) @@ -54,92 +38,44 @@ public DownloadResourceResult(Stream stream, string source) _packageSource = source; } - /// - /// Initializes a new class. - /// - /// A package stream. - /// Thrown if is null. public DownloadResourceResult(Stream stream) : this(stream, source: null) { } - /// - /// Initializes a new class. - /// - /// A package stream. - /// A package reader. - /// A package source. - /// Thrown if is null. public DownloadResourceResult(Stream stream, PackageReaderBase packageReader, string source) : this(stream, source) { _packageReader = packageReader; } - /// - /// Initializes a new class. - /// - /// A package stream. - /// A package reader. - /// Thrown if is null. public DownloadResourceResult(Stream stream, PackageReaderBase packageReader) : this(stream, packageReader, source: null) { } - /// - /// Initializes a new class. - /// - /// A package reader. - /// A package source. - /// Thrown if is null. - public DownloadResourceResult(PackageReaderBase packageReader, string source) - { - if (packageReader == null) - { - throw new ArgumentNullException(nameof(packageReader)); - } - - Status = DownloadResourceResultStatus.AvailableWithoutStream; - _packageReader = packageReader; - _packageSource = source; - } - public DownloadResourceResultStatus Status { get; } /// /// Gets the package . /// - /// The value may be null. public Stream PackageStream => _stream; /// /// Gets the source containing this package, if not from cache /// - /// The value may be null. public string PackageSource => _packageSource; /// /// Gets the for the package. /// - /// The value may be null. + /// This property can be null. public PackageReaderBase PackageReader => _packageReader; - /// - /// Disposes of this instance. - /// public void Dispose() { - if (!_isDisposed) - { - _stream?.Dispose(); - _packageReader?.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } + _stream?.Dispose(); + _packageReader?.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.Protocol/DownloadResourceResultStatus.cs b/src/NuGet.Core/NuGet.Protocol/DownloadResourceResultStatus.cs index 68860d9d6af..8a2390d17b0 100644 --- a/src/NuGet.Core/NuGet.Protocol/DownloadResourceResultStatus.cs +++ b/src/NuGet.Core/NuGet.Protocol/DownloadResourceResultStatus.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace NuGet.Protocol.Core.Types @@ -6,7 +6,6 @@ namespace NuGet.Protocol.Core.Types public enum DownloadResourceResultStatus { Available, - AvailableWithoutStream, NotFound, Cancelled } diff --git a/src/NuGet.Core/NuGet.Protocol/FactoryExtensionsV3.cs b/src/NuGet.Core/NuGet.Protocol/FactoryExtensionsV3.cs index cea0452d652..1a1bc29b7a7 100644 --- a/src/NuGet.Core/NuGet.Protocol/FactoryExtensionsV3.cs +++ b/src/NuGet.Core/NuGet.Protocol/FactoryExtensionsV3.cs @@ -30,7 +30,6 @@ public static IEnumerable> GetCoreV3(this Repositor { yield return new Lazy(() => new FeedTypeResourceProvider()); yield return new Lazy(() => new DependencyInfoResourceV3Provider()); - yield return new Lazy(() => new DownloadResourcePluginProvider()); yield return new Lazy(() => new DownloadResourceV3Provider()); yield return new Lazy(() => new MetadataResourceV3Provider()); yield return new Lazy(() => new RawSearchResourceV3Provider()); @@ -40,7 +39,6 @@ public static IEnumerable> GetCoreV3(this Repositor yield return new Lazy(() => new ODataServiceDocumentResourceV2Provider()); yield return new Lazy(() => new HttpHandlerResourceV3Provider()); yield return new Lazy(() => new HttpSourceResourceProvider()); - yield return new Lazy(() => new PluginFindPackageByIdResourceProvider()); yield return new Lazy(() => new HttpFileSystemBasedFindPackageByIdResourceProvider()); yield return new Lazy(() => new RemoteV3FindPackageByIdResourceProvider()); yield return new Lazy(() => new RemoteV2FindPackageByIdResourceProvider()); @@ -60,7 +58,6 @@ public static IEnumerable> GetCoreV3(this Repositor yield return new Lazy(() => new PackageMetadataResourceV3Provider()); yield return new Lazy(() => new AutoCompleteResourceV2FeedProvider()); yield return new Lazy(() => new AutoCompleteResourceV3Provider()); - yield return new Lazy(() => new PluginResourceProvider()); // Local repository providers yield return new Lazy(() => new FindLocalPackagesResourceUnzippedProvider()); diff --git a/src/NuGet.Core/NuGet.Protocol/LocalRepositories/LocalV2FindPackageByIdResource.cs b/src/NuGet.Core/NuGet.Protocol/LocalRepositories/LocalV2FindPackageByIdResource.cs index a54c4a8b97f..1ab05ac26d7 100644 --- a/src/NuGet.Core/NuGet.Protocol/LocalRepositories/LocalV2FindPackageByIdResource.cs +++ b/src/NuGet.Core/NuGet.Protocol/LocalRepositories/LocalV2FindPackageByIdResource.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -19,9 +19,6 @@ namespace NuGet.Protocol { - /// - /// A resource capable of fetching packages, package versions and package dependency information. - /// public class LocalV2FindPackageByIdResource : FindPackageByIdResource { private readonly ConcurrentDictionary> _packageInfoCache @@ -29,130 +26,38 @@ private readonly ConcurrentDictionary> _ private readonly string _source; - /// - /// Initializes a new class. - /// - /// A package source. - /// Thrown if - /// is null. public LocalV2FindPackageByIdResource(PackageSource packageSource) { - if (packageSource == null) - { - throw new ArgumentNullException(nameof(packageSource)); - } - var rootDirInfo = LocalFolderUtility.GetAndVerifyRootDirectory(packageSource.Source); _source = rootDirInfo.FullName; } - /// - /// Asynchronously gets all package versions for a package ID. - /// - /// A package ID. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override Task> GetAllVersionsAsync( string id, SourceCacheContext cacheContext, ILogger logger, - CancellationToken cancellationToken) + CancellationToken token) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - var infos = GetPackageInfos(id, cacheContext, logger); - return Task.FromResult(infos.Select(p => p.Identity.Version)); } - /// - /// Asynchronously copies a .nupkg to a stream. - /// - /// A package ID. - /// A package version. - /// A destination stream. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// indicating whether or not the .nupkg file was copied. - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override async Task CopyNupkgToStreamAsync( string id, NuGetVersion version, Stream destination, SourceCacheContext cacheContext, ILogger logger, - CancellationToken cancellationToken) + CancellationToken token) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } - - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - var info = GetPackageInfo(id, version, cacheContext, logger); if (info != null) { using (var fileStream = File.OpenRead(info.Path)) { - await fileStream.CopyToAsync(destination, cancellationToken); + await fileStream.CopyToAsync(destination, token); return true; } } @@ -160,53 +65,13 @@ public override async Task CopyNupkgToStreamAsync( return false; } - /// - /// Asynchronously gets dependency information for a specific package. - /// - /// A package id. - /// A package version. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override Task GetDependencyInfoAsync( string id, NuGetVersion version, SourceCacheContext cacheContext, ILogger logger, - CancellationToken cancellationToken) + CancellationToken token) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - FindPackageByIdDependencyInfo dependencyInfo = null; var info = GetPackageInfo(id, version, cacheContext, logger); if (info != null) @@ -217,68 +82,12 @@ public override Task GetDependencyInfoAsync( return Task.FromResult(dependencyInfo); } - private LocalPackageInfo GetPackageInfo( - string id, - NuGetVersion version, - SourceCacheContext cacheContext, - ILogger logger) + private LocalPackageInfo GetPackageInfo(string id, NuGetVersion version, SourceCacheContext cacheContext, ILogger logger) { - return GetPackageInfos(id, cacheContext, logger) - .FirstOrDefault(package => package.Identity.Version == version); + return GetPackageInfos(id, cacheContext, logger).FirstOrDefault(package => package.Identity.Version == version); } - /// - /// Asynchronously gets a package downloader for a package identity. - /// - /// A package identity. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an . - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. - public override Task GetPackageDownloaderAsync( - PackageIdentity packageIdentity, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken) - { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var packageInfo = GetPackageInfo(packageIdentity.Id, packageIdentity.Version, cacheContext, logger); - IPackageDownloader packageDownloader = null; - - if (packageInfo != null) - { - packageDownloader = new LocalPackageArchiveDownloader(packageInfo.Path, packageInfo.Identity, logger); - } - - return Task.FromResult(packageDownloader); - } - - private IReadOnlyList GetPackageInfos( - string id, - SourceCacheContext cacheContext, - ILogger logger) + private IReadOnlyList GetPackageInfos(string id, SourceCacheContext cacheContext, ILogger logger) { IReadOnlyList results = null; @@ -347,4 +156,4 @@ private IReadOnlyList GetPackageInfosCore(string id, ILogger l return result; } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.Protocol/LocalRepositories/LocalV3FindPackageByIdResource.cs b/src/NuGet.Core/NuGet.Protocol/LocalRepositories/LocalV3FindPackageByIdResource.cs index bd7fce515cb..6c0b1627f03 100644 --- a/src/NuGet.Core/NuGet.Protocol/LocalRepositories/LocalV3FindPackageByIdResource.cs +++ b/src/NuGet.Core/NuGet.Protocol/LocalRepositories/LocalV3FindPackageByIdResource.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -19,9 +19,6 @@ namespace NuGet.Protocol { - /// - /// A resource capable of fetching packages, package versions and package dependency information. - /// public class LocalV3FindPackageByIdResource : FindPackageByIdResource { // Use cache insensitive compare for windows @@ -31,122 +28,36 @@ private readonly ConcurrentDictionary> _cache private readonly string _source; private readonly VersionFolderPathResolver _resolver; - /// - /// Initializes a new class. - /// - /// A package source. - /// Thrown if - /// is null. - public LocalV3FindPackageByIdResource(PackageSource packageSource) + public LocalV3FindPackageByIdResource(PackageSource source) { - if (packageSource == null) + if (source == null) { - throw new ArgumentNullException(nameof(packageSource)); + throw new ArgumentNullException(nameof(source)); } - var rootDirInfo = LocalFolderUtility.GetAndVerifyRootDirectory(packageSource.Source); + var rootDirInfo = LocalFolderUtility.GetAndVerifyRootDirectory(source.Source); _source = rootDirInfo.FullName; _resolver = new VersionFolderPathResolver(_source); } - /// - /// Asynchronously gets all package versions for a package ID. - /// - /// A package ID. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override Task> GetAllVersionsAsync( string id, SourceCacheContext cacheContext, ILogger logger, - CancellationToken cancellationToken) + CancellationToken token) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - return Task.FromResult(GetVersions(id, cacheContext, logger).AsEnumerable()); } - /// - /// Asynchronously copies a .nupkg to a stream. - /// - /// A package ID. - /// A package version. - /// A destination stream. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// indicating whether or not the .nupkg file was copied. - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override async Task CopyNupkgToStreamAsync( string id, NuGetVersion version, Stream destination, SourceCacheContext cacheContext, ILogger logger, - CancellationToken cancellationToken) + CancellationToken token) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } - - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - var matchedVersion = GetVersion(id, version, cacheContext, logger); if (matchedVersion != null) @@ -155,7 +66,7 @@ public override async Task CopyNupkgToStreamAsync( using (var fileStream = File.OpenRead(packagePath)) { - await fileStream.CopyToAsync(destination, cancellationToken); + await fileStream.CopyToAsync(destination, token); return true; } } @@ -163,53 +74,13 @@ public override async Task CopyNupkgToStreamAsync( return false; } - /// - /// Asynchronously gets dependency information for a specific package. - /// - /// A package id. - /// A package version. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override Task GetDependencyInfoAsync( string id, NuGetVersion version, SourceCacheContext cacheContext, ILogger logger, - CancellationToken cancellationToken) + CancellationToken token) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - var matchedVersion = GetVersion(id, version, cacheContext, logger); FindPackageByIdDependencyInfo dependencyInfo = null; if (matchedVersion != null) @@ -217,68 +88,17 @@ public override Task GetDependencyInfoAsync( var identity = new PackageIdentity(id, matchedVersion); dependencyInfo = ProcessNuspecReader( - id, - matchedVersion, - nuspecReader => - { - return GetDependencyInfo(nuspecReader); - }); + id, + matchedVersion, + nuspecReader => + { + return GetDependencyInfo(nuspecReader); + }); } return Task.FromResult(dependencyInfo); } - /// - /// Asynchronously gets a package downloader for a package identity. - /// - /// A package identity. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an . - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. - public override Task GetPackageDownloaderAsync( - PackageIdentity packageIdentity, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken) - { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var matchedVersion = GetVersion(packageIdentity.Id, packageIdentity.Version, cacheContext, logger); - IPackageDownloader packageDependency = null; - - if (matchedVersion != null) - { - var packagePath = _resolver.GetPackageFilePath(packageIdentity.Id, matchedVersion); - var matchedPackageIdentity = new PackageIdentity(packageIdentity.Id, matchedVersion); - - packageDependency = new LocalPackageArchiveDownloader(packagePath, matchedPackageIdentity, logger); - } - - return Task.FromResult(packageDependency); - } - private T ProcessNuspecReader(string id, NuGetVersion version, Func process) { var nuspecPath = _resolver.GetManifestFilePath(id, version); @@ -381,4 +201,4 @@ private List GetVersionsCore(string id, ILogger logger) return versions; } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.Protocol/NuGet.Protocol.csproj b/src/NuGet.Core/NuGet.Protocol/NuGet.Protocol.csproj index 06d0071eba1..5d0a87729cc 100644 --- a/src/NuGet.Core/NuGet.Protocol/NuGet.Protocol.csproj +++ b/src/NuGet.Core/NuGet.Protocol/NuGet.Protocol.csproj @@ -17,10 +17,6 @@ net45 - - - - diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/AutomaticProgressReporter.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/AutomaticProgressReporter.cs deleted file mode 100644 index 3a421b7357c..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/AutomaticProgressReporter.cs +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// An automatic progress reporter. - /// - public sealed class AutomaticProgressReporter : IDisposable - { - private readonly CancellationToken _cancellationToken; - private readonly CancellationTokenSource _cancellationTokenSource; - private readonly IConnection _connection; - private bool _isDisposed; - private readonly Message _request; - private readonly SemaphoreSlim _semaphore; - private readonly Timer _timer; - - private AutomaticProgressReporter( - IConnection connection, - Message request, - TimeSpan interval, - CancellationToken cancellationToken) - { - _connection = connection; - _request = request; - _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - _cancellationToken = _cancellationTokenSource.Token; - _semaphore = new SemaphoreSlim(initialCount: 1, maxCount: 1); - _timer = new Timer(OnTimer, state: null, dueTime: interval, period: interval); - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (!_isDisposed) - { - try - { - _semaphore.Wait(_cancellationToken); - } - catch (OperationCanceledException) - { - } - catch (ObjectDisposedException) - { - } - - try - { - using (_cancellationTokenSource) - { - _cancellationTokenSource.Cancel(); - } - } - catch (Exception) - { - } - - try - { - // The timer queues callbacks for execution by thread pool threads, so it is possible for a timer - // callback to be fired after Dispose() has been called. - // The Dispose(WaitHandle) overload, which should handle this race condition, is not available - // until .NET Core 2.0. Until then synchronization is required to ensure that a timer callback - // does not fire after Dispose(). Otherwise, a progress notification might be sent after a - // response, which would be a fatal plugin protocol error. - _timer.Dispose(); - - // Do not dispose of _connection. It is still in use by a plugin. - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - finally - { - try - { - _semaphore.Dispose(); - } - catch (Exception) - { - } - } - } - } - - /// - /// Creates a new class. - /// - /// This class does not take ownership of and dispose of . - /// A connection. - /// A request. - /// A progress interval. - /// A cancellation token. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is either less than or greater than - /// . - /// Thrown if - /// is cancelled. - public static AutomaticProgressReporter Create( - IConnection connection, - Message request, - TimeSpan interval, - CancellationToken cancellationToken) - { - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } - - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (!TimeoutUtilities.IsValid(interval)) - { - throw new ArgumentOutOfRangeException( - nameof(interval), - interval, - Strings.Plugin_TimeoutOutOfRange); - } - - cancellationToken.ThrowIfCancellationRequested(); - - return new AutomaticProgressReporter( - connection, - request, - interval, - cancellationToken); - } - - private void OnTimer(object state) - { - try - { - _semaphore.Wait(_cancellationToken); - } - catch (OperationCanceledException) - { - return; - } - catch (ObjectDisposedException) - { - return; - } - - if (_isDisposed) - { - return; - } - - Task.Run(async () => - { - // Top-level exception handler for a worker pool thread. - try - { - var progress = MessageUtilities.Create( - _request.RequestId, - MessageType.Progress, - _request.Method, - new Progress()); - - await _connection.SendAsync(progress, _cancellationToken); - } - catch (Exception) - { - } - finally - { - _semaphore.Release(); - } - }, - _cancellationToken); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Connection.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Connection.cs deleted file mode 100644 index a3e91a98791..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Connection.cs +++ /dev/null @@ -1,268 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Versioning; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a bidirectional channel between a NuGet client and a plugin. - /// - public sealed class Connection : IConnection - { - private bool _isDisposed; - private readonly IReceiver _receiver; - private readonly ISender _sender; - - private int _state = (int)ConnectionState.ReadyToConnect; - - /// - /// The connection state. - /// - public ConnectionState State => (ConnectionState)_state; - - /// - /// Occurs when an unrecoverable fault has been caught. - /// - public event EventHandler Faulted; - - /// - /// Occurs when a message has been received. - /// - public event EventHandler MessageReceived; - - /// - /// Gets the message dispatcher. - /// - public IMessageDispatcher MessageDispatcher { get; } - - /// - /// Gets the connection options - /// - public ConnectionOptions Options { get; } - - /// - /// Gets the negotiated protocol version, or null if not yet connected. - /// - public SemanticVersion ProtocolVersion { get; private set; } - - /// - /// Instantiates a new instance of the class. - /// - /// A message dispatcher. - /// A sender. - /// A receiver. - /// Connection options. - /// Thrown if is null. - /// Thrown if is null. - /// Thrown if is null. - /// Thrown if is null. - public Connection(IMessageDispatcher dispatcher, ISender sender, IReceiver receiver, ConnectionOptions options) - { - if (dispatcher == null) - { - throw new ArgumentNullException(nameof(dispatcher)); - } - - if (sender == null) - { - throw new ArgumentNullException(nameof(sender)); - } - - if (receiver == null) - { - throw new ArgumentNullException(nameof(receiver)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - MessageDispatcher = dispatcher; - _sender = sender; - _receiver = receiver; - Options = options; - - MessageDispatcher.SetConnection(this); - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (!_isDisposed) - { - Close(); - - _receiver.Dispose(); - _sender.Dispose(); - MessageDispatcher.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - /// - /// Closes the connection. - /// - /// This does not call . - public void Close() - { - if (_state != (int)ConnectionState.Closed) - { - _state = (int)ConnectionState.Closing; - - _receiver.MessageReceived -= OnMessageReceived; - _receiver.Faulted -= OnFaulted; - - _receiver.Close(); - _sender.Close(); - MessageDispatcher.Close(); - - _state = (int)ConnectionState.Closed; - } - } - - /// - /// Asynchronously connects and handshakes with a remote target. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is cancelled. - /// Thrown if the method has been called already. - public async Task ConnectAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - if (State != ConnectionState.ReadyToConnect) - { - throw new InvalidOperationException(Strings.Plugin_ConnectionAlreadyStarted); - } - - _state = (int)ConnectionState.Connecting; - - _receiver.MessageReceived += OnMessageReceived; - _receiver.Faulted += OnFaulted; - - using (var symmetricHandshake = new SymmetricHandshake( - this, - Options.HandshakeTimeout, - Options.ProtocolVersion, - Options.MinimumProtocolVersion)) - { - _sender.Connect(); - _receiver.Connect(); - - _state = (int)ConnectionState.Handshaking; - - try - { - ProtocolVersion = await symmetricHandshake.HandshakeAsync(cancellationToken); - } - catch (Exception) - { - _state = (int)ConnectionState.FailedToHandshake; - - throw; - } - - if (ProtocolVersion == null) - { - _state = (int)ConnectionState.FailedToHandshake; - - throw new ProtocolException(Strings.Plugin_HandshakeFailed); - } - - _state = (int)ConnectionState.Connected; - } - } - - /// - /// Asynchronously sends a message to the remote target. - /// - /// The message to be sent. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if is null. - /// Thrown if - /// is cancelled. - /// Thrown if not connected. - public async Task SendAsync(Message message, CancellationToken cancellationToken) - { - if (message == null) - { - throw new ArgumentNullException(nameof(message)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - if (State == ConnectionState.Closing || - State == ConnectionState.Closed) - { - return; - } - - if (_state < (int)ConnectionState.Connecting) - { - throw new InvalidOperationException(Strings.Plugin_NotConnected); - } - - await _sender.SendAsync(message, cancellationToken); - } - - /// - /// Asynchronously sends a message to the remote target and receives the target's response. - /// - /// The outbound payload type. - /// The inbound payload type. - /// The outbound message method. - /// The outbound message payload. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// from the target. - /// Thrown if - /// is cancelled. - /// Thrown if not connected. - public Task SendRequestAndReceiveResponseAsync( - MessageMethod method, - TOutbound payload, - CancellationToken cancellationToken) - where TOutbound : class - where TInbound : class - { - if (State == ConnectionState.Closing || - State == ConnectionState.Closed) - { - return Task.FromResult(null); - } - - if (_state < (int)ConnectionState.Connecting) - { - throw new InvalidOperationException(Strings.Plugin_NotConnected); - } - - cancellationToken.ThrowIfCancellationRequested(); - - return MessageDispatcher.DispatchRequestAsync(method, payload, cancellationToken); - } - - private void OnMessageReceived(object sender, MessageEventArgs e) - { - MessageReceived?.Invoke(this, e); - } - - private void OnFaulted(object sender, ProtocolErrorEventArgs e) - { - Faulted?.Invoke(this, e); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/ConnectionOptions.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/ConnectionOptions.cs deleted file mode 100644 index 59b4bebe8a4..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/ConnectionOptions.cs +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using NuGet.Versioning; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Plugin connection options. - /// - public sealed class ConnectionOptions - { - /// - /// Gets the plugin handshake timeout. - /// - public TimeSpan HandshakeTimeout { get; } - - /// - /// Gets the minimum plugin protocol version. - /// - public SemanticVersion MinimumProtocolVersion { get; } - - /// - /// Gets the plugin protocol version. - /// - public SemanticVersion ProtocolVersion { get; } - - /// - /// Gets the plugin request timeout. - /// - public TimeSpan RequestTimeout { get; private set; } - - /// - /// Instantiates a new class. - /// - /// The plugin protocol version. - /// The minimum plugin protocol version. - /// The plugin handshake timeout. - /// The plugin request timeout. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is less than . - /// Thrown if - /// is either less than or greater than - /// . - /// Thrown if - /// is either less than or greater than - /// . - public ConnectionOptions( - SemanticVersion protocolVersion, - SemanticVersion minimumProtocolVersion, - TimeSpan handshakeTimeout, - TimeSpan requestTimeout) - { - if (protocolVersion == null) - { - throw new ArgumentNullException(nameof(protocolVersion)); - } - - if (minimumProtocolVersion == null) - { - throw new ArgumentNullException(nameof(minimumProtocolVersion)); - } - - if (minimumProtocolVersion > protocolVersion) - { - throw new ArgumentOutOfRangeException( - nameof(protocolVersion), - protocolVersion, - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_ProtocolVersionOutOfRange, - nameof(protocolVersion), - nameof(minimumProtocolVersion))); - } - - if (!TimeoutUtilities.IsValid(handshakeTimeout)) - { - throw new ArgumentOutOfRangeException( - nameof(handshakeTimeout), - handshakeTimeout, - Strings.Plugin_TimeoutOutOfRange); - } - - if (!TimeoutUtilities.IsValid(requestTimeout)) - { - throw new ArgumentOutOfRangeException( - nameof(requestTimeout), - requestTimeout, - Strings.Plugin_TimeoutOutOfRange); - } - - ProtocolVersion = protocolVersion; - MinimumProtocolVersion = minimumProtocolVersion; - HandshakeTimeout = handshakeTimeout; - RequestTimeout = requestTimeout; - } - - /// - /// Sets a new request timeout. - /// - /// The new request timeout. - /// Thrown if - /// is either less than or greater than - /// . - public void SetRequestTimeout(TimeSpan requestTimeout) - { - if (!TimeoutUtilities.IsValid(requestTimeout)) - { - throw new ArgumentOutOfRangeException( - nameof(requestTimeout), - requestTimeout, - Strings.Plugin_TimeoutOutOfRange); - } - - RequestTimeout = requestTimeout; - } - - /// - /// Instantiates a class with default values. - /// - /// A . - public static ConnectionOptions CreateDefault() - { - return new ConnectionOptions( - protocolVersion: ProtocolConstants.CurrentVersion, - minimumProtocolVersion: ProtocolConstants.CurrentVersion, - handshakeTimeout: ProtocolConstants.HandshakeTimeout, - requestTimeout: ProtocolConstants.RequestTimeout); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/ConnectionState.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/ConnectionState.cs deleted file mode 100644 index 517814bc703..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/ConnectionState.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace NuGet.Protocol.Plugins -{ - /// - /// Connection states. - /// - /// Member order is significant. - /// For example, any connection state before - /// implies no connection. - public enum ConnectionState - { - FailedToHandshake, - Closing, - Closed, - ReadyToConnect, - Connecting, - Handshaking, - Connected - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/EmbeddedSignatureVerifier.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/EmbeddedSignatureVerifier.cs deleted file mode 100644 index 0f49e8da90f..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/EmbeddedSignatureVerifier.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using NuGet.Common; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Base class for embedded signature verifiers. - /// - public abstract class EmbeddedSignatureVerifier - { - /// - /// Checks if a file has a valid embedded signature. - /// - /// The path of a file to be checked. - /// true if the file has a valid signature; otherwise, false. - /// Thrown if - /// is either null or an empty string. - /// Thrown if the current platform is unsupported. - public abstract bool IsValid(string filePath); - - /// - /// Creates an embedded signature verifier for the current platform. - /// - /// An embedded signature verifier. - public static EmbeddedSignatureVerifier Create() - { - if (RuntimeEnvironmentHelper.IsWindows) - { - return new WindowsEmbeddedSignatureVerifier(); - } - - return new FallbackEmbeddedSignatureVerifier(); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/FallbackEmbeddedSignatureVerifier.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/FallbackEmbeddedSignatureVerifier.cs deleted file mode 100644 index e588338246e..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/FallbackEmbeddedSignatureVerifier.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A fallback embedded signature verifier for unsupported platforms. - /// - public sealed class FallbackEmbeddedSignatureVerifier : EmbeddedSignatureVerifier - { - /// - /// Checks if a file has a valid embedded signature. - /// - /// The path of a file to be checked. - /// true if the file has a valid signature; otherwise, false. - /// Thrown always. - public override bool IsValid(string filePath) - { - throw new PlatformNotSupportedException(); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/IConnection.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/IConnection.cs deleted file mode 100644 index 98126757276..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/IConnection.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Versioning; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a bidirectional channel between a NuGet client and a plugin. - /// - public interface IConnection : IDisposable - { - /// - /// Occurs when an unrecoverable fault has been caught. - /// - event EventHandler Faulted; - - /// - /// Occurs when a message has been received. - /// - event EventHandler MessageReceived; - - /// - /// Gets the message dispatcher. - /// - IMessageDispatcher MessageDispatcher { get; } - - /// - /// Gets the connection options - /// - ConnectionOptions Options { get; } - - /// - /// Gets the negotiated protocol version, or null if not yet connected. - /// - SemanticVersion ProtocolVersion { get; } - - /// - /// Closes the connection. - /// - /// This does not call . - void Close(); - - /// - /// Asynchronously sends a message to the remote target. - /// - /// The message to be sent. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if is null. - /// Thrown if - /// is cancelled. - /// Thrown if not connected. - Task SendAsync(Message message, CancellationToken cancellationToken); - - /// - /// Asynchronously sends a message to the remote target and receives the target's response. - /// - /// The outbound payload type. - /// The inbound payload type. - /// The outbound message method. - /// The outbound message payload. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// from the target. - /// Thrown if - /// is cancelled. - /// Thrown if not connected. - Task SendRequestAndReceiveResponseAsync( - MessageMethod method, - TOutbound payload, - CancellationToken cancellationToken) - where TOutbound : class - where TInbound : class; - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/IIdGenerator.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/IIdGenerator.cs deleted file mode 100644 index ddde64e8a47..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/IIdGenerator.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace NuGet.Protocol.Plugins -{ - /// - /// A unique identifier generator. - /// - public interface IIdGenerator - { - /// - /// Generates a new unique identifier. - /// - /// A unique identifier. - string GenerateUniqueId(); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/IMessageDispatcher.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/IMessageDispatcher.cs deleted file mode 100644 index dc43022f36f..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/IMessageDispatcher.cs +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A message dispatcher that maintains state for outstanding requests - /// and routes messages to configured request handlers. - /// - public interface IMessageDispatcher : IDisposable - { - /// - /// Gets the request handlers for use by the dispatcher. - /// - IRequestHandlers RequestHandlers { get; } - - /// - /// Closes the dispatcher. - /// - /// This does not call . - void Close(); - - /// - /// Creates a message. - /// - /// The message type. - /// The message method. - /// A message. - Message CreateMessage(MessageType type, MessageMethod method); - - /// - /// Creates a message. - /// - /// The message payload. - /// The message type. - /// The message method. - /// The message payload. - /// A message. - Message CreateMessage(MessageType type, MessageMethod method, TPayload payload) - where TPayload : class; - - /// - /// Asynchronously dispatches a cancellation request for the specified request. - /// - /// The request. - /// A cancellation token. - /// A task that represents the asynchronous operation. - Task DispatchCancelAsync(Message request, CancellationToken cancellationToken); - - /// - /// Asynchronously dispatches a fault notification for the specified request. - /// - /// The cancel request. - /// The fault payload. - /// A cancellation token. - /// A task that represents the asynchronous operation. - Task DispatchFaultAsync(Message request, Fault fault, CancellationToken cancellationToken); - - /// - /// Asynchronously dispatches a progress notification for the specified request. - /// - /// The request. - /// The progress payload. - /// A cancellation token. - /// A task that represents the asynchronous operation. - Task DispatchProgressAsync(Message request, Progress progress, CancellationToken cancellationToken); - - /// - /// Asynchronously dispatches a request. - /// - /// The request payload type. - /// The expected response payload type. - /// The request method. - /// The request payload. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// from the target. - Task DispatchRequestAsync( - MessageMethod method, - TOutbound payload, - CancellationToken cancellationToken) - where TOutbound : class - where TInbound : class; - - /// - /// Asynchronously dispatches a response. - /// - /// The request payload type. - /// The associated request. - /// The response payload. - /// A cancellation token. - /// A task that represents the asynchronous operation. - Task DispatchResponseAsync(Message request, TOutbound responsePayload, CancellationToken cancellationToken) - where TOutbound : class; - - /// - /// Sets the connection to be used for dispatching messages. - /// - /// A connection instance. Can be null. - void SetConnection(IConnection connection); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/IPlugin.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/IPlugin.cs deleted file mode 100644 index adb210a87e1..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/IPlugin.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a plugin. - /// - public interface IPlugin : IDisposable - { - /// - /// Occurs before the plugin closes. - /// - event EventHandler BeforeClose; - - /// - /// Occurs when the plugin has closed. - /// - event EventHandler Closed; - - /// - /// Gets the connection for the plugin. - /// - IConnection Connection { get; } - - /// - /// Gets the file path for the plugin. - /// - string FilePath { get; } - - /// - /// Gets the unique identifier for the plugin. - /// - string Id { get; } - - /// - /// Gets the name of the plugin. - /// - string Name { get; } - - /// - /// Closes the plugin. - /// - /// This does not call . - void Close(); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/IPluginDiscoverer.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/IPluginDiscoverer.cs deleted file mode 100644 index 387f76da538..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/IPluginDiscoverer.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A plugin discoverer. - /// - public interface IPluginDiscoverer : IDisposable - { - /// - /// Asynchronously discovers plugins. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is cancelled. - Task> DiscoverAsync(CancellationToken cancellationToken); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/IPluginFactory.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/IPluginFactory.cs deleted file mode 100644 index 828babf1594..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/IPluginFactory.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A plugin factory. - /// - public interface IPluginFactory : IDisposable - { - /// - /// Asynchronously gets an existing plugin instance or creates a new instance and connects to it. - /// - /// The file path of the plugin. - /// Command-line arguments to be supplied to the plugin. - /// Request handlers. - /// Connection options. - /// A cancellation token for the plugin's lifetime. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - /// Thrown if this object is disposed. - /// This is intended to be called by NuGet client tools. - Task GetOrCreateAsync( - string filePath, - IEnumerable arguments, - IRequestHandlers requestHandlers, - ConnectionOptions options, - CancellationToken sessionCancellationToken); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/IPluginMulticlientUtilities.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/IPluginMulticlientUtilities.cs deleted file mode 100644 index f84f2f7e006..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/IPluginMulticlientUtilities.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Plugin multiclient utilities. - /// - public interface IPluginMulticlientUtilities - { - /// - /// Asynchronously executes a task once per plugin lifetime per key. - /// - /// A key that identifies the task. - /// A function that returns a task. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null. - /// Thrown if - /// is cancelled. - Task DoOncePerPluginLifetimeAsync(string key, Func taskFunc, CancellationToken cancellationToken); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/IPluginProcess.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/IPluginProcess.cs deleted file mode 100644 index 29c8979e755..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/IPluginProcess.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a plugin process. - /// - public interface IPluginProcess : IDisposable - { - /// - /// Occurs when a line of output has been received. - /// - event EventHandler LineRead; - - /// - /// Occurs when a process exits. - /// - event EventHandler Exited; - - /// - /// Gets a value indicating whether the associated process has been terminated. - /// - bool HasExited { get; } - - /// - /// Asynchronously starts reading the standard output stream. - /// - void BeginReadLine(); - - /// - /// Cancels asynchronous reading of the standard output stream. - /// - void CancelRead(); - - /// - /// Immediately stops the associated process. - /// - void Kill(); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/IReceiver.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/IReceiver.cs deleted file mode 100644 index 70a69a42e23..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/IReceiver.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a unidirectional communications channel from a target. - /// - public interface IReceiver : IDisposable - { - /// - /// Occurs when an unrecoverable fault has been caught. - /// - event EventHandler Faulted; - - /// - /// Occurs when a message has been received. - /// - event EventHandler MessageReceived; - - /// - /// Closes the connection. - /// - /// This does not call . - void Close(); - - /// - /// Connects. - /// - /// Thrown if this object is disposed. - /// Thrown if this object is closed. - /// Thrown if this method has already been called. - void Connect(); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/IRequestHandler.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/IRequestHandler.cs deleted file mode 100644 index bf794c259f8..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/IRequestHandler.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a request handler. - /// - public interface IRequestHandler - { - /// - /// Gets the for a request. - /// - CancellationToken CancellationToken { get; } - - /// - /// Asynchronously handles cancelling a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - /// Thrown if cancellation is not supported. - Task HandleCancelAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken); - - /// - /// Asynchronously handles responding to a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - Task HandleResponseAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/IRequestHandlers.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/IRequestHandlers.cs deleted file mode 100644 index 5bad9fc1053..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/IRequestHandlers.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A set of . - /// - public interface IRequestHandlers - { - /// - /// Atomically add or update a request handler for the specified message method. - /// - /// A message method. - /// An add request handler function. - /// An update request handler function. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - void AddOrUpdate( - MessageMethod method, - Func addHandlerFunc, - Func updateHandlerFunc); - - /// - /// Attempts to add a request handler for the specified message method. - /// - /// A message method. - /// A request handler. - /// true if added; otherwise, false. - /// Thrown if is null. - bool TryAdd(MessageMethod method, IRequestHandler handler); - - /// - /// Attempts to get a request handler for the specified message method. - /// - /// A message method. - /// A request handler. - /// true if the request handler exists; otherwise, false. - bool TryGet(MessageMethod method, out IRequestHandler handler); - - /// - /// Attempts to remove a request handler for the specified message method. - /// - /// A message method. - /// true if a request handler was removed; otherwise, false. - bool TryRemove(MessageMethod method); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/IResponseHandler.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/IResponseHandler.cs deleted file mode 100644 index 203734c7249..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/IResponseHandler.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A response handler. - /// - public interface IResponseHandler - { - /// - /// Asynchronously handles responding to a request. - /// - /// The response payload type. - /// The request message. - /// The response payload. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if is null. - /// Thrown if is null. - /// Thrown if - /// is cancelled. - Task SendResponseAsync(Message request, TPayload payload, CancellationToken cancellationToken) - where TPayload : class; - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/ISender.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/ISender.cs deleted file mode 100644 index a63e91ec720..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/ISender.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a unidirectional communications to a target. - /// - public interface ISender : IDisposable - { - /// - /// Closes the connection. - /// - /// This does not call . - void Close(); - - /// - /// Connects. - /// - /// Thrown if this object is disposed. - /// Thrown if this object is closed. - /// Thrown if this method has already been called. - void Connect(); - - /// - /// Asynchronously sends a message to the target. - /// - /// The message to send. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if this object is disposed. - /// Thrown if has not been called. - /// Thrown if is null. - /// Thrown if - /// is cancelled. - Task SendAsync(Message message, CancellationToken cancellationToken); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/InboundRequestContext.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/InboundRequestContext.cs deleted file mode 100644 index c2286b7748b..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/InboundRequestContext.cs +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Context for an inbound request. - /// - public sealed class InboundRequestContext : IDisposable - { - private readonly CancellationToken _cancellationToken; - private readonly CancellationTokenSource _cancellationTokenSource; - private readonly IConnection _connection; - private bool _isDisposed; - - /// - /// Gets the request ID. - /// - public string RequestId { get; } - - /// - /// Initializes a new class. - /// - /// A connection. - /// A request ID. - /// A cancellation token. - /// Thrown if - /// is null. - /// Thrown if - /// is either null or an empty string. - public InboundRequestContext( - IConnection connection, - string requestId, - CancellationToken cancellationToken) - { - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } - - if (string.IsNullOrEmpty(requestId)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(requestId)); - } - - _connection = connection; - RequestId = requestId; - - _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - - // Capture the cancellation token now because if the cancellation token source - // is disposed race conditions may cause an exception acccessing its Token property. - _cancellationToken = _cancellationTokenSource.Token; - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (_isDisposed) - { - return; - } - - try - { - using (_cancellationTokenSource) - { - _cancellationTokenSource.Cancel(); - } - } - catch (Exception) - { - } - - // Do not dispose of _connection. - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - - - /// - /// Asynchronously starts processing a cancellation request for the inbound request. - /// - /// The request. - /// A request handler. - /// A response handler. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - public void BeginCancelAsync( - Message request, - IRequestHandler requestHandler, - IResponseHandler responseHandler) - { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (requestHandler == null) - { - throw new ArgumentNullException(nameof(requestHandler)); - } - - if (responseHandler == null) - { - throw new ArgumentNullException(nameof(responseHandler)); - } - - Task.Run(async () => - { - // Top-level exception handler for a worker pool thread. - try - { - await requestHandler.HandleCancelAsync( - _connection, - request, - responseHandler, - _cancellationToken); - } - catch (Exception ex) - { - BeginFaultAsync(request, ex); - } - }, - _cancellationToken); - } - - /// - /// Asynchronously starts processing a fault response for the inbound request. - /// - /// The request. - /// An exception. - /// Thrown if - /// is either null. - /// Thrown if - /// is null. - public void BeginFaultAsync(Message request, Exception exception) - { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } - - var responsePayload = new Fault(exception.Message); - var response = new Message( - request.RequestId, - MessageType.Fault, - request.Method, - JsonSerializationUtilities.FromObject(responsePayload)); - - Task.Run(async () => - { - // Top-level exception handler for a worker pool thread. - try - { - await _connection.SendAsync(response, _cancellationToken); - } - catch (Exception) - { - } - }, - _cancellationToken); - } - - /// - /// Asynchronously starts processing a response for the inbound request. - /// - /// The request. - /// A request handler. - /// A response handler. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - public void BeginResponseAsync( - Message request, - IRequestHandler requestHandler, - IResponseHandler responseHandler) - { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (requestHandler == null) - { - throw new ArgumentNullException(nameof(requestHandler)); - } - - if (responseHandler == null) - { - throw new ArgumentNullException(nameof(responseHandler)); - } - - Task.Run(async () => - { - // Top-level exception handler for a worker pool thread. - try - { - await requestHandler.HandleResponseAsync( - _connection, - request, - responseHandler, - _cancellationToken); - } - catch (Exception ex) - { - BeginFaultAsync(request, ex); - } - }, - _cancellationToken); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/JsonSerializationUtilities.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/JsonSerializationUtilities.cs deleted file mode 100644 index 523469b0a93..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/JsonSerializationUtilities.cs +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; - -namespace NuGet.Protocol.Plugins -{ - /// - /// JSON serialization/deserialization utilities. - /// - public static class JsonSerializationUtilities - { - /// - /// Gets the JSON serializer. - /// - public static JsonSerializer Serializer { get; } - - static JsonSerializationUtilities() - { - Serializer = JsonSerializer.Create(new JsonSerializerSettings() - { - Converters = new JsonConverter[] - { - new SemanticVersionConverter(), - new StringEnumConverter() - }, - Formatting = Formatting.None, - NullValueHandling = NullValueHandling.Ignore - }); - } - - /// - /// Deserializes an object from the provided JSON. - /// - /// The deserialization type. - /// JSON to deserialize. - /// An instance of . - /// Thrown if - /// is either null or an empty string. - public static T Deserialize(string json) - where T : class - { - if (string.IsNullOrEmpty(json)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(json)); - } - - using (var stringReader = new StringReader(json)) - using (var jsonReader = new JsonTextReader(stringReader)) - { - return Serializer.Deserialize(jsonReader); - } - } - - /// - /// Serializes an object. - /// - /// An object to serialize. - /// A . - /// Thrown if is null. - public static JObject FromObject(object value) - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - return JObject.FromObject(value, Serializer); - } - - /// - /// Serializes an object to the provided writer. - /// - /// A JSON writer. - /// The value to serialize. - /// Thrown if is null. - public static void Serialize(JsonWriter writer, object value) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - Serializer.Serialize(writer, value); - } - - /// - /// Deserializes an object. - /// - /// The deserialization type. - /// A JSON object. - /// An instance of . - /// Thrown if is null. - public static T ToObject(JObject jObject) - { - if (jObject == null) - { - throw new ArgumentNullException(nameof(jObject)); - } - - return jObject.ToObject(Serializer); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/LineReadEventArgs.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/LineReadEventArgs.cs deleted file mode 100644 index c1c2c7ce917..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/LineReadEventArgs.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Line read event arguments. - /// - public sealed class LineReadEventArgs : EventArgs - { - /// - /// The output line read. - /// - public string Line { get; } - - /// - /// Instantiates a new class. - /// - /// The output line read. - public LineReadEventArgs(string line) - { - Line = line; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageDispatcher.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/MessageDispatcher.cs deleted file mode 100644 index b1ffab65b31..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageDispatcher.cs +++ /dev/null @@ -1,712 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A message dispatcher that maintains state for outstanding requests - /// and routes messages to configured request handlers. - /// - public sealed class MessageDispatcher : IMessageDispatcher, IResponseHandler - { - private IConnection _connection; - private readonly IIdGenerator _idGenerator; - private bool _isClosed; - private bool _isDisposed; - private readonly ConcurrentDictionary _inboundRequestContexts; - private readonly ConcurrentDictionary _outboundRequestContexts; - - /// - /// Gets the request handlers for use by the dispatcher. - /// - public IRequestHandlers RequestHandlers { get; } - - /// - /// Instantiates a new class. - /// - /// Request handlers. - /// A unique identifier generator. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - public MessageDispatcher(IRequestHandlers requestHandlers, IIdGenerator idGenerator) - { - if (requestHandlers == null) - { - throw new ArgumentNullException(nameof(requestHandlers)); - } - - if (idGenerator == null) - { - throw new ArgumentNullException(nameof(idGenerator)); - } - - RequestHandlers = requestHandlers; - _idGenerator = idGenerator; - - _inboundRequestContexts = new ConcurrentDictionary(); - _outboundRequestContexts = new ConcurrentDictionary(); - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (_isDisposed) - { - return; - } - - Close(); - - SetConnection(connection: null); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - - /// - /// Closes the dispatcher. - /// - /// This does not call . - public void Close() - { - if (!_isClosed) - { - SetConnection(connection: null); - - foreach (var entry in _inboundRequestContexts) - { - entry.Value.Dispose(); - } - - foreach (var entry in _outboundRequestContexts) - { - entry.Value.Dispose(); - } - - _isClosed = true; - } - } - - /// - /// Creates a message. - /// - /// The message type. - /// The message method. - /// A message. - public Message CreateMessage(MessageType type, MessageMethod method) - { - var requestId = _idGenerator.GenerateUniqueId(); - - return MessageUtilities.Create(requestId, type, method); - } - - /// - /// Creates a message. - /// - /// The message payload. - /// The message type. - /// The message method. - /// The message payload. - /// A message. - /// Throws if is null. - public Message CreateMessage(MessageType type, MessageMethod method, TPayload payload) - where TPayload : class - { - if (payload == null) - { - throw new ArgumentNullException(nameof(payload)); - } - - var requestId = _idGenerator.GenerateUniqueId(); - - return MessageUtilities.Create(requestId, type, method, payload); - } - - /// - /// Asynchronously dispatches a cancellation request for the specified request. - /// - /// The request. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if is null. - /// Thrown if - /// is cancelled. - public Task DispatchCancelAsync(Message request, CancellationToken cancellationToken) - { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - // Capture _connection as SetConnection(...) could null it out later. - var connection = _connection; - - if (connection == null) - { - return Task.FromResult(0); - } - - return DispatchCancelAsync(connection, request, cancellationToken); - } - - /// - /// Asynchronously dispatches a fault notification for the specified request. - /// - /// The cancel request. - /// The fault payload. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if is null. - /// Thrown if - /// is cancelled. - public Task DispatchFaultAsync(Message request, Fault fault, CancellationToken cancellationToken) - { - if (fault == null) - { - throw new ArgumentNullException(nameof(fault)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - // Capture _connection as SetConnection(...) could null it out later. - var connection = _connection; - - if (connection == null) - { - return Task.FromResult(0); - } - - return DispatchFaultAsync(connection, request, fault, cancellationToken); - } - - /// - /// Asynchronously dispatches a progress notification for the specified request. - /// - /// The request. - /// The progress payload. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if is null. - /// Thrown if is null. - /// Thrown if - /// is cancelled. - public Task DispatchProgressAsync(Message request, Progress progress, CancellationToken cancellationToken) - { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (progress == null) - { - throw new ArgumentNullException(nameof(progress)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - // Capture _connection as SetConnection(...) could null it out later. - var connection = _connection; - - if (connection == null) - { - return Task.FromResult(0); - } - - return DispatchProgressAsync(connection, request, progress, cancellationToken); - } - - /// - /// Asynchronously dispatches a request. - /// - /// The request payload type. - /// The expected response payload type. - /// The request method. - /// The request payload. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// from the target. - /// Thrown if - /// is cancelled. - public Task DispatchRequestAsync( - MessageMethod method, - TOutbound payload, - CancellationToken cancellationToken) - where TOutbound : class - where TInbound : class - { - cancellationToken.ThrowIfCancellationRequested(); - - // Capture _connection as SetConnection(...) could null it out later. - var connection = _connection; - - if (connection == null) - { - return Task.FromResult(null); - } - - return DispatchWithNewContextAsync( - connection, - MessageType.Request, - method, - payload, - cancellationToken); - } - - /// - /// Asynchronously dispatches a response. - /// - /// The request payload type. - /// The associated request. - /// The response payload. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if is null. - /// Thrown if is null. - /// Thrown if - /// is cancelled. - public Task DispatchResponseAsync( - Message request, - TOutbound responsePayload, - CancellationToken cancellationToken) - where TOutbound : class - { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (responsePayload == null) - { - throw new ArgumentNullException(nameof(responsePayload)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - // Capture _connection as SetConnection(...) could null it out later. - var connection = _connection; - - if (connection == null) - { - return Task.FromResult(0); - } - - return DispatchAsync(connection, MessageType.Response, request, responsePayload, cancellationToken); - } - - /// - /// Sets the connection to be used for dispatching messages. - /// - /// A connection instance. Can be null. - public void SetConnection(IConnection connection) - { - if (_connection == connection) - { - return; - } - - if (_connection != null) - { - _connection.MessageReceived -= OnMessageReceived; - } - - _connection = connection; - - if (_connection != null) - { - _connection.MessageReceived += OnMessageReceived; - } - } - - Task IResponseHandler.SendResponseAsync( - Message request, - TPayload payload, - CancellationToken cancellationToken) - { - return DispatchResponseAsync(request, payload, cancellationToken); - } - - private async Task DispatchAsync( - IConnection connection, - MessageType type, - Message request, - TOutgoing payload, - CancellationToken cancellationToken) - where TOutgoing : class - { - InboundRequestContext requestContext; - - if (!_inboundRequestContexts.TryGetValue(request.RequestId, out requestContext)) - { - return; - } - - var message = MessageUtilities.Create(request.RequestId, type, request.Method, payload); - - try - { - await connection.SendAsync(message, cancellationToken); - } - finally - { - RemoveInboundRequestContext(request.RequestId); - } - } - - private async Task DispatchCancelAsync( - IConnection connection, - Message request, - CancellationToken cancellationToken) - { - var message = new Message(request.RequestId, MessageType.Cancel, request.Method); - - await DispatchWithExistingContextAsync(connection, message, cancellationToken); - } - - private async Task DispatchFaultAsync( - IConnection connection, - Message request, - Fault fault, - CancellationToken cancellationToken) - { - Message message; - - var jsonPayload = JsonSerializationUtilities.FromObject(fault); - - if (request == null) - { - var requestId = _idGenerator.GenerateUniqueId(); - - message = new Message(requestId, MessageType.Fault, MessageMethod.None, jsonPayload); - - await connection.SendAsync(message, cancellationToken); - } - else - { - message = new Message(request.RequestId, MessageType.Fault, request.Method, jsonPayload); - - await DispatchWithExistingContextAsync(connection, message, cancellationToken); - } - } - - private async Task DispatchProgressAsync( - IConnection connection, - Message request, - Progress progress, - CancellationToken cancellationToken) - { - var message = MessageUtilities.Create(request.RequestId, MessageType.Progress, request.Method, progress); - - await DispatchWithExistingContextAsync(connection, message, cancellationToken); - } - - private async Task DispatchWithExistingContextAsync( - IConnection connection, - Message response, - CancellationToken cancellationToken) - { - var requestContext = GetOutboundRequestContext(response.RequestId); - - await connection.SendAsync(response, cancellationToken); - } - - private async Task DispatchWithNewContextAsync( - IConnection connection, - MessageType type, - MessageMethod method, - TOutgoing payload, - CancellationToken cancellationToken) - where TOutgoing : class - where TIncoming : class - { - var message = CreateMessage(type, method, payload); - var timeout = GetRequestTimeout(connection, type, method); - var isKeepAlive = GetIsKeepAlive(connection, type, method); - var requestContext = CreateOutboundRequestContext( - message, - timeout, - isKeepAlive, - cancellationToken); - - _outboundRequestContexts.TryAdd(message.RequestId, requestContext); - - switch (type) - { - case MessageType.Request: - case MessageType.Response: - case MessageType.Fault: - try - { - await connection.SendAsync(message, cancellationToken); - - return await requestContext.CompletionTask; - } - finally - { - RemoveOutboundRequestContext(message.RequestId); - } - - default: - break; - } - - return null; - } - - private void OnMessageReceived(object sender, MessageEventArgs e) - { - // Capture _connection as SetConnection(...) could null it out later. - var connection = _connection; - - if (connection == null) - { - return; - } - - OutboundRequestContext requestContext; - - if (_outboundRequestContexts.TryGetValue(e.Message.RequestId, out requestContext)) - { - switch (e.Message.Type) - { - case MessageType.Response: - requestContext.HandleResponse(e.Message); - break; - - case MessageType.Progress: - requestContext.HandleProgress(e.Message); - break; - - case MessageType.Fault: - requestContext.HandleFault(e.Message); - break; - - case MessageType.Cancel: - requestContext.HandleCancel(); - break; - - default: - throw new ProtocolException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_InvalidMessageType, - e.Message.Type)); - } - - return; - } - - switch (e.Message.Type) - { - case MessageType.Cancel: - HandleInboundCancel(connection, e.Message); - break; - - case MessageType.Request: - HandleInboundRequest(connection, e.Message); - break; - - case MessageType.Fault: - HandleInboundFault(connection, e.Message); - break; - - default: - throw new ProtocolException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_InvalidMessageType, - e.Message.Type)); - } - } - - private void HandleInboundCancel(IConnection connection, Message message) - { - var cancellationToken = CancellationToken.None; - IRequestHandler requestHandler = null; - ProtocolException exception = null; - - try - { - requestHandler = GetInboundRequestHandler(message.Method); - cancellationToken = requestHandler.CancellationToken; - } - catch (ProtocolException ex) - { - exception = ex; - } - - var requestContext = GetInboundRequestContext(message.RequestId); - - if (exception == null && requestHandler != null) - { - requestContext.BeginCancelAsync(message, requestHandler, this); - } - else - { - requestContext.BeginFaultAsync(message, exception); - } - } - - private void HandleInboundFault(IConnection connection, Message fault) - { - if (fault == null) - { - throw new ArgumentNullException(nameof(fault)); - } - - var payload = MessageUtilities.DeserializePayload(fault); - - throw new ProtocolException(payload.Message); - } - - private void HandleInboundRequest(IConnection connection, Message message) - { - var cancellationToken = CancellationToken.None; - IRequestHandler requestHandler = null; - ProtocolException exception = null; - - try - { - requestHandler = GetInboundRequestHandler(message.Method); - cancellationToken = requestHandler.CancellationToken; - } - catch (ProtocolException ex) - { - exception = ex; - } - - var requestContext = CreateInboundRequestContext(message, cancellationToken); - - if (exception == null && requestHandler != null) - { - _inboundRequestContexts.TryAdd(message.RequestId, requestContext); - - requestContext.BeginResponseAsync(message, requestHandler, this); - } - else - { - requestContext.BeginFaultAsync(message, exception); - } - } - - private IRequestHandler GetInboundRequestHandler(MessageMethod method) - { - IRequestHandler handler; - - if (!RequestHandlers.TryGet(method, out handler)) - { - throw new ProtocolException( - string.Format(CultureInfo.CurrentCulture, Strings.Plugin_RequestHandlerDoesNotExist, method)); - } - - return handler; - } - - private InboundRequestContext GetInboundRequestContext(string requestId) - { - InboundRequestContext requestContext; - - if (!_inboundRequestContexts.TryGetValue(requestId, out requestContext)) - { - throw new ProtocolException( - string.Format(CultureInfo.CurrentCulture, Strings.Plugin_RequestContextDoesNotExist, requestId)); - } - - return requestContext; - } - - private OutboundRequestContext GetOutboundRequestContext(string requestId) - { - OutboundRequestContext requestContext; - - if (!_outboundRequestContexts.TryGetValue(requestId, out requestContext)) - { - throw new ProtocolException( - string.Format(CultureInfo.CurrentCulture, Strings.Plugin_RequestContextDoesNotExist, requestId)); - } - - return requestContext; - } - - private void RemoveInboundRequestContext(string requestId) - { - InboundRequestContext requestContext; - - if (_inboundRequestContexts.TryRemove(requestId, out requestContext)) - { - requestContext.Dispose(); - } - } - - private void RemoveOutboundRequestContext(string requestId) - { - OutboundRequestContext requestContext; - - if (_outboundRequestContexts.TryRemove(requestId, out requestContext)) - { - requestContext.Dispose(); - } - } - - private InboundRequestContext CreateInboundRequestContext( - Message message, - CancellationToken cancellationToken) - { - return new InboundRequestContext( - _connection, - message.RequestId, - cancellationToken); - } - - private OutboundRequestContext CreateOutboundRequestContext( - Message message, - TimeSpan? timeout, - bool isKeepAlive, - CancellationToken cancellationToken) - { - return new OutboundRequestContext( - _connection, - message, - timeout, - isKeepAlive, - cancellationToken); - } - - private static bool GetIsKeepAlive(IConnection connection, MessageType type, MessageMethod method) - { - if (type == MessageType.Request && method == MessageMethod.Handshake) - { - return false; - } - - return true; - } - - private static TimeSpan GetRequestTimeout(IConnection connection, MessageType type, MessageMethod method) - { - if (type == MessageType.Request && method == MessageMethod.Handshake) - { - return connection.Options.HandshakeTimeout; - } - - return connection.Options.RequestTimeout; - } - - private sealed class NullPayload - { - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageEventArgs.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/MessageEventArgs.cs deleted file mode 100644 index b5001d8adeb..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageEventArgs.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Message event arguments. - /// - public sealed class MessageEventArgs : EventArgs - { - /// - /// Gets the message. - /// - public Message Message { get; } - - /// - /// Instantiates a new class. - /// - /// A message. - /// Thrown if is null. - public MessageEventArgs(Message message) - { - if (message == null) - { - throw new ArgumentNullException(nameof(message)); - } - - Message = message; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageMethod.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/MessageMethod.cs deleted file mode 100644 index c80ab3594c2..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageMethod.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace NuGet.Protocol.Plugins -{ - /// - /// Message methods. - /// - public enum MessageMethod - { - /// - /// None - /// - None, - - /// - /// Close - /// - Close, - - /// - /// Copy files in a package - /// - CopyFilesInPackage, - - /// - /// Copy a .nupkg file - /// - CopyNupkgFile, - - /// - /// Get credentials - /// - GetCredentials, - - /// - /// Get files in a package - /// - GetFilesInPackage, - - /// - /// Get operation claims - /// - GetOperationClaims, - - /// - /// Get package hash - /// - GetPackageHash, - - /// - /// Get package versions - /// - GetPackageVersions, - - /// - /// Get service index - /// - GetServiceIndex, - - /// - /// Handshake - /// - Handshake, - - /// - /// Initialize - /// - Initialize, - - /// - /// Log - /// - Log, - - /// - /// Monitor NuGet process exit - /// - MonitorNuGetProcessExit, - - /// - /// Prefetch a package - /// - PrefetchPackage, - - /// - /// Set credentials - /// - SetCredentials, - - /// - /// Set log level - /// - SetLogLevel - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageResponseCode.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/MessageResponseCode.cs deleted file mode 100644 index 5a32bf33eec..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageResponseCode.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace NuGet.Protocol.Plugins -{ - /// - /// Message response codes. - /// - public enum MessageResponseCode - { - /// - /// The response is success. - /// - Success, - - /// - /// The response is error. - /// - Error, - - /// - /// The response is not found. - /// - NotFound - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageType.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/MessageType.cs deleted file mode 100644 index 34ab3177922..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageType.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace NuGet.Protocol.Plugins -{ - /// - /// Message types. - /// - public enum MessageType - { - /// - /// A cancellation request for an existing request. - /// - Cancel, - - /// - /// A fault notification, either standalone or for an existing request. - /// - Fault, - - /// - /// A progress notification for an existing request. - /// - Progress, - - /// - /// A request. - /// - Request, - - /// - /// A response for an existing request. - /// - Response - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageUtilities.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/MessageUtilities.cs deleted file mode 100644 index 7c1767b98ef..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageUtilities.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Helper methods for messages. - /// - public static class MessageUtilities - { - /// - /// Instantiates a new class. - /// - /// The message request ID. - /// The message type. - /// The message method. - /// a instance. - /// Thrown if - /// is either null or an empty string. - public static Message Create( - string requestId, - MessageType type, - MessageMethod method) - { - if (string.IsNullOrEmpty(requestId)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(requestId)); - } - - return new Message(requestId, type, method); - } - - /// - /// Instantiates a new class. - /// - /// The message payload type. - /// The message request ID. - /// The message type. - /// The message method. - /// The message payload. - /// a instance. - /// Thrown if - /// is either null or an empty string. - /// Thrown if is null. - public static Message Create( - string requestId, - MessageType type, - MessageMethod method, - TPayload payload) - where TPayload : class - { - if (string.IsNullOrEmpty(requestId)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(requestId)); - } - - if (payload == null) - { - throw new ArgumentNullException(nameof(payload)); - } - - var jsonPayload = JsonSerializationUtilities.FromObject(payload); - - return new Message(requestId, type, method, jsonPayload); - } - - /// - /// Deserializes a message payload. - /// - /// The message payload type. - /// The message. - /// The deserialized message payload of type - /// or null if no payload exists. - /// Thrown if is null. - public static TPayload DeserializePayload(Message message) - { - if (message == null) - { - throw new ArgumentNullException(nameof(message)); - } - - if (message.Payload == null) - { - return default(TPayload); - } - - return JsonSerializationUtilities.ToObject(message.Payload); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyFilesInPackageRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyFilesInPackageRequest.cs deleted file mode 100644 index 3dc7100a676..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyFilesInPackageRequest.cs +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request to copy files in a package to a specified destination. - /// - public sealed class CopyFilesInPackageRequest - { - /// - /// Gets the destination folder path. - /// - [JsonRequired] - public string DestinationFolderPath { get; } - - /// - /// Gets the files in the package to be copied. - /// - [JsonRequired] - public IEnumerable FilesInPackage { get; } - - /// - /// Gets the package ID. - /// - [JsonRequired] - public string PackageId { get; } - - /// - /// Gets the package source repository location. - /// - [JsonRequired] - public string PackageSourceRepository { get; } - - /// - /// Gets the package version. - /// - [JsonRequired] - public string PackageVersion { get; } - - /// - /// Initializes a new class. - /// - /// The package source repository location. - /// The package ID. - /// The package version. - /// The files in the package to be copied. - /// The destination folder path. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or an empty string. - [JsonConstructor] - public CopyFilesInPackageRequest( - string packageSourceRepository, - string packageId, - string packageVersion, - IEnumerable filesInPackage, - string destinationFolderPath) - { - if (string.IsNullOrEmpty(packageSourceRepository)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageSourceRepository)); - } - - if (string.IsNullOrEmpty(packageId)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageId)); - } - - if (string.IsNullOrEmpty(packageVersion)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageVersion)); - } - - if (filesInPackage == null || !filesInPackage.Any()) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(filesInPackage)); - } - - if (string.IsNullOrEmpty(destinationFolderPath)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(destinationFolderPath)); - } - - PackageId = packageId; - PackageVersion = packageVersion; - PackageSourceRepository = packageSourceRepository; - FilesInPackage = filesInPackage; - DestinationFolderPath = destinationFolderPath; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyFilesInPackageResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyFilesInPackageResponse.cs deleted file mode 100644 index 421b3fff810..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyFilesInPackageResponse.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A response to a copy package files request. - /// - public sealed class CopyFilesInPackageResponse - { - /// - /// Gets the paths of files copies. - /// - public IEnumerable CopiedFiles { get; } - - /// - /// Gets the response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Initializes a new class. - /// - /// The response code. - /// The paths of files copies. - /// Thrown if - /// is an undefined value. - /// Thrown if - /// is and - /// is either null or empty. - [JsonConstructor] - public CopyFilesInPackageResponse(MessageResponseCode responseCode, IEnumerable copiedFiles) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - if (responseCode == MessageResponseCode.Success && (copiedFiles == null || !copiedFiles.Any())) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(copiedFiles)); - } - - ResponseCode = responseCode; - CopiedFiles = copiedFiles; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyNupkgFileRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyNupkgFileRequest.cs deleted file mode 100644 index 2f9eea13671..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyNupkgFileRequest.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request to copy a .nupkg file. - /// - public sealed class CopyNupkgFileRequest - { - /// - /// Gets the destination file path for the .nupkg file. - /// - [JsonRequired] - public string DestinationFilePath { get; } - - /// - /// Gets the package ID. - /// - [JsonRequired] - public string PackageId { get; } - - /// - /// Gets the package source repository location. - /// - [JsonRequired] - public string PackageSourceRepository { get; } - - /// - /// Gets the package version. - /// - [JsonRequired] - public string PackageVersion { get; } - - /// - /// Initializes a new class. - /// - /// The package source repository location. - /// The package ID. - /// The package version. - /// The destination file path for the .nupkg file. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - [JsonConstructor] - public CopyNupkgFileRequest( - string packageSourceRepository, - string packageId, - string packageVersion, - string destinationFilePath) - { - if (string.IsNullOrEmpty(packageSourceRepository)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageSourceRepository)); - } - - if (string.IsNullOrEmpty(packageId)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageId)); - } - - if (string.IsNullOrEmpty(packageVersion)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageVersion)); - } - - if (string.IsNullOrEmpty(destinationFilePath)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(destinationFilePath)); - } - - PackageId = packageId; - PackageVersion = packageVersion; - PackageSourceRepository = packageSourceRepository; - DestinationFilePath = destinationFilePath; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyNupkgFileResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyNupkgFileResponse.cs deleted file mode 100644 index c6ec3d25053..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/CopyNupkgFileResponse.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A response to a copy .nupkg file request. - /// - public sealed class CopyNupkgFileResponse - { - /// - /// Gets the response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Initializes a new class. - /// - /// The response code. - /// Thrown if - /// is an undefined value. - [JsonConstructor] - public CopyNupkgFileResponse(MessageResponseCode responseCode) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - ResponseCode = responseCode; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/Fault.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/Fault.cs deleted file mode 100644 index b4a8ffc8aae..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/Fault.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A notification indicating the sender has experienced an unrecoverable fault. - /// - public sealed class Fault - { - /// - /// Gets the fault message. - /// - [JsonRequired] - public string Message { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The fault message. - /// Thrown if - /// is either null or an empty string. - [JsonConstructor] - public Fault(string message) - { - if (string.IsNullOrEmpty(message)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(message)); - } - - Message = message; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetCredentialsRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetCredentialsRequest.cs deleted file mode 100644 index 585fd5891a1..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetCredentialsRequest.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using System.Net; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request to get credentials. - /// - public sealed class GetCredentialsRequest - { - /// - /// Gets the package source repository location. - /// - [JsonRequired] - public string PackageSourceRepository { get; } - - /// - /// Gets the HTTP status code that necessitates credentials. - /// - [JsonRequired] - public HttpStatusCode StatusCode { get; } - - /// - /// Initializes a new class. - /// - /// The package source repository location. - /// The HTTP status code. - [JsonConstructor] - public GetCredentialsRequest(string packageSourceRepository, HttpStatusCode statusCode) - { - if (string.IsNullOrEmpty(packageSourceRepository)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageSourceRepository)); - } - - if (!Enum.IsDefined(typeof(HttpStatusCode), statusCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - statusCode), - nameof(statusCode)); - } - - PackageSourceRepository = packageSourceRepository; - StatusCode = statusCode; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetCredentialsResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetCredentialsResponse.cs deleted file mode 100644 index 3a39c7a66e2..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetCredentialsResponse.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A response to a get credentials request. - /// - public sealed class GetCredentialsResponse - { - /// - /// Gets the password. - /// - public string Password { get; } - - /// - /// Gets the response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Gets the username. - /// - public string Username { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The plugin's response code. - /// Thrown if - /// is an undefined value. - [JsonConstructor] - public GetCredentialsResponse( - MessageResponseCode responseCode, - string username, - string password) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - ResponseCode = responseCode; - Username = username; - Password = password; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetFilesInPackageRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetFilesInPackageRequest.cs deleted file mode 100644 index 514747aa55d..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetFilesInPackageRequest.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A get files in package request. - /// - public sealed class GetFilesInPackageRequest - { - /// - /// Gets the package ID. - /// - [JsonRequired] - public string PackageId { get; } - - /// - /// Gets the package source repository location. - /// - [JsonRequired] - public string PackageSourceRepository { get; } - - /// - /// Gets the package version. - /// - [JsonRequired] - public string PackageVersion { get; } - - /// - /// Initializes a new class. - /// - /// The package source repository location. - /// The package ID. - /// The package version. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - [JsonConstructor] - public GetFilesInPackageRequest( - string packageSourceRepository, - string packageId, - string packageVersion) - { - if (string.IsNullOrEmpty(packageSourceRepository)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageSourceRepository)); - } - - if (string.IsNullOrEmpty(packageId)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageId)); - } - - if (string.IsNullOrEmpty(packageVersion)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageVersion)); - } - - PackageSourceRepository = packageSourceRepository; - PackageId = packageId; - PackageVersion = packageVersion; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetFilesInPackageResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetFilesInPackageResponse.cs deleted file mode 100644 index bf017b4b5ee..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetFilesInPackageResponse.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A response to a get files in package request. - /// - public sealed class GetFilesInPackageResponse - { - /// - /// Gets the paths of files in the package. - /// - public IEnumerable Files { get; } - - /// - /// Gets the response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Initializes a new class. - /// - /// The response code. - /// The paths of files in the package. - /// Thrown if - /// is an undefined value. - /// Thrown if - /// is and - /// is either null or empty. - [JsonConstructor] - public GetFilesInPackageResponse(MessageResponseCode responseCode, IEnumerable files) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - if (responseCode == MessageResponseCode.Success && (files == null || !files.Any())) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(files)); - } - - ResponseCode = responseCode; - Files = files; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetOperationClaimsRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetOperationClaimsRequest.cs deleted file mode 100644 index a7d864cce92..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetOperationClaimsRequest.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A query to a plugin about which operations it supports for a specific package source. - /// - public sealed class GetOperationClaimsRequest - { - /// - /// Gets the package source repository location for the . - /// - [JsonRequired] - public string PackageSourceRepository { get; } - - /// - /// Gets the service index (index.json) for the . - /// - [JsonRequired] - public JObject ServiceIndex { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The package source location. - /// The service index (index.json). - /// Thrown if is either - /// null or an empty string. - /// Thrown if is null. - [JsonConstructor] - public GetOperationClaimsRequest(string packageSourceRepository, JObject serviceIndex) - { - if (string.IsNullOrEmpty(packageSourceRepository)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageSourceRepository)); - } - - if (serviceIndex == null) - { - throw new ArgumentNullException(nameof(serviceIndex)); - } - - PackageSourceRepository = packageSourceRepository; - ServiceIndex = serviceIndex; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetOperationClaimsResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetOperationClaimsResponse.cs deleted file mode 100644 index 2bb53062dec..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetOperationClaimsResponse.cs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A plugin's response as to which operations it supports for a specific package source. - /// - public sealed class GetOperationClaimsResponse - { - /// - /// Gets the plugin's operation claims. - /// - [JsonRequired] - public IReadOnlyList Claims { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The operation claims. - /// Thrown if is null. - /// Thrown if contains - /// undefined values. - [JsonConstructor] - public GetOperationClaimsResponse(IEnumerable claims) - { - if (claims == null) - { - throw new ArgumentNullException(nameof(claims)); - } - - var unrecognizedClaims = claims.Where(claim => !Enum.IsDefined(typeof(OperationClaim), claim)); - - if (unrecognizedClaims.Any()) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedOperationClaims, - string.Join(",", unrecognizedClaims)), - nameof(claims)); - } - - Claims = claims.ToList(); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageHashRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageHashRequest.cs deleted file mode 100644 index 2d69009e628..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageHashRequest.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request to get a package hash. - /// - public sealed class GetPackageHashRequest - { - /// - /// Gets the hash algorithm. - /// - [JsonRequired] - public string HashAlgorithm { get; } - - /// - /// Gets the package ID. - /// - [JsonRequired] - public string PackageId { get; } - - /// - /// Gets the package source repository location. - /// - [JsonRequired] - public string PackageSourceRepository { get; } - - /// - /// Gets the package version. - /// - [JsonRequired] - public string PackageVersion { get; } - - /// - /// Initializes a new class. - /// - /// The package source repository location. - /// The package ID. - /// The package version. - /// The hash algorithm. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - [JsonConstructor] - public GetPackageHashRequest( - string packageSourceRepository, - string packageId, - string packageVersion, - string hashAlgorithm) - { - if (string.IsNullOrEmpty(packageSourceRepository)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageSourceRepository)); - } - - if (string.IsNullOrEmpty(packageId)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageId)); - } - - if (string.IsNullOrEmpty(packageVersion)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageVersion)); - } - - if (string.IsNullOrEmpty(hashAlgorithm)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(hashAlgorithm)); - } - - PackageId = packageId; - PackageVersion = packageVersion; - PackageSourceRepository = packageSourceRepository; - HashAlgorithm = hashAlgorithm; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageHashResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageHashResponse.cs deleted file mode 100644 index 7eb355cb49b..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageHashResponse.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A response to a get package hash request. - /// - public sealed class GetPackageHashResponse - { - /// - /// Gets the package hash. - /// - public string Hash { get; } - - /// - /// Gets the response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Initializes a new class. - /// - /// The response code. - /// Thrown if - /// is an undefined value. - /// Thrown if - /// is and - /// is either null or empty. - [JsonConstructor] - public GetPackageHashResponse(MessageResponseCode responseCode, string hash) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - if (responseCode == MessageResponseCode.Success && string.IsNullOrEmpty(hash)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(hash)); - } - - ResponseCode = responseCode; - Hash = hash; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageVersionsRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageVersionsRequest.cs deleted file mode 100644 index 4ab28730a4b..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageVersionsRequest.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request for package versions. - /// - public sealed class GetPackageVersionsRequest - { - /// - /// Gets the package ID. - /// - [JsonRequired] - public string PackageId { get; } - - /// - /// Gets the package source repository location. - /// - [JsonRequired] - public string PackageSourceRepository { get; } - - /// - /// Initializes a new class. - /// - /// The package source repository location. - /// The package ID. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - [JsonConstructor] - public GetPackageVersionsRequest( - string packageSourceRepository, - string packageId) - { - if (string.IsNullOrEmpty(packageSourceRepository)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageSourceRepository)); - } - - if (string.IsNullOrEmpty(packageId)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageId)); - } - - PackageSourceRepository = packageSourceRepository; - PackageId = packageId; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageVersionsResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageVersionsResponse.cs deleted file mode 100644 index 21eaebb4b18..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetPackageVersionsResponse.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A response to a get package versions request. - /// - public sealed class GetPackageVersionsResponse - { - /// - /// Gets the response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Gets the package versions. - /// - public IEnumerable Versions { get; } - - /// - /// Initializes a new class. - /// - /// The response code. - /// The package versions. - /// Thrown if - /// is an undefined value. - /// Thrown if - /// is and - /// is either null or empty. - [JsonConstructor] - public GetPackageVersionsResponse(MessageResponseCode responseCode, IEnumerable versions) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - if (responseCode == MessageResponseCode.Success && (versions == null || !versions.Any())) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(versions)); - } - - ResponseCode = responseCode; - Versions = versions; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetServiceIndexRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetServiceIndexRequest.cs deleted file mode 100644 index 4e2c5646aba..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetServiceIndexRequest.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request to get the service index for a package source repository. - /// - public sealed class GetServiceIndexRequest - { - /// - /// Gets the package source repository location. - /// - [JsonRequired] - public string PackageSourceRepository { get; } - - /// - /// Initializes a new class. - /// - /// The package source repository location. - [JsonConstructor] - public GetServiceIndexRequest(string packageSourceRepository) - { - if (string.IsNullOrEmpty(packageSourceRepository)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageSourceRepository)); - } - - PackageSourceRepository = packageSourceRepository; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetServiceIndexResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetServiceIndexResponse.cs deleted file mode 100644 index a44f76e7db4..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/GetServiceIndexResponse.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A response to a get service index request. - /// - public sealed class GetServiceIndexResponse - { - /// - /// Gets the response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Gets the service index (index.json) for the package source repository. - /// - public JObject ServiceIndex { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The response code. - /// The service index (index.json) for the package source repository. - /// Thrown if - /// is an undefined value. - /// Thrown if - /// is and - /// is null. - [JsonConstructor] - public GetServiceIndexResponse(MessageResponseCode responseCode, JObject serviceIndex) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - if (responseCode == MessageResponseCode.Success && serviceIndex == null) - { - throw new ArgumentNullException(nameof(serviceIndex)); - } - - ResponseCode = responseCode; - ServiceIndex = serviceIndex; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/HandshakeRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/HandshakeRequest.cs deleted file mode 100644 index 383d9f58bf5..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/HandshakeRequest.cs +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; -using NuGet.Versioning; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A handshake request. - /// - public sealed class HandshakeRequest - { - /// - /// Gets the requestor's plugin protocol version. - /// - [JsonRequired] - public SemanticVersion ProtocolVersion { get; } - - /// - /// Gets the requestor's minimum plugin protocol version. - /// - [JsonRequired] - public SemanticVersion MinimumProtocolVersion { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The requestor's plugin protocol version. - /// The requestor's minimum plugin protocol version. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is less than . - [JsonConstructor] - public HandshakeRequest(SemanticVersion protocolVersion, SemanticVersion minimumProtocolVersion) - { - if (protocolVersion == null) - { - throw new ArgumentNullException(nameof(protocolVersion)); - } - - if (minimumProtocolVersion == null) - { - throw new ArgumentNullException(nameof(minimumProtocolVersion)); - } - - if (minimumProtocolVersion > protocolVersion) - { - throw new ArgumentOutOfRangeException( - nameof(protocolVersion), - protocolVersion, - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_ProtocolVersionOutOfRange, - nameof(protocolVersion), - nameof(minimumProtocolVersion))); - } - - ProtocolVersion = protocolVersion; - MinimumProtocolVersion = minimumProtocolVersion; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/HandshakeResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/HandshakeResponse.cs deleted file mode 100644 index edadfbee3ec..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/HandshakeResponse.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; -using NuGet.Versioning; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A handshake response. - /// - public sealed class HandshakeResponse - { - /// - /// Gets the handshake responder's handshake response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Gets the handshake responder's plugin protocol version if the handshake was successful; - /// otherwise, null. - /// - public SemanticVersion ProtocolVersion { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The handshake responder's handshake response code. - /// The handshake responder's plugin protocol version - /// if the handshake was successful; otherwise, null. - /// Thrown if - /// is an undefined value. - /// Thrown if - /// is and - /// is null. - /// Thrown if - /// is not and - /// is not null. - [JsonConstructor] - public HandshakeResponse(MessageResponseCode responseCode, SemanticVersion protocolVersion) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - if (responseCode == MessageResponseCode.Success) - { - if (protocolVersion == null) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(protocolVersion)); - } - } - else if (protocolVersion != null) - { - throw new ArgumentException( - Strings.Plugin_ProtocolVersionNotSupportedOnError, - nameof(protocolVersion)); - } - - ResponseCode = responseCode; - ProtocolVersion = protocolVersion; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/InitializeRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/InitializeRequest.cs deleted file mode 100644 index ab6ca1d659f..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/InitializeRequest.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// An initialization request to a plugin. - /// - public sealed class InitializeRequest - { - /// - /// Gets the requestor's NuGet client version. - /// - [JsonRequired] - public string ClientVersion { get; } - - /// - /// Gets the requestor's current culture. - /// - [JsonRequired] - public string Culture { get; } - - /// - /// Gets the default request timeout for all subsequent requests. - /// - [JsonRequired] - public TimeSpan RequestTimeout { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The requestor's NuGet client version. - /// The requestor's current culture. - /// The default request timeout. - /// Thrown if is either null - /// or an empty string. - /// Thrown if is either null - /// or an empty string. - /// Thrown if - /// is either less than or greater than - /// . - [JsonConstructor] - public InitializeRequest(string clientVersion, string culture, TimeSpan requestTimeout) - { - if (string.IsNullOrEmpty(clientVersion)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(clientVersion)); - } - - if (string.IsNullOrEmpty(culture)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(culture)); - } - - if (!TimeoutUtilities.IsValid(requestTimeout)) - { - throw new ArgumentOutOfRangeException( - nameof(requestTimeout), - requestTimeout, - Strings.Plugin_TimeoutOutOfRange); - } - - ClientVersion = clientVersion; - Culture = culture; - RequestTimeout = requestTimeout; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/InitializeResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/InitializeResponse.cs deleted file mode 100644 index 57310da2795..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/InitializeResponse.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// An initialization response from a plugin. - /// - public sealed class InitializeResponse - { - /// - /// Gets the plugin's initialization response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The plugin's initialization response code. - /// Thrown if - /// is an undefined value. - [JsonConstructor] - public InitializeResponse(MessageResponseCode responseCode) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - ResponseCode = responseCode; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/LogRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/LogRequest.cs deleted file mode 100644 index 63bf996a909..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/LogRequest.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; -using NuGet.Common; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A logging request. - /// - public sealed class LogRequest - { - /// - /// Gets the logging level for the message. - /// - [JsonRequired] - public LogLevel LogLevel { get; } - - /// - /// Gets the message. - /// - [JsonRequired] - public string Message { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The logging level for the message. - /// The message to be logged. - /// Thrown if is an undefined - /// value. - /// Thrown if is either null - /// or an empty string. - [JsonConstructor] - public LogRequest(LogLevel logLevel, string message) - { - if (!Enum.IsDefined(typeof(LogLevel), logLevel)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - logLevel), - nameof(logLevel)); - } - - if (string.IsNullOrEmpty(message)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(message)); - } - - LogLevel = logLevel; - Message = message; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/LogResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/LogResponse.cs deleted file mode 100644 index d0c8f527e57..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/LogResponse.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A logging response. - /// - public sealed class LogResponse - { - /// - /// Gets the logging response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The logging response code. - /// Thrown if - /// is an undefined value. - [JsonConstructor] - public LogResponse(MessageResponseCode responseCode) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - ResponseCode = responseCode; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/Message.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/Message.cs deleted file mode 100644 index bc17b1547b5..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/Message.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a message between a NuGet client and a plugin. - /// - public sealed class Message - { - /// - /// Gets the request ID. - /// - [JsonRequired] - public string RequestId { get; } - - /// - /// Gets the message type. - /// - [JsonRequired] - public MessageType Type { get; } - - /// - /// Gets the message method. - /// - [JsonRequired] - public MessageMethod Method { get; } - - /// - /// Gets the optional message payload. - /// - public JObject Payload { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The request ID. - /// The message type. - /// The message method. - /// An optional message payload. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is an undefined value. - /// Thrown if - /// is an undefined value. - [JsonConstructor] - public Message(string requestId, MessageType type, MessageMethod method, JObject payload = null) - { - if (string.IsNullOrEmpty(requestId)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(requestId)); - } - - if (!Enum.IsDefined(typeof(MessageType), type)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - type), - nameof(type)); - } - - if (!Enum.IsDefined(typeof(MessageMethod), method)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - method), - nameof(method)); - } - - RequestId = requestId; - Type = type; - Method = method; - Payload = payload; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/MonitorNuGetProcessExitRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/MonitorNuGetProcessExitRequest.cs deleted file mode 100644 index e494eee24ce..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/MonitorNuGetProcessExitRequest.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request to monitor a NuGet process exit. - /// - public sealed class MonitorNuGetProcessExitRequest - { - /// - /// Gets the process ID. - /// - [JsonRequired] - public int ProcessId { get; } - - /// - /// Initializes a new class. - /// - /// The process ID. - [JsonConstructor] - public MonitorNuGetProcessExitRequest(int processId) - { - ProcessId = processId; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/MonitorNuGetProcessExitResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/MonitorNuGetProcessExitResponse.cs deleted file mode 100644 index ffaf22126fd..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/MonitorNuGetProcessExitResponse.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A response to a monitor NuGet process exit request. - /// - public sealed class MonitorNuGetProcessExitResponse - { - /// - /// Gets the response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The plugin's response code. - /// Thrown if - /// is an undefined value. - [JsonConstructor] - public MonitorNuGetProcessExitResponse(MessageResponseCode responseCode) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - ResponseCode = responseCode; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/PrefetchPackageRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/PrefetchPackageRequest.cs deleted file mode 100644 index 46b75971046..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/PrefetchPackageRequest.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request to a plugin to prefetch a package. - /// - public sealed class PrefetchPackageRequest - { - /// - /// Gets the package ID. - /// - [JsonRequired] - public string PackageId { get; } - - /// - /// Gets the package source repository location. - /// - [JsonRequired] - public string PackageSourceRepository { get; } - - /// - /// Gets the package version. - /// - [JsonRequired] - public string PackageVersion { get; } - - /// - /// Initializes a new class. - /// - /// The package source repository location. - /// The package ID. - /// The package version. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null or an empty string. - [JsonConstructor] - public PrefetchPackageRequest( - string packageSourceRepository, - string packageId, - string packageVersion) - { - if (string.IsNullOrEmpty(packageSourceRepository)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageSourceRepository)); - } - - if (string.IsNullOrEmpty(packageId)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageId)); - } - - if (string.IsNullOrEmpty(packageVersion)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageVersion)); - } - - PackageSourceRepository = packageSourceRepository; - PackageId = packageId; - PackageVersion = packageVersion; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/PrefetchPackageResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/PrefetchPackageResponse.cs deleted file mode 100644 index c80990bb40b..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/PrefetchPackageResponse.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A plugin's response to a package prefetch request. - /// - public sealed class PrefetchPackageResponse - { - /// - /// Gets the plugin's response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The plugin's response code. - /// Thrown if - /// is an undefined value. - [JsonConstructor] - public PrefetchPackageResponse(MessageResponseCode responseCode) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - ResponseCode = responseCode; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/Progress.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/Progress.cs deleted file mode 100644 index e2f638c1edf..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/Progress.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A progress notification. - /// - public sealed class Progress - { - /// - /// Gets the progress percentage. - /// - public double? Percentage { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The progress percentage. - [JsonConstructor] - public Progress(double? percentage = null) - { - if (!IsValidPercentage(percentage)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(percentage)); - } - - Percentage = percentage; - } - - private static bool IsValidPercentage(double? percentage) - { - if (percentage.HasValue && - (double.IsNaN(percentage.Value) || double.IsInfinity(percentage.Value) || - percentage.Value < 0 || percentage.Value > 1)) - { - return false; - } - - return true; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetCredentialsRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetCredentialsRequest.cs deleted file mode 100644 index 03ad9bbe8ae..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetCredentialsRequest.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request to set credentials for a package source with any last known good credentials. - /// - public sealed class SetCredentialsRequest - { - /// - /// Gets the package source repository location. - /// - [JsonRequired] - public string PackageSourceRepository { get; } - - /// - /// Gets the package source repository password. - /// - public string Password { get; } - - /// - /// Gets the proxy password. - /// - public string ProxyPassword { get; } - - /// - /// Gets the proxy username. - /// - public string ProxyUsername { get; } - - /// - /// Gets the package source repository username. - /// - public string Username { get; } - - /// - /// Initializes a new class. - /// - /// The package source repository location. - /// The proxy username. - /// The proxy password. - /// The package source repository username. - /// The package source repository password. - public SetCredentialsRequest( - string packageSourceRepository, - string proxyUsername, - string proxyPassword, - string username, - string password) - { - if (string.IsNullOrEmpty(packageSourceRepository)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageSourceRepository)); - } - - PackageSourceRepository = packageSourceRepository; - ProxyUsername = proxyUsername; - ProxyPassword = proxyPassword; - Username = username; - Password = password; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetCredentialsResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetCredentialsResponse.cs deleted file mode 100644 index 13d44c3f65d..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetCredentialsResponse.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A plugin's response to a set credentials request. - /// - public sealed class SetCredentialsResponse - { - /// - /// Gets the plugin's response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The plugin's response code. - /// Thrown if - /// is an undefined value. - [JsonConstructor] - public SetCredentialsResponse(MessageResponseCode responseCode) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - ResponseCode = responseCode; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetLogLevelRequest.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetLogLevelRequest.cs deleted file mode 100644 index ed89224714a..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetLogLevelRequest.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; -using NuGet.Common; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request to set the log level. - /// - public sealed class SetLogLevelRequest - { - /// - /// Gets the log level. - /// - [JsonRequired] - public LogLevel LogLevel { get; } - - /// - /// Initializes a new class. - /// - /// The log level. - /// Thrown if is an undefined - /// value. - [JsonConstructor] - public SetLogLevelRequest(LogLevel logLevel) - { - if (!Enum.IsDefined(typeof(LogLevel), logLevel)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - logLevel), - nameof(logLevel)); - } - - LogLevel = logLevel; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetLogLevelResponse.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetLogLevelResponse.cs deleted file mode 100644 index 3906d197837..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Messages/SetLogLevelResponse.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A response to a log level set request. - /// - public sealed class SetLogLevelResponse - { - /// - /// Gets the response code. - /// - [JsonRequired] - public MessageResponseCode ResponseCode { get; } - - /// - /// Initializes a new class. - /// - /// The response code. - /// Thrown if - /// is an undefined value. - [JsonConstructor] - public SetLogLevelResponse(MessageResponseCode responseCode) - { - if (!Enum.IsDefined(typeof(MessageResponseCode), responseCode)) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_UnrecognizedEnumValue, - responseCode), - nameof(responseCode)); - } - - ResponseCode = responseCode; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/NoOpDisposePlugin.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/NoOpDisposePlugin.cs deleted file mode 100644 index 07d6c1de2ab..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/NoOpDisposePlugin.cs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A plugin wrapper that no-ops IDisposable. - /// - public sealed class NoOpDisposePlugin : IPlugin - { - private readonly IPlugin _plugin; - - /// - /// Occurs before the plugin closes. - /// - public event EventHandler BeforeClose - { - add - { - _plugin.BeforeClose += value; - } - remove - { - _plugin.BeforeClose -= value; - } - } - - /// - /// Occurs when the plugin has closed. - /// - public event EventHandler Closed - { - add - { - _plugin.Closed += value; - } - remove - { - _plugin.Closed -= value; - } - } - - /// - /// Gets the connection for the plugin. - /// - public IConnection Connection => _plugin.Connection; - - /// - /// Gets the file path for the plugin. - /// - public string FilePath => _plugin.FilePath; - - /// - /// Gets the unique identifier for the plugin. - /// - public string Id => _plugin.Id; - - /// - /// Gets the name of the plugin. - /// - public string Name => _plugin.Name; - - /// - /// Instantiates a new class. - /// - /// A plugin - /// Thrown if is null. - public NoOpDisposePlugin(IPlugin plugin) - { - if (plugin == null) - { - throw new ArgumentNullException(nameof(plugin)); - } - - _plugin = plugin; - } - - /// - /// Does nothing. - /// - /// Plugin disposal is implemented elsewhere. - public void Dispose() - { - } - - /// - /// Closes the plugin. - /// - /// This does not call . - public void Close() - { - _plugin.Close(); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/OperationClaim.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/OperationClaim.cs deleted file mode 100644 index 909510b872f..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/OperationClaim.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace NuGet.Protocol.Plugins -{ - /// - /// Plugin operation claims. - /// - public enum OperationClaim - { - /// - /// The download package operation claim. - /// - DownloadPackage - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/OutboundRequestContext.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/OutboundRequestContext.cs deleted file mode 100644 index f67bb4b8ad7..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/OutboundRequestContext.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Context for an outbound request. - /// - public abstract class OutboundRequestContext : IDisposable - { - /// - /// Gets the request ID. - /// - public string RequestId { get; protected set; } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - protected abstract void Dispose(bool disposing); - - /// - /// Handles cancellation for the outbound request. - /// - public abstract void HandleCancel(); - - /// - /// Handles progress notifications for the outbound request. - /// - /// A progress notification. - /// Thrown if is null. - public abstract void HandleProgress(Message progress); - - /// - /// Handles a response for the outbound request. - /// - /// A response. - /// Thrown if is null. - public abstract void HandleResponse(Message response); - - /// - /// Handles a fault response for the outbound request. - /// - /// A fault response. - /// Thrown if is null. - public abstract void HandleFault(Message fault); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/OutboundRequestContext`1.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/OutboundRequestContext`1.cs deleted file mode 100644 index 7edd72f026e..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/OutboundRequestContext`1.cs +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Context for an outbound request. - /// - /// The response payload type. - public sealed class OutboundRequestContext : OutboundRequestContext - { - private readonly CancellationToken _cancellationToken; - private readonly CancellationTokenSource _cancellationTokenSource; - private readonly IConnection _connection; - private bool _isClosed; - private bool _isDisposed; - private bool _isKeepAlive; - private readonly Message _request; - private readonly TaskCompletionSource _taskCompletionSource; - private readonly TimeSpan? _timeout; - private readonly Timer _timer; - - /// - /// Gets the completion task. - /// - public Task CompletionTask => _taskCompletionSource.Task; - - /// - /// Initializes a new class. - /// - /// A connection. - /// A request. - /// An optional request timeout. - /// A flag indicating whether or not the request supports progress notifications - /// to reset the request timeout. - /// A cancellation token. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public OutboundRequestContext( - IConnection connection, - Message request, - TimeSpan? timeout, - bool isKeepAlive, - CancellationToken cancellationToken) - { - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } - - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - _connection = connection; - _request = request; - _taskCompletionSource = new TaskCompletionSource(); - _timeout = timeout; - _isKeepAlive = isKeepAlive; - RequestId = request.RequestId; - - if (timeout.HasValue) - { - _timer = new Timer( - OnTimeout, - state: null, - dueTime: timeout.Value, - period: Timeout.InfiniteTimeSpan); - } - - _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - - _cancellationTokenSource.Token.Register(Close); - - // Capture the cancellation token now because if the cancellation token source - // is disposed race conditions may cause an exception acccessing its Token property. - _cancellationToken = _cancellationTokenSource.Token; - } - - /// - /// Handles cancellation for the outbound request. - /// - public override void HandleCancel() - { - _taskCompletionSource.TrySetCanceled(); - } - - /// - /// Handles progress notifications for the outbound request. - /// - /// A progress notification. - /// Thrown if is null. - public override void HandleProgress(Message progress) - { - if (progress == null) - { - throw new ArgumentNullException(nameof(progress)); - } - - var payload = MessageUtilities.DeserializePayload(progress); - - if (_timeout.HasValue && _isKeepAlive) - { - _timer.Change(_timeout.Value, Timeout.InfiniteTimeSpan); - } - } - - /// - /// Handles a response for the outbound request. - /// - /// A response. - /// Thrown if is null. - public override void HandleResponse(Message response) - { - if (response == null) - { - throw new ArgumentNullException(nameof(response)); - } - - var payload = MessageUtilities.DeserializePayload(response); - - _taskCompletionSource.TrySetResult(payload); - } - - /// - /// Handles a fault response for the outbound request. - /// - /// A fault response. - /// Thrown if is null. - public override void HandleFault(Message fault) - { - if (fault == null) - { - throw new ArgumentNullException(nameof(fault)); - } - - var payload = MessageUtilities.DeserializePayload(fault); - - throw new ProtocolException(payload.Message); - } - - protected override void Dispose(bool disposing) - { - if (_isDisposed) - { - return; - } - - if (disposing) - { - Close(); - - // Do not dispose of _connection. - } - - _isDisposed = true; - } - - private void Close() - { - if (!_isClosed) - { - _taskCompletionSource.TrySetCanceled(); - - if (_timer != null) - { - _timer.Dispose(); - } - - try - { - using (_cancellationTokenSource) - { - _cancellationTokenSource.Cancel(); - } - } - catch (Exception) - { - } - - _isClosed = true; - } - } - - private void OnTimeout(object state) - { - Debug.WriteLine($"Request {_request.RequestId} timed out."); - - _taskCompletionSource.TrySetCanceled(); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Plugin.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Plugin.cs deleted file mode 100644 index 9ee851c29a7..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Plugin.cs +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a plugin. - /// - public sealed class Plugin : IPlugin - { - private bool _isClosed; - private readonly TimeSpan _idleTimeout; - private readonly Timer _idleTimer; - private readonly object _idleTimerLock; - private bool _isDisposed; - private readonly bool _isOwnProcess; - private readonly IPluginProcess _process; - - /// - /// Occurs before the plugin closes. - /// - public event EventHandler BeforeClose; - - /// - /// Occurs when the plugin has closed. - /// - public event EventHandler Closed; - - /// - /// Occurs when a plugin process has exited. - /// - public event EventHandler Exited; - - /// - /// Occurs when a plugin or plugin connection has faulted. - /// - public event EventHandler Faulted; - - /// - /// Occurs when a plugin has been idle for the configured idle timeout period. - /// - public event EventHandler Idle; - - /// - /// Gets the connection for the plugin - /// - public IConnection Connection { get; } - - /// - /// Gets the file path for the plugin. - /// - public string FilePath { get; } - - /// - /// Gets the unique identifier for the plugin. - /// - public string Id { get; } - - /// - /// Gets the name of the plugin. - /// - public string Name { get; } - - /// - /// Instantiates a new class. - /// - /// The plugin file path. - /// The plugin connection. - /// The plugin process. - /// true if is the current process; - /// otherwise, false. - /// The plugin idle timeout. Can be . - /// Thrown if is either null - /// or an empty string. - /// Thrown if is null. - /// Thrown if is null. - /// Thrown if is smaller than - /// . - public Plugin(string filePath, IConnection connection, IPluginProcess process, bool isOwnProcess, TimeSpan idleTimeout) - { - if (string.IsNullOrEmpty(filePath)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(filePath)); - } - - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } - - if (process == null) - { - throw new ArgumentNullException(nameof(process)); - } - - if (idleTimeout < Timeout.InfiniteTimeSpan) - { - throw new ArgumentOutOfRangeException( - nameof(idleTimeout), - idleTimeout, - Strings.Plugin_IdleTimeoutMustBeGreaterThanOrEqualToInfiniteTimeSpan); - } - - Name = Path.GetFileNameWithoutExtension(filePath); - FilePath = filePath; - Id = Guid.NewGuid().ToString("N"); - Connection = connection; - _process = process; - _isOwnProcess = isOwnProcess; - _idleTimerLock = new object(); - _idleTimeout = idleTimeout; - - if (idleTimeout != Timeout.InfiniteTimeSpan) - { - _idleTimer = new Timer(OnIdleTimer, state: null, dueTime: idleTimeout, period: Timeout.InfiniteTimeSpan); - } - - Connection.Faulted += OnFaulted; - Connection.MessageReceived += OnMessageReceived; - - if (!isOwnProcess) - { - process.Exited += OnExited; - } - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (_isDisposed) - { - return; - } - - Close(); - - Connection.Dispose(); - - lock (_idleTimerLock) - { - _idleTimer?.Dispose(); - } - - if (!_isOwnProcess) - { - _process.Exited -= OnExited; - - _process.Kill(); - _process.Dispose(); - } - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - - /// - /// Closes the plugin. - /// - /// This does not call . - public void Close() - { - if (!_isClosed) - { - Connection.Faulted -= OnFaulted; - Connection.MessageReceived -= OnMessageReceived; - - FireBeforeClose(); - - Connection.Close(); - - FireClosed(); - - _isClosed = true; - } - } - - private void FireBeforeClose() - { - try - { - BeforeClose?.Invoke(this, EventArgs.Empty); - } - catch (Exception) - { - } - } - - private void FireClosed() - { - try - { - Closed?.Invoke(this, EventArgs.Empty); - } - catch (Exception) - { - } - } - - private void OnExited(object sender, EventArgs e) - { - Exited?.Invoke(this, new PluginEventArgs(this)); - } - - private void OnFaulted(object sender, ProtocolErrorEventArgs e) - { - Faulted?.Invoke(this, new PluginEventArgs(this)); - } - - private void OnIdleTimer(object state) - { - Idle?.Invoke(this, new PluginEventArgs(this)); - } - - private void OnMessageReceived(object sender, MessageEventArgs e) - { - lock (_idleTimerLock) - { - _idleTimer?.Change(_idleTimeout, Timeout.InfiniteTimeSpan); - } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginConstants.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginConstants.cs deleted file mode 100644 index 73dcb3ffd5f..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginConstants.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Plugin constants. - /// - public static class PluginConstants - { - /// - /// Default close timeout for plugins. - /// - public static readonly TimeSpan CloseTimeout = TimeSpan.FromSeconds(2); - - /// - /// Default idle timeout for plugins. - /// - public static readonly TimeSpan IdleTimeout = TimeSpan.FromMinutes(1); - - /// - /// Default command-line arguments for plugins. - /// - public static readonly IEnumerable PluginArguments = new[] { "-Plugin" }; - - /// - /// The progress notification interval. - /// - /// This value must be less than half of . - public static readonly TimeSpan ProgressInterval = TimeSpan.FromSeconds(10); - - /// - /// The default request timeout set by an initialize request after handshaking. - /// - public static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(30); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginCreationResult.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginCreationResult.cs deleted file mode 100644 index 0a57f1689ec..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginCreationResult.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A plugin's creation result. - /// - public sealed class PluginCreationResult - { - /// - /// Gets the plugin's operation claims. - /// - public IReadOnlyList Claims { get; } - - /// - /// Gets a message if is null; otherwise, null. - /// - public string Message { get; } - - /// - /// Gets a plugin. - /// - public IPlugin Plugin { get; } - - /// - /// Gets a plugin multiclient utilities. - /// - public IPluginMulticlientUtilities PluginMulticlientUtilities { get; } - - /// - /// Instantiates a new class. - /// - /// A plugin. - /// A plugin multiclient utilities. - /// The plugin's operation claims. - /// Thrown if is null. - /// Thrown if is null. - /// Thrown if is null. - public PluginCreationResult(IPlugin plugin, IPluginMulticlientUtilities utilities, IReadOnlyList claims) - { - if (plugin == null) - { - throw new ArgumentNullException(nameof(plugin)); - } - - if (utilities == null) - { - throw new ArgumentNullException(nameof(utilities)); - } - - if (claims == null) - { - throw new ArgumentNullException(nameof(claims)); - } - - Plugin = plugin; - PluginMulticlientUtilities = utilities; - Claims = claims; - } - - /// - /// Instantiates a new class. - /// - /// A message why a plugin could not be created. - /// Thrown if - /// is either null or an empty string. - public PluginCreationResult(string message) - { - if (string.IsNullOrEmpty(message)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(message)); - } - - Message = message; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginDiscoverer.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginDiscoverer.cs deleted file mode 100644 index 893c92a25c0..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginDiscoverer.cs +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Common; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Discovers plugins and their operation claims. - /// - public sealed class PluginDiscoverer : IPluginDiscoverer - { - private bool _isDisposed; - private List _pluginFiles; - private readonly string _rawPluginPaths; - private IEnumerable _results; - private readonly SemaphoreSlim _semaphore; - private readonly EmbeddedSignatureVerifier _verifier; - - /// - /// Instantiates a new class. - /// - /// The raw semicolon-delimited list of supposed plugin file paths. - /// An embedded signature verifier. - /// Thrown if is null. - public PluginDiscoverer(string rawPluginPaths, EmbeddedSignatureVerifier verifier) - { - if (verifier == null) - { - throw new ArgumentNullException(nameof(verifier)); - } - - _rawPluginPaths = rawPluginPaths; - _verifier = verifier; - _semaphore = new SemaphoreSlim(initialCount: 1, maxCount: 1); - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (_isDisposed) - { - return; - } - - _semaphore.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - - /// - /// Asynchronously discovers plugins. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// from the target. - /// Thrown if - /// is cancelled. - public async Task> DiscoverAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - if (_results != null) - { - return _results; - } - - await _semaphore.WaitAsync(cancellationToken); - - try - { - if (_results != null) - { - return _results; - } - - _pluginFiles = GetPluginFiles(cancellationToken); - var results = new List(); - - for (var i = 0; i < _pluginFiles.Count; ++i) - { - var pluginFile = _pluginFiles[i]; - string message = null; - - switch (pluginFile.State) - { - case PluginFileState.Valid: - break; - - case PluginFileState.NotFound: - message = string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_FileNotFound, - pluginFile.Path); - break; - - case PluginFileState.InvalidFilePath: - message = string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_InvalidPluginFilePath, - pluginFile.Path); - break; - - case PluginFileState.InvalidEmbeddedSignature: - message = string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_InvalidEmbeddedSignature, - pluginFile.Path); - break; - - default: - throw new NotImplementedException(); - } - - var result = new PluginDiscoveryResult(pluginFile, message); - - results.Add(result); - } - - _results = results; - } - finally - { - _semaphore.Release(); - } - - return _results; - } - - private List GetPluginFiles(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var filePaths = GetPluginFilePaths(); - - var files = new List(); - - foreach (var filePath in filePaths) - { - cancellationToken.ThrowIfCancellationRequested(); - - if (PathValidator.IsValidLocalPath(filePath) || PathValidator.IsValidUncPath(filePath)) - { - if (File.Exists(filePath)) - { - var isValid = _verifier.IsValid(filePath); - var state = isValid ? PluginFileState.Valid : PluginFileState.InvalidEmbeddedSignature; - - files.Add(new PluginFile(filePath, state)); - } - else - { - files.Add(new PluginFile(filePath, PluginFileState.NotFound)); - } - } - else - { - files.Add(new PluginFile(filePath, PluginFileState.InvalidFilePath)); - } - } - - return files; - } - - private IEnumerable GetPluginFilePaths() - { - if (string.IsNullOrEmpty(_rawPluginPaths)) - { - return Enumerable.Empty(); - } - - return _rawPluginPaths.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginDiscoveryResult.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginDiscoveryResult.cs deleted file mode 100644 index b009e233d96..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginDiscoveryResult.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A plugin discovery result. - /// - public sealed class PluginDiscoveryResult - { - /// - /// Gets the plugin file. - /// - public PluginFile PluginFile { get; } - - /// - /// Gets a message if is not ; - /// otherwise, null. - /// - public string Message { get; } - - /// - /// Instantiates a new class. - /// - /// A plugin file. - /// A message if is not - /// ; otherwise, null. - /// Thrown if - /// is null. - public PluginDiscoveryResult(PluginFile pluginFile, string message = null) - { - if (pluginFile == null) - { - throw new ArgumentNullException(nameof(pluginFile)); - } - - PluginFile = pluginFile; - Message = message; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginEventArgs.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginEventArgs.cs deleted file mode 100644 index 7ab480e60a7..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginEventArgs.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Plugin event arguments. - /// - public sealed class PluginEventArgs : EventArgs - { - /// - /// Gets the plugin. - /// - public IPlugin Plugin { get; } - - /// - /// Instantiates a new class. - /// - /// A plugin. - /// Thrown if is null. - public PluginEventArgs(IPlugin plugin) - { - if (plugin == null) - { - throw new ArgumentNullException(nameof(plugin)); - } - - Plugin = plugin; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginException.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginException.cs deleted file mode 100644 index 26a3bb7b329..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginException.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A plugin exception. - /// - public sealed class PluginException : Exception - { - /// - /// Instantiates a new class. - /// - /// The exception message. - public PluginException(string message) - : base(message) - { - } - - /// - /// Instantiates a new class. - /// - /// The exception message. - /// The inner exception. - public PluginException(string message, Exception innerException) - : base(message, innerException) - { - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginFactory.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginFactory.cs deleted file mode 100644 index 740e360db39..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginFactory.cs +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A plugin factory. - /// - public sealed class PluginFactory : IPluginFactory - { - private bool _isDisposed; - private readonly TimeSpan _pluginIdleTimeout; - private readonly ConcurrentDictionary>> _plugins; - - /// - /// Instantiates a new class. - /// - /// The plugin idle timeout. - /// Thrown if - /// is less than . - public PluginFactory(TimeSpan pluginIdleTimeout) - { - if (pluginIdleTimeout < Timeout.InfiniteTimeSpan) - { - throw new ArgumentOutOfRangeException( - nameof(pluginIdleTimeout), - pluginIdleTimeout, - Strings.Plugin_IdleTimeoutMustBeGreaterThanOrEqualToInfiniteTimeSpan); - } - - _pluginIdleTimeout = pluginIdleTimeout; - _plugins = new ConcurrentDictionary>>(); - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (_isDisposed) - { - return; - } - - foreach (var entry in _plugins) - { - var lazyTask = entry.Value; - - if (lazyTask.IsValueCreated && lazyTask.Value.Status == TaskStatus.RanToCompletion) - { - var plugin = lazyTask.Value.Result; - - plugin.Dispose(); - } - } - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - - /// - /// Asynchronously gets an existing plugin instance or creates a new instance and connects to it. - /// - /// The file path of the plugin. - /// Command-line arguments to be supplied to the plugin. - /// Request handlers. - /// Connection options. - /// A cancellation token for the plugin's lifetime. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - /// Thrown if this object is disposed. - /// This is intended to be called by NuGet client tools. - public async Task GetOrCreateAsync( - string filePath, - IEnumerable arguments, - IRequestHandlers requestHandlers, - ConnectionOptions options, - CancellationToken sessionCancellationToken) - { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(PluginFactory)); - } - - if (string.IsNullOrEmpty(filePath)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(filePath)); - } - - if (arguments == null) - { - throw new ArgumentNullException(nameof(arguments)); - } - - if (requestHandlers == null) - { - throw new ArgumentNullException(nameof(requestHandlers)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - sessionCancellationToken.ThrowIfCancellationRequested(); - - var lazyTask = _plugins.GetOrAdd( - filePath, - (path) => new Lazy>( - () => CreatePluginAsync(filePath, arguments, requestHandlers, options, sessionCancellationToken))); - - await lazyTask.Value; - - // Manage plugin lifetime by its idleness. Thus, don't allow callers to prematurely dispose of a plugin. - return new NoOpDisposePlugin(lazyTask.Value.Result); - } - - private async Task CreatePluginAsync( - string filePath, - IEnumerable arguments, - IRequestHandlers requestHandlers, - ConnectionOptions options, - CancellationToken sessionCancellationToken) - { - var startInfo = new ProcessStartInfo(filePath) - { - Arguments = string.Join(" ", arguments), - UseShellExecute = false, - RedirectStandardError = false, - RedirectStandardInput = true, - RedirectStandardOutput = true, - StandardOutputEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false) - }; - - var process = Process.Start(startInfo); - var sender = new Sender(process.StandardInput); - var receiver = new StandardOutputReceiver(new PluginProcess(process)); - var messageDispatcher = new MessageDispatcher(requestHandlers, new RequestIdGenerator()); - var connection = new Connection(messageDispatcher, sender, receiver, options); - var pluginProcess = new PluginProcess(process); - - var plugin = new Plugin( - filePath, - connection, - pluginProcess, - isOwnProcess: false, - idleTimeout: _pluginIdleTimeout); - - try - { - // Wire up handlers before calling ConnectAsync(...). - RegisterEventHandlers(plugin); - - await connection.ConnectAsync(sessionCancellationToken); - - process.EnableRaisingEvents = true; - } - catch (ProtocolException ex) - { - throw new ProtocolException( - string.Format(CultureInfo.CurrentCulture, Strings.Plugin_Exception, plugin.Name, ex.Message)); - } - catch (Exception) - { - plugin.Dispose(); - - throw; - } - - return plugin; - } - - /// - /// Asynchronously creates a plugin instance and connects to it. - /// - /// Request handlers. - /// Connection options. - /// A cancellation token for the plugin's lifetime. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// instance. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. - /// This is intended to be called by a plugin. - public static async Task CreateFromCurrentProcessAsync( - IRequestHandlers requestHandlers, - ConnectionOptions options, - CancellationToken sessionCancellationToken) - { - if (requestHandlers == null) - { - throw new ArgumentNullException(nameof(requestHandlers)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - sessionCancellationToken.ThrowIfCancellationRequested(); - - var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); - var standardInput = new StreamReader(Console.OpenStandardInput(), encoding); - var standardOutput = new StreamWriter(Console.OpenStandardOutput(), encoding); - var sender = new Sender(standardOutput); - var receiver = new StandardInputReceiver(standardInput); - var messageDispatcher = new MessageDispatcher(requestHandlers, new RequestIdGenerator()); - var connection = new Connection(messageDispatcher, sender, receiver, options); - - var process = Process.GetCurrentProcess(); - var filePath = process.MainModule.FileName; - var pluginProcess = new PluginProcess(process); - - // Wire up handlers before calling ConnectAsync(...). - var plugin = new Plugin( - filePath, - connection, - pluginProcess, - isOwnProcess: true, - idleTimeout: Timeout.InfiniteTimeSpan); - - requestHandlers.TryAdd(MessageMethod.Close, new CloseRequestHandler(plugin)); - requestHandlers.TryAdd(MessageMethod.MonitorNuGetProcessExit, new MonitorNuGetProcessExitRequestHandler(plugin)); - - try - { - await connection.ConnectAsync(sessionCancellationToken); - } - catch (Exception) - { - plugin.Dispose(); - - throw; - } - - return plugin; - } - - private void Dispose(IPlugin plugin) - { - UnregisterEventHandlers(plugin as Plugin); - - Lazy> lazyTask; - - if (_plugins.TryRemove(plugin.FilePath, out lazyTask)) - { - if (lazyTask.IsValueCreated && lazyTask.Value.Status == TaskStatus.RanToCompletion) - { - using (var pluginSingleton = lazyTask.Value.Result) - { - SendCloseRequest(pluginSingleton); - } - } - } - else - { - plugin.Dispose(); - } - } - - private void OnPluginFaulted(object sender, PluginEventArgs e) - { - Dispose(e.Plugin); - } - - private void OnPluginExited(object sender, PluginEventArgs e) - { - Dispose(e.Plugin); - } - - private void OnPluginIdle(object sender, PluginEventArgs e) - { - Dispose(e.Plugin); - } - - private void SendCloseRequest(IPlugin plugin) - { - var message = plugin.Connection.MessageDispatcher.CreateMessage( - MessageType.Request, - MessageMethod.Close); - - using (var cancellationTokenSource = new CancellationTokenSource(PluginConstants.CloseTimeout)) - { - try - { - plugin.Connection.SendAsync(message, cancellationTokenSource.Token).Wait(); - } - catch (Exception) - { - } - } - } - - private void RegisterEventHandlers(Plugin plugin) - { - plugin.Exited += OnPluginExited; - plugin.Faulted += OnPluginFaulted; - plugin.Idle += OnPluginIdle; - } - - private void UnregisterEventHandlers(Plugin plugin) - { - if (plugin != null) - { - plugin.Exited -= OnPluginExited; - plugin.Faulted -= OnPluginFaulted; - plugin.Idle -= OnPluginIdle; - } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginFile.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginFile.cs deleted file mode 100644 index d524643bfde..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginFile.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a plugin file. - /// - public sealed class PluginFile - { - /// - /// Gets the plugin's file path. - /// - public string Path { get; } - - /// - /// Gets the plugin file state. - /// - public PluginFileState State { get; } - - /// - /// Instantiates a new class. - /// - /// The plugin's file path. - /// The plugin file state. - public PluginFile(string filePath, PluginFileState state) - { - if (string.IsNullOrEmpty(filePath)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(filePath)); - } - - Path = filePath; - State = state; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginFileState.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginFileState.cs deleted file mode 100644 index 41e1b8b09db..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginFileState.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace NuGet.Protocol.Plugins -{ - /// - /// State of a plugin file path. - /// - public enum PluginFileState - { - /// - /// The file exists and has a valid embedded signature. - /// - Valid, - - /// - /// The file was not found. - /// - NotFound, - - /// - /// The file path was invalid (e.g.: not rooted). - /// - InvalidFilePath, - - /// - /// The file exists but it has either no embedded signature or an invalid embedded signature. - /// - InvalidEmbeddedSignature - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginMulticlientUtilities.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginMulticlientUtilities.cs deleted file mode 100644 index 08d69865dfd..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginMulticlientUtilities.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Plugin multiclient utilities. - /// - public sealed class PluginMulticlientUtilities : IPluginMulticlientUtilities - { - private readonly ConcurrentDictionary> _actions; - - /// - /// Initializes a new class. - /// - public PluginMulticlientUtilities() - { - _actions = new ConcurrentDictionary>(); - } - - /// - /// Asynchronously executes a task once per plugin lifetime per key. - /// - /// A key that identifies the task. - /// A function that returns a task. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is either null. - /// Thrown if - /// is cancelled. - public async Task DoOncePerPluginLifetimeAsync( - string key, - Func taskFunc, - CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(key)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(key)); - } - - if (taskFunc == null) - { - throw new ArgumentNullException(nameof(taskFunc)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var lazyTask = _actions.GetOrAdd(key, _ => new Lazy(() => taskFunc())); - - await lazyTask.Value; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginPackageDownloader.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginPackageDownloader.cs deleted file mode 100644 index cf5ef8fa716..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginPackageDownloader.cs +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Packaging; -using NuGet.Packaging.Core; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A package downloader that delegates to a plugin. - /// - public sealed class PluginPackageDownloader : IPackageDownloader - { - private bool _isDisposed; - private readonly PackageIdentity _packageIdentity; - private readonly PluginPackageReader _packageReader; - private readonly string _packageSourceRepository; - private readonly IPlugin _plugin; - - /// - /// Gets an asynchronous package content reader. - /// - /// Thrown if this object is disposed. - public IAsyncPackageContentReader ContentReader - { - get - { - ThrowIfDisposed(); - - return _packageReader; - } - } - - /// - /// Gets an asynchronous package core reader. - /// - /// Thrown if this object is disposed. - public IAsyncPackageCoreReader CoreReader - { - get - { - ThrowIfDisposed(); - - return _packageReader; - } - } - - /// - /// Initializes a new class. - /// - /// A plugin. - /// A package identity. - /// A plugin package reader. - /// A package source repository location. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is either null or an empty string. - public PluginPackageDownloader( - IPlugin plugin, - PackageIdentity packageIdentity, - PluginPackageReader packageReader, - string packageSourceRepository) - { - if (plugin == null) - { - throw new ArgumentNullException(nameof(plugin)); - } - - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (packageReader == null) - { - throw new ArgumentNullException(nameof(packageReader)); - } - - if (string.IsNullOrEmpty(packageSourceRepository)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageSourceRepository)); - } - - _plugin = plugin; - _packageIdentity = packageIdentity; - _packageReader = packageReader; - _packageSourceRepository = packageSourceRepository; - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (!_isDisposed) - { - _packageReader.Dispose(); - _plugin.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - /// - /// Asynchronously copies a .nupkg to a target file path. - /// - /// The destination file path. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// indicating whether or not the copy was successful. - /// Thrown if this object is disposed. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. - public async Task CopyNupkgFileToAsync(string destinationFilePath, CancellationToken cancellationToken) - { - ThrowIfDisposed(); - - if (string.IsNullOrEmpty(destinationFilePath)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(destinationFilePath)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var filePath = await _packageReader.CopyNupkgAsync(destinationFilePath, cancellationToken); - - return !string.IsNullOrEmpty(filePath); - } - - /// - /// Asynchronously gets a package hash. - /// - /// The hash algorithm. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// representing the package hash. - /// Thrown if this object is disposed. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. - public async Task GetPackageHashAsync(string hashAlgorithm, CancellationToken cancellationToken) - { - ThrowIfDisposed(); - - if (string.IsNullOrEmpty(hashAlgorithm)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(hashAlgorithm)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var request = new GetPackageHashRequest( - _packageSourceRepository, - _packageIdentity.Id, - _packageIdentity.Version.ToNormalizedString(), - hashAlgorithm); - - var response = await _plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.GetPackageHash, - request, - cancellationToken); - - if (response != null && response.ResponseCode == MessageResponseCode.Success) - { - return response.Hash; - } - - return null; - } - - private void ThrowIfDisposed() - { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(PluginPackageDownloader)); - } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginPackageReader.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginPackageReader.cs deleted file mode 100644 index 894b12784df..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginPackageReader.cs +++ /dev/null @@ -1,1164 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Common; -using NuGet.Frameworks; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Versioning; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A package reader that delegates package read operations to a plugin. - /// - public sealed class PluginPackageReader : PackageReaderBase - { - private readonly ConcurrentDictionary>> _fileStreams; - private IEnumerable _files; - private readonly SemaphoreSlim _getFilesSemaphore; - private readonly SemaphoreSlim _getNuspecReaderSemaphore; - private bool _isDisposed; - private NuspecReader _nuspecReader; - private readonly PackageIdentity _packageIdentity; - private readonly string _packageSourceRepository; - private readonly IPlugin _plugin; - private readonly Lazy _tempDirectoryPath; - - /// - /// Initializes a new class. - /// - /// A plugin. - /// A package identity. - /// A package source repository location. - /// Thrown if is null. - /// Thrown if - /// is null. - /// Thrown if - /// is either null or an empty string. - public PluginPackageReader(IPlugin plugin, PackageIdentity packageIdentity, string packageSourceRepository) - : base(DefaultFrameworkNameProvider.Instance, DefaultCompatibilityProvider.Instance) - { - if (plugin == null) - { - throw new ArgumentNullException(nameof(plugin)); - } - - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (string.IsNullOrEmpty(packageSourceRepository)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(packageSourceRepository)); - } - - _plugin = plugin; - _packageIdentity = packageIdentity; - _packageSourceRepository = packageSourceRepository; - _getFilesSemaphore = new SemaphoreSlim(initialCount: 1, maxCount: 1); - _getNuspecReaderSemaphore = new SemaphoreSlim(initialCount: 1, maxCount: 1); - _fileStreams = new ConcurrentDictionary>>(StringComparer.OrdinalIgnoreCase); - _tempDirectoryPath = new Lazy(GetTemporaryDirectoryPath); - } - - /// - /// Gets a stream for a file in the package. - /// - /// The file path in the package. - /// A stream. - /// Thrown always. - public override Stream GetStream(string path) - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets a stream for a file in the package. - /// - /// The file path in the package. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a . - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is cancelled. - public override async Task GetStreamAsync(string path, CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(path)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var lazyCreator = _fileStreams.GetOrAdd( - path, - p => new Lazy>( - () => GetStreamInternalAsync(p, cancellationToken))); - - await lazyCreator.Value; - - if (lazyCreator.Value.Result == null) - { - return null; - } - - return lazyCreator.Value.Result.Create(); - } - - /// - /// Gets files in the package. - /// - /// An enumerable of files in the package. - /// Thrown always. - public override IEnumerable GetFiles() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets files in the package. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is cancelled. - public override async Task> GetFilesAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - if (_files != null) - { - return _files; - } - - await _getFilesSemaphore.WaitAsync(cancellationToken); - - try - { - if (_files != null) - { - return _files; - } - - _files = await GetFilesInternalAsync(cancellationToken); - } - finally - { - _getFilesSemaphore.Release(); - } - - return _files; - } - - /// - /// Gets files in the package. - /// - /// A folder in the package. - /// An enumerable of files in the package. - /// Thrown always. - public override IEnumerable GetFiles(string folder) - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets files in the package under the specified folder. - /// - /// A folder in the package. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if is null. - /// Thrown if - /// is cancelled. - public override async Task> GetFilesAsync( - string folder, - CancellationToken cancellationToken) - { - if (folder == null) - { - throw new ArgumentNullException(nameof(folder)); - } - - var files = await GetFilesAsync(cancellationToken); - - return files.Where(f => f.StartsWith(folder + "/", StringComparison.OrdinalIgnoreCase)); - } - - /// - /// Copies specified files in the package to the destination location. - /// - /// A directory path to copy files to. - /// An enumerable of files in the package to copy. - /// A package file extraction delegate. - /// A logger. - /// A cancellation token. - /// An enumerable of file paths in the destination location. - /// Thrown always. - public override IEnumerable CopyFiles( - string destination, - IEnumerable packageFiles, - ExtractPackageFileDelegate extractFile, - ILogger logger, - CancellationToken token) - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously copies specified files in the package to the destination location. - /// - /// A directory path to copy files to. - /// An enumerable of files in the package to copy. - /// A package file extraction delegate. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is null. - /// Thrown if is null. - /// Thrown if - /// is cancelled. - public override async Task> CopyFilesAsync( - string destination, - IEnumerable packageFiles, - ExtractPackageFileDelegate extractFile, - ILogger logger, - CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(destination)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(destination)); - } - - if (packageFiles == null) - { - throw new ArgumentNullException(nameof(packageFiles)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - if (!packageFiles.Any()) - { - return Enumerable.Empty(); - } - - var packageId = _packageIdentity.Id; - var packageVersion = _packageIdentity.Version.ToNormalizedString(); - var request = new CopyFilesInPackageRequest( - _packageSourceRepository, - packageId, - packageVersion, - packageFiles, - destination); - var response = await _plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.CopyFilesInPackage, - request, - cancellationToken); - - if (response != null) - { - switch (response.ResponseCode) - { - case MessageResponseCode.Success: - return response.CopiedFiles; - - case MessageResponseCode.Error: - throw new PluginException( - string.Format(CultureInfo.CurrentCulture, - Strings.Plugin_FailedOperationForPackage, - _plugin.Name, - MessageMethod.CopyFilesInPackage, - packageId, - packageVersion)); - - case MessageResponseCode.NotFound: - // This class is only created if a success response code is received for a - // PrefetchPackageRequest, meaning that the plugin has already confirmed - // that the package exists. - - default: - break; - } - } - - return Enumerable.Empty(); - } - - /// - /// Gets the package identity. - /// - /// A package identity. - /// Thrown always. - public override PackageIdentity GetIdentity() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets the package identity. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is cancelled. - public override async Task GetIdentityAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var nuspecReader = await GetNuspecReaderAsync(cancellationToken); - - return nuspecReader.GetIdentity(); - } - - /// - /// Gets the minimum client version in the .nuspec. - /// - /// A NuGet version. - /// Thrown always. - public override NuGetVersion GetMinClientVersion() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets the minimum client version in the .nuspec. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is cancelled. - public override async Task GetMinClientVersionAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var nuspecReader = await GetNuspecReaderAsync(cancellationToken); - - return nuspecReader.GetMinClientVersion(); - } - - /// - /// Gets the package types. - /// - /// A read-only list of package types. - /// Thrown always. - public override IReadOnlyList GetPackageTypes() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets the package types. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is cancelled. - public override async Task> GetPackageTypesAsync( - CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var nuspecReader = await GetNuspecReaderAsync(cancellationToken); - - return nuspecReader.GetPackageTypes(); - } - - /// - /// Gets a stream for the .nuspec file. - /// - /// A stream. - /// Thrown always. - public override Stream GetNuspec() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets a stream for the .nuspec file. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a . - /// Thrown if - /// is cancelled. - public override async Task GetNuspecAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var nuspecFile = await GetNuspecFileAsync(cancellationToken); - - return await GetStreamAsync(nuspecFile, cancellationToken); - } - - /// - /// Gets the .nuspec file path in the package. - /// - /// The .nuspec file path in the package. - /// Thrown always. - public override string GetNuspecFile() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets the .nuspec file path in the package. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a . - /// Thrown if - /// is cancelled. - public override async Task GetNuspecFileAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var files = await GetFilesAsync(cancellationToken); - - return GetNuspecFile(files); - } - - /// - /// Gets the .nuspec reader. - /// - public override NuspecReader NuspecReader => throw new NotSupportedException(); - - /// - /// Asynchronously gets the .nuspec reader. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a . - /// Thrown if - /// is cancelled. - public override async Task GetNuspecReaderAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - if (_nuspecReader != null) - { - return _nuspecReader; - } - - await _getNuspecReaderSemaphore.WaitAsync(cancellationToken); - - try - { - if (_nuspecReader != null) - { - return _nuspecReader; - } - - var stream = await GetNuspecAsync(cancellationToken); - - _nuspecReader = new NuspecReader(stream); - } - finally - { - _getNuspecReaderSemaphore.Release(); - } - - return _nuspecReader; - } - - /// - /// Gets supported frameworks. - /// - /// An enumerable of NuGet frameworks. - /// Thrown always. - public override IEnumerable GetSupportedFrameworks() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets supported frameworks. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is cancelled. - public override async Task> GetSupportedFrameworksAsync( - CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var frameworks = new HashSet(new NuGetFrameworkFullComparer()); - - frameworks.UnionWith((await GetLibItemsAsync(cancellationToken)).Select(g => g.TargetFramework)); - - frameworks.UnionWith((await GetBuildItemsAsync(cancellationToken)).Select(g => g.TargetFramework)); - - frameworks.UnionWith((await GetContentItemsAsync(cancellationToken)).Select(g => g.TargetFramework)); - - frameworks.UnionWith((await GetToolItemsAsync(cancellationToken)).Select(g => g.TargetFramework)); - - frameworks.UnionWith((await GetFrameworkItemsAsync(cancellationToken)).Select(g => g.TargetFramework)); - - return frameworks.Where(f => !f.IsUnsupported).OrderBy(f => f, new NuGetFrameworkSorter()); - } - - /// - /// Gets framework items. - /// - /// An enumerable of framework specific groups. - /// Thrown always. - public override IEnumerable GetFrameworkItems() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets framework items. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is cancelled. - public override async Task> GetFrameworkItemsAsync( - CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var nuspecReader = await GetNuspecReaderAsync(cancellationToken); - - return nuspecReader.GetFrameworkReferenceGroups(); - } - - /// - /// Gets a flag indicating whether or not the package is serviceable. - /// - /// A flag indicating whether or not the package is serviceable. - /// Thrown always. - public override bool IsServiceable() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets a flag indicating whether or not the package is serviceable. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a . - /// Thrown if - /// is cancelled. - public override async Task IsServiceableAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var nuspecReader = await GetNuspecReaderAsync(cancellationToken); - - return nuspecReader.IsServiceable(); - } - - /// - /// Gets build items. - /// - /// An enumerable of framework specific groups. - /// Thrown always. - public override IEnumerable GetBuildItems() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets build items. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is cancelled. - public override async Task> GetBuildItemsAsync( - CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var nuspecReader = await GetNuspecReaderAsync(cancellationToken); - var id = nuspecReader.GetIdentity().Id; - - var results = new List(); - - foreach (var group in await GetFileGroupsAsync(PackagingConstants.Folders.Build, cancellationToken)) - { - var filteredGroup = group; - - if (group.Items.Any(e => !IsAllowedBuildFile(id, e))) - { - // create a new group with only valid files - filteredGroup = new FrameworkSpecificGroup(group.TargetFramework, group.Items.Where(e => IsAllowedBuildFile(id, e))); - - if (!filteredGroup.Items.Any()) - { - // nothing was useful in the folder, skip this group completely - filteredGroup = null; - } - } - - if (filteredGroup != null) - { - results.Add(filteredGroup); - } - } - - return results; - } - - /// - /// Gets tool items. - /// - /// An enumerable of framework specific groups. - /// Thrown always. - public override IEnumerable GetToolItems() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets tool items. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is cancelled. - public override Task> GetToolItemsAsync( - CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - return GetFileGroupsAsync(PackagingConstants.Folders.Tools, cancellationToken); - } - - /// - /// Gets content items. - /// - /// An enumerable of framework specific groups. - /// Thrown always. - public override IEnumerable GetContentItems() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets content items. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is cancelled. - public override Task> GetContentItemsAsync( - CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - return GetFileGroupsAsync(PackagingConstants.Folders.Content, cancellationToken); - } - - /// - /// Gets items in the specified folder in the package. - /// - /// A folder in the package. - /// An enumerable of framework specific groups. - /// Thrown always. - public override IEnumerable GetItems(string folderName) - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets items in the specified folder in the package. - /// - /// A folder in the package. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if is null. - /// Thrown if - /// is cancelled. - public override Task> GetItemsAsync( - string folderName, - CancellationToken cancellationToken) - { - if (folderName == null) - { - throw new ArgumentNullException(nameof(folderName)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - return GetFileGroupsAsync(folderName, cancellationToken); - } - - /// - /// Gets package dependencies. - /// - /// An enumerable of package dependency groups. - /// Thrown always. - public override IEnumerable GetPackageDependencies() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets package dependencies. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is cancelled. - public override async Task> GetPackageDependenciesAsync( - CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var nuspecReader = await GetNuspecReaderAsync(cancellationToken); - - return nuspecReader.GetDependencyGroups(); - } - - /// - /// Gets lib items. - /// - /// An enumerable of framework specific groups. - /// Thrown always. - public override IEnumerable GetLibItems() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets lib items. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is cancelled. - public override Task> GetLibItemsAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - return GetFileGroupsAsync(PackagingConstants.Folders.Lib, cancellationToken); - } - - /// - /// Gets reference items. - /// - /// An enumerable of framework specific groups. - /// Thrown always. - public override IEnumerable GetReferenceItems() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets reference items. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is cancelled. - public override async Task> GetReferenceItemsAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var nuspecReader = await GetNuspecReaderAsync(cancellationToken); - var referenceGroups = nuspecReader.GetReferenceGroups(); - var fileGroups = new List(); - - // filter out non reference assemblies - foreach (var group in await GetLibItemsAsync(cancellationToken)) - { - fileGroups.Add(new FrameworkSpecificGroup(group.TargetFramework, group.Items.Where(e => IsReferenceAssembly(e)))); - } - - // results - var libItems = new List(); - - if (referenceGroups.Any()) - { - // the 'any' group from references, for pre2.5 nuspecs this will be the only group - var fallbackGroup = referenceGroups.Where(g => g.TargetFramework.Equals(NuGetFramework.AnyFramework)).FirstOrDefault(); - - foreach (var fileGroup in fileGroups) - { - // check for a matching reference group to use for filtering - var referenceGroup = NuGetFrameworkUtility.GetNearest( - items: referenceGroups, - framework: fileGroup.TargetFramework, - frameworkMappings: FrameworkProvider, - compatibilityProvider: CompatibilityProvider); - - if (referenceGroup == null) - { - referenceGroup = fallbackGroup; - } - - if (referenceGroup == null) - { - // add the lib items without any filtering - libItems.Add(fileGroup); - } - else - { - var filteredItems = new List(); - - foreach (var path in fileGroup.Items) - { - // reference groups only have the file name, not the path - var file = Path.GetFileName(path); - - if (referenceGroup.Items.Any(s => StringComparer.OrdinalIgnoreCase.Equals(s, file))) - { - filteredItems.Add(path); - } - } - - if (filteredItems.Any()) - { - libItems.Add(new FrameworkSpecificGroup(fileGroup.TargetFramework, filteredItems)); - } - } - } - } - else - { - libItems.AddRange(fileGroups); - } - - return libItems; - } - - /// - /// Gets a flag indicating whether or not the package is a development dependency. - /// - /// A flag indicating whether or not the package is a development dependency - /// Thrown always. - public override bool GetDevelopmentDependency() - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets a flag indicating whether or not the package is a development dependency. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a . - /// Thrown if - /// is cancelled. - public override async Task GetDevelopmentDependencyAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var nuspecReader = await GetNuspecReaderAsync(cancellationToken); - - return nuspecReader.GetDevelopmentDependency(); - } - - /// - /// Asynchronously copies a package to the specified destination file path. - /// - /// The destination file path. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a . - /// Thrown if - /// is either null or an empty string. - /// Thrown if - /// is cancelled. - public override async Task CopyNupkgAsync( - string nupkgFilePath, - CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(nupkgFilePath)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(nupkgFilePath)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var packageId = _packageIdentity.Id; - var packageVersion = _packageIdentity.Version.ToNormalizedString(); - var request = new CopyNupkgFileRequest( - _packageSourceRepository, - packageId, - packageVersion, - nupkgFilePath); - var response = await _plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.CopyNupkgFile, - request, - cancellationToken); - - if (response != null) - { - switch (response.ResponseCode) - { - case MessageResponseCode.Success: - return nupkgFilePath; - - case MessageResponseCode.NotFound: - CreatePackageDownloadMarkerFile(nupkgFilePath); - break; - - default: - break; - } - } - - return null; - } - - protected override void Dispose(bool disposing) - { - if (!_isDisposed) - { - foreach (var pair in _fileStreams) - { - if (pair.Value.Value.Status == TaskStatus.RanToCompletion) - { - var fileStream = pair.Value.Value.Result; - - if (fileStream != null) - { - fileStream.Dispose(); - } - } - } - - _fileStreams.Clear(); - - _plugin.Dispose(); - - _getFilesSemaphore.Dispose(); - _getNuspecReaderSemaphore.Dispose(); - - if (_tempDirectoryPath.IsValueCreated) - { - LocalResourceUtils.DeleteDirectoryTree(_tempDirectoryPath.Value, new List()); - } - - _isDisposed = true; - } - } - - private async Task> GetFileGroupsAsync( - string folder, - CancellationToken cancellationToken) - { - var groups = new Dictionary>(new NuGetFrameworkFullComparer()); - - var isContentFolder = StringComparer.OrdinalIgnoreCase.Equals(folder, PackagingConstants.Folders.Content); - var allowSubFolders = true; - - foreach (var path in await GetFilesAsync(folder, cancellationToken)) - { - // Use the known framework or if the folder did not parse, use the Any framework and consider it a sub folder - var framework = GetFrameworkFromPath(path, allowSubFolders); - - List items = null; - if (!groups.TryGetValue(framework, out items)) - { - items = new List(); - groups.Add(framework, items); - } - - items.Add(path); - } - - // Sort the groups by framework, and the items by ordinal string compare to keep things deterministic - return groups.Keys.OrderBy(e => e, new NuGetFrameworkSorter()) - .Select(framework => new FrameworkSpecificGroup(framework, groups[framework].OrderBy(e => e, StringComparer.OrdinalIgnoreCase))); - } - - private async Task GetStreamInternalAsync( - string pathInPackage, - CancellationToken cancellationToken) - { - var packageId = _packageIdentity.Id; - var packageVersion = _packageIdentity.Version.ToNormalizedString(); - - var payload = new CopyFilesInPackageRequest( - _packageSourceRepository, - packageId, - packageVersion, - new[] { pathInPackage }, - _tempDirectoryPath.Value); - - var response = await _plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.CopyFilesInPackage, - payload, - CancellationToken.None); - - if (response != null) - { - switch (response.ResponseCode) - { - case MessageResponseCode.Success: - return new FileStreamCreator(response.CopiedFiles.Single()); - - case MessageResponseCode.Error: - throw new PluginException( - string.Format(CultureInfo.CurrentCulture, - Strings.Plugin_FailedOperationForPackage, - _plugin.Name, - MessageMethod.CopyFilesInPackage, - packageId, - packageVersion)); - - case MessageResponseCode.NotFound: - // This class is only created if a success response code is received for a - // PrefetchPackageRequest, meaning that the plugin has already confirmed - // that the package exists. - - default: - break; - } - } - - return null; - } - - private async Task> GetFilesInternalAsync(CancellationToken cancellationToken) - { - var packageId = _packageIdentity.Id; - var packageVersion = _packageIdentity.Version.ToNormalizedString(); - var request = new GetFilesInPackageRequest(_packageSourceRepository, packageId, packageVersion); - var response = await _plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.GetFilesInPackage, - request, - cancellationToken); - - if (response != null) - { - switch (response.ResponseCode) - { - case MessageResponseCode.Success: - return response.Files; - - case MessageResponseCode.Error: - throw new PluginException( - string.Format(CultureInfo.CurrentCulture, - Strings.Plugin_FailedOperationForPackage, - _plugin.Name, - MessageMethod.GetFilesInPackage, - packageId, - packageVersion)); - - case MessageResponseCode.NotFound: - // This class is only created if a success response code is received for a - // PrefetchPackageRequest, meaning that the plugin has already confirmed - // that the package exists. - - default: - break; - } - } - - return Enumerable.Empty(); - } - - private void CreatePackageDownloadMarkerFile(string nupkgFilePath) - { - var directory = Path.GetDirectoryName(nupkgFilePath); - var resolver = new VersionFolderPathResolver(directory); - var fileName = resolver.GetPackageDownloadMarkerFileName(_packageIdentity.Id); - var filePath = Path.Combine(directory, fileName); - - File.WriteAllText(filePath, string.Empty); - } - - private static string GetTemporaryDirectoryPath() - { - var tempDirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); - - Directory.CreateDirectory(tempDirectoryPath); - - return tempDirectoryPath; - } - - private sealed class FileStreamCreator : IDisposable - { - private readonly string _filePath; - private bool _isDisposed; - - internal FileStreamCreator(string filePath) - { - _filePath = filePath; - } - - public void Dispose() - { - if (!_isDisposed) - { - try - { - File.Delete(_filePath); - } - catch (Exception) - { - } - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - internal FileStream Create() - { - return new FileStream( - _filePath, - FileMode.Open, - FileAccess.Read, - FileShare.Read); - } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginProcess.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginProcess.cs deleted file mode 100644 index 9dc074eb528..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginProcess.cs +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a plugin process. - /// - public sealed class PluginProcess : IPluginProcess - { - private bool _isDisposed; - private readonly Process _process; - - /// - /// Occurs when a process exits. - /// - public event EventHandler Exited - { - add - { - _process.Exited += value; - } - remove - { - _process.Exited -= value; - } - } - - /// - /// Occurs when a line of output has been received. - /// - public event EventHandler LineRead; - - /// - /// Gets a value indicating whether the associated process has been terminated. - /// - public bool HasExited - { - get - { - return _process.HasExited; - } - } - - /// - /// Instantiates a new class. - /// - /// A plugin process. - /// Thrown if is null. - public PluginProcess(Process process) - { - if (process == null) - { - throw new ArgumentNullException(nameof(process)); - } - - _process = process; - _process.OutputDataReceived += OnOutputDataReceived; - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (_isDisposed) - { - return; - } - - _process.OutputDataReceived -= OnOutputDataReceived; - _process.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - - /// - /// Asynchronously starts reading the standard output stream. - /// - public void BeginReadLine() - { - _process.BeginOutputReadLine(); - } - - /// - /// Cancels asynchronous reading of the standard output stream. - /// - public void CancelRead() - { - _process.CancelOutputRead(); - } - - /// - /// Immediately stops the associated process. - /// - public void Kill() - { - try - { - if (_process.HasExited) - { - return; - } - - _process.Kill(); - } - catch (Exception) - { - } - } - - private void OnOutputDataReceived(object sender, DataReceivedEventArgs e) - { - LineRead?.Invoke(sender, new LineReadEventArgs(e.Data)); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/ProtocolConstants.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/ProtocolConstants.cs deleted file mode 100644 index 71e67582d68..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/ProtocolConstants.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using NuGet.Versioning; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Plugin protocol constants. - /// - public static class ProtocolConstants - { - /// - /// The current protocol version. - /// - public static readonly SemanticVersion CurrentVersion = new SemanticVersion(major: 1, minor: 0, patch: 0); - - /// - /// The default handshake timeout. - /// - public static readonly TimeSpan HandshakeTimeout = TimeSpan.FromSeconds(5); - - /// - /// The maximum timeout value. - /// - /// This is set by CancellationTokenSource's constructor. - public static readonly TimeSpan MaxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); - - /// - /// The minimum timeout value. - /// - public static readonly TimeSpan MinTimeout = TimeSpan.FromTicks(1); - - /// - /// The default request timeout. - /// - public static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(5); - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/ProtocolErrorEventArgs.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/ProtocolErrorEventArgs.cs deleted file mode 100644 index cd7673ab542..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/ProtocolErrorEventArgs.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Protocol error event arguments. - /// - public sealed class ProtocolErrorEventArgs : EventArgs - { - /// - /// Gets the exception. - /// - public Exception Exception { get; } - - /// - /// Gets the message. - /// - public Message Message { get; } - - /// - /// Instantiates a new class. - /// - /// An exception. - /// Thrown if is null. - public ProtocolErrorEventArgs(Exception exception) - { - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } - - Exception = exception; - } - - /// - /// Instantiates a new class. - /// - /// An exception. - /// A message. - /// Thrown if is null. - /// Thrown if is null. - public ProtocolErrorEventArgs(Exception exception, Message message) - : this(exception) - { - if (message == null) - { - throw new ArgumentNullException(nameof(message)); - } - - Message = message; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/ProtocolException.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/ProtocolException.cs deleted file mode 100644 index 9cf4d8d0050..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/ProtocolException.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A plugin protocol exception. - /// - public sealed class ProtocolException : Exception - { - /// - /// Instantiates a new class. - /// - /// The exception message. - public ProtocolException(string message) - : base(message) - { - } - - /// - /// Instantiates a new class. - /// - /// The exception message. - /// The inner exception. - public ProtocolException(string message, Exception innerException) - : base(message, innerException) - { - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Receiver.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Receiver.cs deleted file mode 100644 index be8a5b67e71..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Receiver.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a unidirectional communications channel from a target. - /// - public abstract class Receiver : IReceiver - { - /// - /// Gets a flag indicating whether or not this instance is closed. - /// - protected bool IsClosed { get; private set; } - - /// - /// Gets or sets a flag indicating whether or not this instance is disposed. - /// - protected bool IsDisposed { get; set; } - - /// - /// Occurs when an unrecoverable fault has been caught. - /// - public event EventHandler Faulted; - - /// - /// Occurs when a message has been received. - /// - public event EventHandler MessageReceived; - - /// - /// Closes the connection. - /// - /// This does not call . - public virtual void Close() - { - IsClosed = true; - } - - /// - /// Connects. - /// - /// Thrown if this object is disposed. - /// Thrown if this object is closed. - /// Thrown if this method has already been called. - public abstract void Connect(); - - /// - /// Disposes of this instance. - /// - public abstract void Dispose(); - - protected void FireFaultEvent(Exception exception, Message message) - { - var ex = new ProtocolException(Strings.Plugin_ProtocolException, exception); - var eventArgs = message == null - ? new ProtocolErrorEventArgs(ex) : new ProtocolErrorEventArgs(ex, message); - - Faulted?.Invoke(this, eventArgs); - } - - protected void FireMessageReceivedEvent(Message message) - { - MessageReceived?.Invoke(this, new MessageEventArgs(message)); - } - - protected void ThrowIfClosed() - { - if (IsClosed) - { - throw new InvalidOperationException(Strings.Plugin_ConnectionIsClosed); - } - } - - protected void ThrowIfDisposed() - { - if (IsDisposed) - { - throw new ObjectDisposedException(GetType().Name); - } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers.cs deleted file mode 100644 index 50916290b42..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A set of . - /// - public sealed class RequestHandlers : IRequestHandlers - { - private readonly ConcurrentDictionary _handlers; - - /// - /// Instantiates a new class. - /// - public RequestHandlers() - { - _handlers = new ConcurrentDictionary(); - } - - /// - /// Atomically add or update a request handler for the specified message method. - /// - /// A message method. - /// An add request handler function. - /// An update request handler function. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - public void AddOrUpdate( - MessageMethod method, - Func addHandlerFunc, - Func updateHandlerFunc) - { - if (addHandlerFunc == null) - { - throw new ArgumentNullException(nameof(addHandlerFunc)); - } - - if (updateHandlerFunc == null) - { - throw new ArgumentNullException(nameof(updateHandlerFunc)); - } - - _handlers.AddOrUpdate(method, m => addHandlerFunc(), (m, r) => updateHandlerFunc(r)); - } - - /// - /// Attempts to add a request handler for the specified message method. - /// - /// A message method. - /// A request handler. - /// true if added; otherwise, false. - /// Thrown if is null. - public bool TryAdd(MessageMethod method, IRequestHandler handler) - { - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } - - return _handlers.TryAdd(method, handler); - } - - /// - /// Attempts to get a request handler for the specified message method. - /// - /// A message method. - /// An existing request handler. - /// true if the request handler exists; otherwise, false. - public bool TryGet(MessageMethod method, out IRequestHandler handler) - { - return _handlers.TryGetValue(method, out handler); - } - - /// - /// Attempts to remove a request handler for the specified message method. - /// - /// A message method. - /// true if a request handler was removed; otherwise, false. - public bool TryRemove(MessageMethod method) - { - IRequestHandler handler; - - return _handlers.TryRemove(method, out handler); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/CloseRequestHandler.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/CloseRequestHandler.cs deleted file mode 100644 index 20d3202f6dc..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/CloseRequestHandler.cs +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request handler for closing a plugin. - /// - public sealed class CloseRequestHandler : IRequestHandler, IDisposable - { - private bool _isDisposed; - private readonly IPlugin _plugin; - - public CancellationToken CancellationToken => CancellationToken.None; - - /// - /// Initializes a new class. - /// - /// A plugin. - /// Thrown if is null. - public CloseRequestHandler(IPlugin plugin) - { - if (plugin == null) - { - throw new ArgumentNullException(nameof(plugin)); - } - - _plugin = plugin; - } - - public void Dispose() - { - if (!_isDisposed) - { - _plugin.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - /// - /// Asynchronously handles cancelling a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown always. - public Task HandleCancelAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously handles responding to a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if is null. - /// Thrown if - /// is null. - public Task HandleResponseAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } - - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (responseHandler == null) - { - throw new ArgumentNullException(nameof(responseHandler)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - _plugin.Close(); - - return Task.FromResult(0); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetCredentialsRequestHandler.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetCredentialsRequestHandler.cs deleted file mode 100644 index be955ec2ca0..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetCredentialsRequestHandler.cs +++ /dev/null @@ -1,311 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Globalization; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Configuration; -using NuGet.Protocol.Core.Types; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request handler for get credentials requests. - /// - public sealed class GetCredentialsRequestHandler : IRequestHandler, IDisposable - { - private const string _basicAuthenticationType = "Basic"; - - private readonly ICredentialService _credentialService; - private bool _isDisposed; - private readonly IPlugin _plugin; - private readonly IWebProxy _proxy; - private readonly ConcurrentDictionary _repositories; - - /// - /// Gets the for a request. - /// - public CancellationToken CancellationToken => CancellationToken.None; - - /// - /// Initializes a new class. - /// - /// A plugin. - /// A web proxy. - /// An optional credential service. - /// Thrown if - /// is null. - public GetCredentialsRequestHandler( - IPlugin plugin, - IWebProxy proxy, - ICredentialService credentialService) - { - if (plugin == null) - { - throw new ArgumentNullException(nameof(plugin)); - } - - _plugin = plugin; - _proxy = proxy; - _credentialService = credentialService; - _repositories = new ConcurrentDictionary(); - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (!_isDisposed) - { - _plugin.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - /// - /// Adds or updates a source repository in a source repository cache. - /// - /// A source repository. - /// Thrown if - /// is null. - public void AddOrUpdateSourceRepository(SourceRepository sourceRepository) - { - if (sourceRepository == null) - { - throw new ArgumentNullException(nameof(sourceRepository)); - } - - if (sourceRepository.PackageSource != null && sourceRepository.PackageSource.IsHttp) - { - _repositories.AddOrUpdate( - sourceRepository.PackageSource.Source, - sourceRepository, - (source, repo) => sourceRepository); - } - } - - /// - /// Asynchronously handles cancelling a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown always. - public Task HandleCancelAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously handles responding to a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public async Task HandleResponseAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } - - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (responseHandler == null) - { - throw new ArgumentNullException(nameof(responseHandler)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var requestPayload = MessageUtilities.DeserializePayload(request); - var packageSource = GetPackageSource(requestPayload.PackageSourceRepository); - - GetCredentialsResponse responsePayload; - - if (packageSource.IsHttp && - string.Equals( - requestPayload.PackageSourceRepository, - packageSource.Source, - StringComparison.OrdinalIgnoreCase)) - { - NetworkCredential credential = null; - - using (var progressReporter = AutomaticProgressReporter.Create( - _plugin.Connection, - request, - PluginConstants.ProgressInterval, - cancellationToken)) - { - credential = await GetCredentialAsync( - packageSource, - requestPayload.StatusCode, - cancellationToken); - } - - if (credential == null) - { - responsePayload = new GetCredentialsResponse( - MessageResponseCode.NotFound, - username: null, - password: null); - } - else - { - responsePayload = new GetCredentialsResponse( - MessageResponseCode.Success, - credential.UserName, - credential.Password); - } - } - else - { - responsePayload = new GetCredentialsResponse( - MessageResponseCode.NotFound, - username: null, - password: null); - } - - await responseHandler.SendResponseAsync(request, responsePayload, cancellationToken); - } - - private async Task GetCredentialAsync( - PackageSource packageSource, - HttpStatusCode statusCode, - CancellationToken cancellationToken) - { - var requestType = GetCredentialRequestType(statusCode); - - if (requestType == CredentialRequestType.Proxy) - { - return await GetProxyCredentialAsync(packageSource, cancellationToken); - } - - return await GetPackageSourceCredential(requestType, packageSource, cancellationToken); - } - - private async Task GetPackageSourceCredential( - CredentialRequestType requestType, - PackageSource packageSource, - CancellationToken cancellationToken) - { - if (packageSource.Credentials != null && packageSource.Credentials.IsValid()) - { - return new NetworkCredential(packageSource.Credentials.Username, packageSource.Credentials.Password); - } - - if (_credentialService == null) - { - return null; - } - - string message; - if (requestType == CredentialRequestType.Unauthorized) - { - message = string.Format( - CultureInfo.CurrentCulture, - Strings.Http_CredentialsForUnauthorized, - packageSource.Source); - } - else - { - message = string.Format( - CultureInfo.CurrentCulture, - Strings.Http_CredentialsForForbidden, - packageSource.Source); - } - - var sourceUri = packageSource.SourceUri; - var credentials = await _credentialService.GetCredentialsAsync( - sourceUri, - _proxy, - requestType, - message, - cancellationToken); - - return credentials?.GetCredential(sourceUri, authType: null); - } - - private async Task GetProxyCredentialAsync( - PackageSource packageSource, - CancellationToken cancellationToken) - { - if (_proxy != null && _credentialService != null) - { - var sourceUri = packageSource.SourceUri; - var proxyUri = _proxy.GetProxy(sourceUri); - var message = string.Format( - CultureInfo.CurrentCulture, - Strings.Http_CredentialsForProxy, - proxyUri); - var proxyCredentials = await _credentialService.GetCredentialsAsync( - sourceUri, - _proxy, - CredentialRequestType.Proxy, - message, - cancellationToken); - - return proxyCredentials?.GetCredential(proxyUri, _basicAuthenticationType); - } - - return null; - } - - private static CredentialRequestType GetCredentialRequestType(HttpStatusCode statusCode) - { - switch (statusCode) - { - case HttpStatusCode.ProxyAuthenticationRequired: - return CredentialRequestType.Proxy; - - case HttpStatusCode.Unauthorized: - return CredentialRequestType.Unauthorized; - - case HttpStatusCode.Forbidden: - default: - return CredentialRequestType.Forbidden; - } - } - - private PackageSource GetPackageSource(string packageSourceRepository) - { - SourceRepository sourceRepository; - - if (_repositories.TryGetValue(packageSourceRepository, out sourceRepository)) - { - return sourceRepository.PackageSource; - } - - return new PackageSource(packageSourceRepository); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetServiceIndexRequestHandler.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetServiceIndexRequestHandler.cs deleted file mode 100644 index 4c04088dfc4..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetServiceIndexRequestHandler.cs +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Threading; -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; -using NuGet.Protocol.Core.Types; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request handler for get service index requests. - /// - public sealed class GetServiceIndexRequestHandler : IRequestHandler, IDisposable - { - private bool _isDisposed; - private readonly IPlugin _plugin; - private readonly ConcurrentDictionary _repositories; - - /// - /// Gets the for a request. - /// - public CancellationToken CancellationToken => CancellationToken.None; - - /// - /// Initializes a new class. - /// - /// A plugin. - /// Thrown if is null. - public GetServiceIndexRequestHandler(IPlugin plugin) - { - if (plugin == null) - { - throw new ArgumentNullException(nameof(plugin)); - } - - _plugin = plugin; - _repositories = new ConcurrentDictionary(); - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (!_isDisposed) - { - _plugin.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - /// - /// Adds or updates a source repository in a source repository cache. - /// - /// A source repository. - /// Thrown if - /// is null. - public void AddOrUpdateSourceRepository(SourceRepository sourceRepository) - { - if (sourceRepository == null) - { - throw new ArgumentNullException(nameof(sourceRepository)); - } - - if (sourceRepository.PackageSource != null && sourceRepository.PackageSource.IsHttp) - { - _repositories.AddOrUpdate( - sourceRepository.PackageSource.Source, - sourceRepository, - (source, repo) => sourceRepository); - } - } - - /// - /// Asynchronously handles cancelling a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown always. - public Task HandleCancelAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously handles responding to a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public async Task HandleResponseAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } - - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (responseHandler == null) - { - throw new ArgumentNullException(nameof(responseHandler)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var getRequest = MessageUtilities.DeserializePayload(request); - SourceRepository sourceRepository; - ServiceIndexResourceV3 serviceIndex = null; - GetServiceIndexResponse responsePayload; - - if (_repositories.TryGetValue(getRequest.PackageSourceRepository, out sourceRepository)) - { - serviceIndex = await sourceRepository.GetResourceAsync(cancellationToken); - } - - if (serviceIndex == null) - { - responsePayload = new GetServiceIndexResponse(MessageResponseCode.NotFound, serviceIndex: null); - } - else - { - var serviceIndexJson = JObject.Parse(serviceIndex.Json); - - responsePayload = new GetServiceIndexResponse(MessageResponseCode.Success, serviceIndexJson); - } - - await responseHandler.SendResponseAsync(request, responsePayload, cancellationToken); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/LogRequestHandler.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/LogRequestHandler.cs deleted file mode 100644 index 47ca1ef88d5..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/LogRequestHandler.cs +++ /dev/null @@ -1,192 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Common; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request handler for logging. - /// - public sealed class LogRequestHandler : IRequestHandler - { - private ILogger _logger; - private LogLevel _logLevel; - - /// - /// Gets the for a request. - /// - public CancellationToken CancellationToken => CancellationToken.None; - - /// - /// Instantiates a new instance of the class. - /// - /// A logger. - /// Thrown if is null. - public LogRequestHandler(ILogger logger) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - SetLogger(logger); - } - - /// - /// Asynchronously handles progress notifications for a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Cancellation requests are not supported - /// by this request handler. - public Task HandleCancelAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously handles responding to a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public async Task HandleResponseAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } - - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (responseHandler == null) - { - throw new ArgumentNullException(nameof(responseHandler)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var logRequest = MessageUtilities.DeserializePayload(request); - MessageResponseCode responseCode; - - if (logRequest.LogLevel >= _logLevel) - { - Log(logRequest); - - responseCode = MessageResponseCode.Success; - } - else - { - responseCode = MessageResponseCode.Error; - } - - var response = new LogResponse(responseCode); - - await responseHandler.SendResponseAsync(request, response, cancellationToken); - } - - /// - /// Sets the logger. - /// - /// A logger. - /// Thrown if is null. - public void SetLogger(ILogger logger) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - if (ReferenceEquals(_logger, logger)) - { - return; - } - - _logger = logger; - _logLevel = GetLogLevel(logger); - } - - /// - /// Gets the log level of a logger. - /// - /// A logger. - /// A log level. - /// Thrown if is null. - public static LogLevel GetLogLevel(ILogger logger) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - var loggerBase = logger as LoggerBase; - - if (loggerBase != null) - { - return loggerBase.VerbosityLevel; - } - - return LogLevel.Information; - } - - private void Log(LogRequest request) - { - switch (request.LogLevel) - { - case LogLevel.Debug: - _logger.LogDebug(request.Message); - break; - - case LogLevel.Verbose: - _logger.LogVerbose(request.Message); - break; - - case LogLevel.Information: - _logger.LogInformation(request.Message); - break; - - case LogLevel.Minimal: - _logger.LogMinimal(request.Message); - break; - - case LogLevel.Warning: - _logger.LogWarning(request.Message); - break; - - case LogLevel.Error: - _logger.LogError(request.Message); - break; - - default: - throw new NotImplementedException(); - } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/MonitorNuGetProcessExitRequestHandler.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/MonitorNuGetProcessExitRequestHandler.cs deleted file mode 100644 index 0211e32b201..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/MonitorNuGetProcessExitRequestHandler.cs +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A request handler for monitoring the exit of a NuGet process. - /// - public sealed class MonitorNuGetProcessExitRequestHandler : IRequestHandler, IDisposable - { - private bool _isDisposed; - private readonly IPlugin _plugin; - private readonly ConcurrentDictionary _processes; - - public CancellationToken CancellationToken => CancellationToken.None; - - /// - /// Initializes a new class. - /// - /// A plugin. - /// Thrown if is null. - public MonitorNuGetProcessExitRequestHandler(IPlugin plugin) - { - if (plugin == null) - { - throw new ArgumentNullException(nameof(plugin)); - } - - _plugin = plugin; - _processes = new ConcurrentDictionary(); - } - - public void Dispose() - { - if (!_isDisposed) - { - foreach (var entry in _processes) - { - entry.Value.EnableRaisingEvents = false; - entry.Value.Dispose(); - } - - _processes.Clear(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - /// - /// Asynchronously handles cancelling a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown always. - public Task HandleCancelAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously handles responding to a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if is null. - /// Thrown if - /// is null. - public async Task HandleResponseAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } - - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (responseHandler == null) - { - throw new ArgumentNullException(nameof(responseHandler)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var monitorRequest = MessageUtilities.DeserializePayload(request); - - Process process = null; - - try - { - process = _processes.GetOrAdd(monitorRequest.ProcessId, pid => Process.GetProcessById(pid)); - } - catch (Exception) - { - } - - MessageResponseCode responseCode; - - if (process == null) - { - responseCode = MessageResponseCode.NotFound; - } - else - { - process.Exited += OnProcessExited; - - process.EnableRaisingEvents = true; - - responseCode = MessageResponseCode.Success; - } - - var response = new MonitorNuGetProcessExitResponse(responseCode); - - await responseHandler.SendResponseAsync(request, response, cancellationToken); - } - - private void OnProcessExited(object sender, EventArgs e) - { - _plugin.Close(); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/SymmetricHandshake.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/SymmetricHandshake.cs deleted file mode 100644 index cb2201934ce..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/SymmetricHandshake.cs +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Versioning; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A helper class that performs a symmetric handshake. - /// - public sealed class SymmetricHandshake : IRequestHandler, IDisposable - { - private readonly IConnection _connection; - private readonly HandshakeResponse _handshakeFailedResponse; - private readonly TimeSpan _handshakeTimeout; - private bool _isDisposed; - private readonly SemanticVersion _minimumProtocolVersion; - private HandshakeRequest _outboundHandshakeRequest; - private readonly SemanticVersion _protocolVersion; - private TaskCompletionSource _responseSentTaskCompletionSource; - private readonly CancellationTokenSource _timeoutCancellationTokenSource; - - /// - /// Gets the for a request. - /// - public CancellationToken CancellationToken { get; } - - /// - /// Initializes a new instance of the class. - /// - /// A connection. - /// The handshake timeout. - /// The handshaker's protocol version. - /// The handshaker's minimum protocol version. - public SymmetricHandshake( - IConnection connection, - TimeSpan handshakeTimeout, - SemanticVersion protocolVersion, - SemanticVersion minimumProtocolVersion) - { - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } - - if (!TimeoutUtilities.IsValid(handshakeTimeout)) - { - throw new ArgumentOutOfRangeException( - nameof(handshakeTimeout), - handshakeTimeout, - Strings.Plugin_TimeoutOutOfRange); - } - - if (protocolVersion == null) - { - throw new ArgumentNullException(nameof(protocolVersion)); - } - - if (minimumProtocolVersion == null) - { - throw new ArgumentNullException(nameof(minimumProtocolVersion)); - } - - _connection = connection; - _handshakeTimeout = handshakeTimeout; - _protocolVersion = protocolVersion; - _minimumProtocolVersion = minimumProtocolVersion; - _handshakeFailedResponse = new HandshakeResponse(MessageResponseCode.Error, protocolVersion: null); - _responseSentTaskCompletionSource = new TaskCompletionSource(); - _timeoutCancellationTokenSource = new CancellationTokenSource(handshakeTimeout); - - _timeoutCancellationTokenSource.Token.Register(() => - { - _responseSentTaskCompletionSource.TrySetCanceled(); - }); - - CancellationToken = _timeoutCancellationTokenSource.Token; - - if (!_connection.MessageDispatcher.RequestHandlers.TryAdd(MessageMethod.Handshake, this)) - { - throw new ArgumentException(Strings.Plugin_HandshakeRequestHandlerAlreadyExists, nameof(connection)); - } - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (_isDisposed) - { - return; - } - - _connection.MessageDispatcher.RequestHandlers.TryRemove(MessageMethod.Handshake); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - - /// - /// Asynchronously handles handshaking. - /// - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// if the handshake was successful; otherwise, null. - /// Thrown if - /// is cancelled. - public async Task HandshakeAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - _outboundHandshakeRequest = new HandshakeRequest(_protocolVersion, _minimumProtocolVersion); - - var response = await _connection.SendRequestAndReceiveResponseAsync( - MessageMethod.Handshake, - _outboundHandshakeRequest, - cancellationToken); - - if (response != null && response.ResponseCode == MessageResponseCode.Success) - { - if (IsSupportedVersion(response.ProtocolVersion)) - { - await _responseSentTaskCompletionSource.Task; - - return response.ProtocolVersion; - } - } - - await _responseSentTaskCompletionSource.Task; - - return null; - } - - /// - /// Asynchronously handles cancelling a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Cancellation requests are not supported - /// by this request handler. - public Task HandleCancelAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - throw new ProtocolException(Strings.Plugin_IllegalMessageWhileHandshaking); - } - - /// - /// Asynchronously handles responding to a request. - /// - /// The connection. - /// A request message. - /// A response handler. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if - /// is null. - /// Thrown if is null. - /// Thrown if - /// is null. - /// Thrown if - /// is cancelled. - public async Task HandleResponseAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } - - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (responseHandler == null) - { - throw new ArgumentNullException(nameof(responseHandler)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var response = _handshakeFailedResponse; - var handshakeRequest = MessageUtilities.DeserializePayload(request); - - if (handshakeRequest != null) - { - if (!(handshakeRequest.MinimumProtocolVersion > handshakeRequest.ProtocolVersion || - handshakeRequest.ProtocolVersion < _minimumProtocolVersion || - handshakeRequest.MinimumProtocolVersion > _protocolVersion)) - { - SemanticVersion negotiatedProtocolVersion; - - if (_protocolVersion <= handshakeRequest.ProtocolVersion) - { - negotiatedProtocolVersion = _protocolVersion; - } - else - { - negotiatedProtocolVersion = handshakeRequest.ProtocolVersion; - } - - response = new HandshakeResponse(MessageResponseCode.Success, negotiatedProtocolVersion); - } - } - - await responseHandler.SendResponseAsync(request, response, cancellationToken) - .ContinueWith(task => _responseSentTaskCompletionSource.TrySetResult(0)); - } - - private bool IsSupportedVersion(SemanticVersion requestedProtocolVersion) - { - return _minimumProtocolVersion <= requestedProtocolVersion && requestedProtocolVersion <= _protocolVersion; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestIdGenerator.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestIdGenerator.cs deleted file mode 100644 index 0214bc036ec..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestIdGenerator.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// A unique identifier generator. - /// - public sealed class RequestIdGenerator : IIdGenerator - { - /// - /// Generates a new unique identifier. - /// - /// A unique identifier. - public string GenerateUniqueId() - { - return Guid.NewGuid().ToString(); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/Sender.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/Sender.cs deleted file mode 100644 index 27b717d758e..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/Sender.cs +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a unidirectional communications channel to a target. - /// - /// - /// Any public static members of this type are thread safe. - /// Any instance members are not guaranteed to be thread safe. - /// - public sealed class Sender : ISender - { - private bool _hasConnected; - private bool _isClosed; - private bool _isDisposed; - private readonly object _sendLock; - private readonly TextWriter _textWriter; - - /// - /// Instantiates a new class. - /// - /// A text writer. - /// Thrown if is null. - public Sender(TextWriter writer) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - _textWriter = writer; - _sendLock = new object(); - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (_isDisposed) - { - return; - } - - Close(); - - _textWriter.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - - /// - /// Closes the connection. - /// - /// This does not call . - public void Close() - { - _isClosed = true; - } - - /// - /// Connects. - /// - /// Thrown if this object is disposed. - /// Thrown if this object is closed. - /// Thrown if this method has already been called. - public void Connect() - { - ThrowIfDisposed(); - - if (_isClosed) - { - throw new InvalidOperationException(Strings.Plugin_ConnectionIsClosed); - } - - if (_hasConnected) - { - throw new InvalidOperationException(Strings.Plugin_ConnectionAlreadyStarted); - } - - _hasConnected = true; - } - - /// - /// Asynchronously sends a message to the target. - /// - /// The message to send. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// Thrown if this object is disposed. - /// Thrown if has not been called. - /// Thrown if is null. - /// Thrown if - /// is cancelled. - public Task SendAsync(Message message, CancellationToken cancellationToken) - { - ThrowIfDisposed(); - - if (message == null) - { - throw new ArgumentNullException(nameof(message)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - if (!_hasConnected) - { - throw new InvalidOperationException(Strings.Plugin_NotConnected); - } - - if (!_isClosed) - { - lock (_sendLock) - { - using (var jsonWriter = new JsonTextWriter(_textWriter)) - { - jsonWriter.CloseOutput = false; - - JsonSerializationUtilities.Serialize(jsonWriter, message); - - // We need to terminate JSON objects with a delimiter (i.e.: a single - // newline sequence) to signal to the receiver when to stop reading. - _textWriter.WriteLine(); - _textWriter.Flush(); - } - } - } - - return Task.FromResult(0); - } - - private void ThrowIfDisposed() - { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(Sender)); - } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/StandardInputReceiver.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/StandardInputReceiver.cs deleted file mode 100644 index 18c4bcf9988..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/StandardInputReceiver.cs +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a unidirectional communications channel from a target. - /// - /// - /// Any public static members of this type are thread safe. - /// Any instance members are not guaranteed to be thread safe. - /// - public sealed class StandardInputReceiver : Receiver - { - private readonly TextReader _reader; - private readonly CancellationTokenSource _receiveCancellationTokenSource; - private Task _receiveThread; - - /// - /// Instantiates a new class. - /// - /// A text reader. - /// Thrown if is null. - public StandardInputReceiver(TextReader reader) - { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - - _reader = reader; - _receiveCancellationTokenSource = new CancellationTokenSource(); - } - - /// - /// Disposes of this instance. - /// - public override void Dispose() - { - if (IsDisposed) - { - return; - } - - Close(); - - try - { - using (_receiveCancellationTokenSource) - { - _receiveCancellationTokenSource.Cancel(); - - // Do not attempt to wait on completion of the receive thread task. - // In scenarios where standard input is backed by a non-blocking stream - // (e.g.: a MemoryStream in unit tests) waiting on the receive thread task - // is fine. However, when standard input is backed by a blocking stream, - // reading from standard input is a blocking call, and while the receive - // thread is in a read call it cannot respond to cancellation requests. - // We would likely hang if we attempted to wait on completion of the - // receive thread task. - } - } - catch (Exception) - { - } - - _reader.Dispose(); - - GC.SuppressFinalize(this); - - IsDisposed = true; - } - - /// - /// Connects. - /// - /// Thrown if this object is disposed. - /// Thrown if this object is closed. - /// Thrown if this method has already been called. - public override void Connect() - { - ThrowIfDisposed(); - ThrowIfClosed(); - - if (_receiveThread != null) - { - throw new InvalidOperationException(Strings.Plugin_ConnectionAlreadyStarted); - } - - _receiveThread = Task.Factory.StartNew( - Receive, - _receiveCancellationTokenSource.Token, - _receiveCancellationTokenSource.Token, - TaskCreationOptions.LongRunning | TaskCreationOptions.DenyChildAttach, - TaskScheduler.Default); - } - - private void Receive(object state) - { - Message message = null; - - try - { - var cancellationToken = (CancellationToken)state; - - string line; - - // Reading from the standard input stream is a blocking call; while we're - // in a read call we can't respond to cancellation requests. - while (!IsClosed && (line = _reader.ReadLine()) != null) - { - message = null; - - cancellationToken.ThrowIfCancellationRequested(); - - message = JsonSerializationUtilities.Deserialize(line); - - if (message != null) - { - FireMessageReceivedEvent(message); - } - } - } - catch (Exception ex) - { - FireFaultEvent(ex, message); - } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/StandardOutputReceiver.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/StandardOutputReceiver.cs deleted file mode 100644 index 8bf3a8560d7..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/StandardOutputReceiver.cs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Represents a unidirectional communications channel from a target. - /// - /// - /// Any public static members of this type are thread safe. - /// Any instance members are not guaranteed to be thread safe. - /// - public sealed class StandardOutputReceiver : Receiver - { - private bool _hasConnected; - private readonly IPluginProcess _process; - - /// - /// Instantiates a new class. - /// - /// A plugin process. - /// Thrown if is null. - public StandardOutputReceiver(IPluginProcess process) - { - if (process == null) - { - throw new ArgumentNullException(nameof(process)); - } - - _process = process; - } - - /// - /// Disposes of this instance. - /// - public override void Dispose() - { - if (IsDisposed) - { - return; - } - - Close(); - - // The process instance is shared with other classes and will be disposed elsewhere. - - GC.SuppressFinalize(this); - - IsDisposed = true; - } - - /// - /// Closes the connection. - /// - /// This does not call . - public override void Close() - { - if (!IsClosed) - { - base.Close(); - - _process.LineRead -= OnLineRead; - - _process.CancelRead(); - } - } - - /// - /// Connects. - /// - /// Thrown if this object is disposed. - /// Thrown if this object is closed. - /// Thrown if this method has already been called. - public override void Connect() - { - ThrowIfDisposed(); - ThrowIfClosed(); - - if (_hasConnected) - { - throw new InvalidOperationException(Strings.Plugin_ConnectionAlreadyStarted); - } - - _process.LineRead += OnLineRead; - _process.BeginReadLine(); - - _hasConnected = true; - } - - private void OnLineRead(object sender, LineReadEventArgs e) - { - Message message = null; - - // Top-level exception handler for a worker pool thread. - try - { - if (!IsClosed && !string.IsNullOrEmpty(e.Line)) - { - message = JsonSerializationUtilities.Deserialize(e.Line); - - if (message != null) - { - FireMessageReceivedEvent(message); - } - } - } - catch (Exception ex) - { - FireFaultEvent(ex, message); - } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/TimeoutUtilities.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/TimeoutUtilities.cs deleted file mode 100644 index 6799dda1278..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/TimeoutUtilities.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Timeout utilities. - /// - public static class TimeoutUtilities - { - /// - /// Determines if a timeout is valid. - /// - /// A timeout. - /// true if the timeout is valid; otherwise, false. - public static bool IsValid(TimeSpan timeout) - { - if (ProtocolConstants.MinTimeout <= timeout && timeout <= ProtocolConstants.MaxTimeout) - { - return true; - } - - return false; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/WindowsEmbeddedSignatureVerifier.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/WindowsEmbeddedSignatureVerifier.cs deleted file mode 100644 index b8e5b8c3748..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/WindowsEmbeddedSignatureVerifier.cs +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Runtime.InteropServices; - -namespace NuGet.Protocol.Plugins -{ - /// - /// Windows Authenticode signature verifier. - /// - public sealed class WindowsEmbeddedSignatureVerifier : EmbeddedSignatureVerifier - { - [DllImport("wintrust.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Unicode)] - private static extern int WinVerifyTrust([In] IntPtr hwnd, - [In] [MarshalAs(UnmanagedType.LPStruct)] Guid pgActionID, - [In] WINTRUST_DATA pWVTData); - - /// - /// Checks if a file has a valid Authenticode signature. - /// - /// The path of a file to be checked. - /// true if the file has a valid signature; otherwise, false. - /// Thrown if - /// is either null or an empty string. - public override bool IsValid(string filePath) - { - if (string.IsNullOrEmpty(filePath)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(filePath)); - } - - var WINTRUST_ACTION_GENERIC_VERIFY_V2 = new Guid("{00AAC56B-CD44-11D0-8CC2-00C04FC295EE}"); - - using (var pFilePath = new SafeCoTaskMem(filePath)) - { - var fileInfo = new WINTRUST_FILE_INFO() { pcwszFilePath = pFilePath.DangerousGetHandle() }; - - using (var pFile = new SafeCoTaskMem((int)fileInfo.cbStruct)) - { - Marshal.StructureToPtr(fileInfo, pFile.DangerousGetHandle(), fDeleteOld: false); - - var data = new WINTRUST_DATA() { pFile = pFile.DangerousGetHandle() }; - - return WinVerifyTrust(IntPtr.Zero, WINTRUST_ACTION_GENERIC_VERIFY_V2, data) == 0; - } - } - } - - private sealed class SafeCoTaskMem : SafeHandle - { - private SafeCoTaskMem() : base(IntPtr.Zero, ownsHandle: true) - { - } - - internal SafeCoTaskMem(int cbSize) : this() - { - handle = Marshal.AllocCoTaskMem(cbSize); - } - - internal SafeCoTaskMem(string value) : this() - { - handle = Marshal.StringToCoTaskMemUni(value); - } - - public override bool IsInvalid - { - get { return handle == IntPtr.Zero || handle == IntPtr.Zero; } - } - - protected override bool ReleaseHandle() - { - if (!IsInvalid) - { - Marshal.FreeCoTaskMem(handle); - } - - return true; - } - } - - private enum UIChoice : uint - { - WTD_UI_ALL = 1, - WTD_UI_NONE = 2, - WTD_UI_NOBAD = 3, - WTD_UI_NOGOOD = 4 - } - - private enum RevocationChecks : uint - { - WTD_REVOKE_NONE = 0, - WTD_REVOKE_WHOLECHAIN = 1 - } - - private enum UnionChoice : uint - { - WTD_CHOICE_FILE = 1, - WTD_CHOICE_CATALOG = 2, - WTD_CHOICE_BLOB = 3, - WTD_CHOICE_SIGNER = 4, - WTD_CHOICE_CERT = 5 - } - - private enum StateAction : uint - { - WTD_STATEACTION_IGNORE = 0, - WTD_STATEACTION_VERIFY = 1, - WTD_STATEACTION_CLOSE = 2, - WTD_STATEACTION_AUTO_CACHE = 3, - WTD_STATEACTION_AUTO_CACHE_FLUSH = 4 - } - - [Flags] - private enum ProviderFlags : uint - { - WTD_USE_IE4_TRUST_FLAG = 1, - WTD_NO_IE4_CHAIN_FLAG = 2, - WTD_NO_POLICY_USAGE_FLAG = 4, - WTD_REVOCATION_CHECK_NONE = 16, - WTD_REVOCATION_CHECK_END_CERT = 32, - WTD_REVOCATION_CHECK_CHAIN = 64, - WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = 128, - WTD_SAFER_FLAG = 256, - WTD_HASH_ONLY_FLAG = 512, - WTD_USE_DEFAULT_OSVER_CHECK = 1024, - WTD_LIFETIME_SIGNING_FLAG = 2048, - WTD_CACHE_ONLY_URL_RETRIEVAL = 4096, - WTD_DISABLE_MD2_MD4 = 8192, - WTD_MOTW = 16384 - } - - [Flags] - private enum UIContext : uint - { - WTD_UICONTEXT_EXECUTE = 0, - WTD_UICONTEXT_INSTALL = 1 - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - private sealed class WINTRUST_FILE_INFO - { -#if IS_DESKTOP - internal uint cbStruct = (uint)Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)); -#else - internal uint cbStruct = (uint)Marshal.SizeOf(); -#endif - internal IntPtr pcwszFilePath; - internal IntPtr hFile; - internal IntPtr pgKnownSubject; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - private sealed class WINTRUST_DATA - { -#if IS_DESKTOP - internal uint cbStruct = (uint)Marshal.SizeOf(typeof(WINTRUST_DATA)); -#else - internal uint cbStruct = (uint)Marshal.SizeOf(); -#endif - internal IntPtr pPolicyCallbackData = IntPtr.Zero; - internal IntPtr pSIPClientData = IntPtr.Zero; - internal UIChoice dwUIChoice = UIChoice.WTD_UI_NONE; - internal RevocationChecks fdwRevocationChecks = RevocationChecks.WTD_REVOKE_NONE; - internal UnionChoice dwUnionChoice = UnionChoice.WTD_CHOICE_FILE; - internal IntPtr pFile; - internal StateAction dwStateAction = StateAction.WTD_STATEACTION_IGNORE; - internal IntPtr hWVTStateData = IntPtr.Zero; - internal string pwszURLReference = null; - internal ProviderFlags dwProvFlags = ProviderFlags.WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT - | ProviderFlags.WTD_DISABLE_MD2_MD4; - internal UIContext dwUIContext = UIContext.WTD_UICONTEXT_EXECUTE; - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Providers/DownloadResourcePluginProvider.cs b/src/NuGet.Core/NuGet.Protocol/Providers/DownloadResourcePluginProvider.cs deleted file mode 100644 index e1d88c59031..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Providers/DownloadResourcePluginProvider.cs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Protocol.Core.Types; -using NuGet.Protocol.Plugins; - -namespace NuGet.Protocol -{ - /// - /// A download resource provider for plugins. - /// - public sealed class DownloadResourcePluginProvider : ResourceProvider - { - /// - /// Instanatiates a new class. - /// - public DownloadResourcePluginProvider() - : base(typeof(DownloadResource), - nameof(DownloadResourcePluginProvider), - before: nameof(DownloadResourceV3Provider)) - { - } - - /// - /// Attempts to create a resource for the specified source repository. - /// - /// A source repository. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a Tuple<bool, INuGetResource> - /// Thrown if is null. - /// Thrown if - /// is cancelled. - public override async Task> TryCreate( - SourceRepository source, - CancellationToken cancellationToken) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - DownloadResourcePlugin resource = null; - - var pluginResource = await source.GetResourceAsync(cancellationToken); - - if (pluginResource != null) - { - var serviceIndexResource = await source.GetResourceAsync(cancellationToken); - var httpHandlerResource = await source.GetResourceAsync(cancellationToken); - - if (serviceIndexResource != null && httpHandlerResource != null) - { - var result = await pluginResource.GetPluginAsync(OperationClaim.DownloadPackage, cancellationToken); - - if (result != null) - { - AddOrUpdateGetCredentialsRequestHandler(result.Plugin, source, httpHandlerResource); - AddOrUpdateGetServiceIndexRequestHandler(result.Plugin, source); - - resource = new DownloadResourcePlugin( - result.Plugin, - result.PluginMulticlientUtilities, - source.PackageSource); - } - } - } - - return new Tuple(resource != null, resource); - } - - private static void AddOrUpdateGetCredentialsRequestHandler( - IPlugin plugin, - SourceRepository source, - HttpHandlerResource httpHandlerResource) - { - plugin.Connection.MessageDispatcher.RequestHandlers.AddOrUpdate( - MessageMethod.GetCredentials, - () => new GetCredentialsRequestHandler( - plugin, - httpHandlerResource.ClientHandler?.Proxy, - HttpHandlerResourceV3.CredentialService), - existingHandler => - { - var handler = (GetCredentialsRequestHandler)existingHandler; - - handler.AddOrUpdateSourceRepository(source); - - return handler; - }); - } - - private static void AddOrUpdateGetServiceIndexRequestHandler(IPlugin plugin, SourceRepository source) - { - plugin.Connection.MessageDispatcher.RequestHandlers.AddOrUpdate( - MessageMethod.GetServiceIndex, - () => new GetServiceIndexRequestHandler(plugin), - existingHandler => - { - var handler = (GetServiceIndexRequestHandler)existingHandler; - - handler.AddOrUpdateSourceRepository(source); - - return handler; - }); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Providers/PluginResourceProvider.cs b/src/NuGet.Core/NuGet.Protocol/Providers/PluginResourceProvider.cs deleted file mode 100644 index 5c43e873be5..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Providers/PluginResourceProvider.cs +++ /dev/null @@ -1,371 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; -using NuGet.Common; -using NuGet.Packaging; -using NuGet.Protocol.Plugins; -using NuGet.Shared; - -namespace NuGet.Protocol.Core.Types -{ - /// - /// A plugin resource provider. - /// - /// This is unsealed only to facilitate testing. - public class PluginResourceProvider : ResourceProvider, IDisposable - { - private const string _pluginPathsEnvironmentVariable = "NUGET_PLUGIN_PATHS"; - private const string _pluginRequestTimeoutEnvironmentVariable = "NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS"; - - private Lazy _discoverer; - private bool _isDisposed; - private IPluginFactory _pluginFactory; - private ConcurrentDictionary>>> _pluginOperationClaims; - private ConcurrentDictionary> _pluginUtilities; - private string _rawPluginPaths; - private TimeSpan _requestTimeout; - - private static Lazy _currentProcessId = new Lazy(GetCurrentProcessId); - - /// - /// Gets an environment variable reader. - /// - /// This is non-private only to facilitate testing. - public static IEnvironmentVariableReader EnvironmentVariableReader { get; private set; } - - /// - /// Initializes a new class. - /// - public PluginResourceProvider() - : base(typeof(PluginResource), nameof(PluginResourceProvider)) - { - Reinitialize( - new EnvironmentVariableWrapper(), - new Lazy(InitializeDiscoverer), - new PluginFactory(PluginConstants.IdleTimeout)); - } - - /// - /// Disposes of this instance. - /// - public void Dispose() - { - if (!_isDisposed) - { - if (_discoverer.IsValueCreated) - { - _discoverer.Value.Dispose(); - } - - _pluginFactory.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - /// - /// Asynchronously attempts to create a resource for the specified source repository. - /// - /// A source repository. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a Tuple<bool, INuGetResource> - /// Thrown if is null. - /// Thrown if - /// is cancelled. - public override async Task> TryCreate( - SourceRepository source, - CancellationToken cancellationToken) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - PluginResource resource = null; - - // Fast path - if (source.PackageSource.IsHttp && IsPluginPossiblyAvailable()) - { - var serviceIndex = await source.GetResourceAsync(cancellationToken); - - if (serviceIndex != null) - { - var results = await _discoverer.Value.DiscoverAsync(cancellationToken); - - var pluginCreationResults = await GetPluginsForPackageSourceAsync( - source.PackageSource.Source, - serviceIndex, - results, - cancellationToken); - - if (pluginCreationResults.Any()) - { - resource = new PluginResource( - pluginCreationResults, - source.PackageSource, - HttpHandlerResourceV3.CredentialService); - } - } - } - - return new Tuple(resource != null, resource); - } - - /// - /// Reinitializes static state. - /// - /// This is non-private only to facilitate unit testing. - /// This should not be called by product code. - /// An environment variable reader. - /// A lazy plugin discoverer. - /// A plugin factory. - /// Thrown if is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - public void Reinitialize(IEnvironmentVariableReader reader, - Lazy pluginDiscoverer, - IPluginFactory pluginFactory) - { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - - if (pluginDiscoverer == null) - { - throw new ArgumentNullException(nameof(pluginDiscoverer)); - } - - if (pluginFactory == null) - { - throw new ArgumentNullException(nameof(pluginFactory)); - } - - EnvironmentVariableReader = reader; - _rawPluginPaths = reader.GetEnvironmentVariable(_pluginPathsEnvironmentVariable); - - var requestTimeoutInSeconds = reader.GetEnvironmentVariable(_pluginRequestTimeoutEnvironmentVariable); - - _requestTimeout = GetRequestTimeout(requestTimeoutInSeconds); - _discoverer = pluginDiscoverer; - _pluginFactory = pluginFactory; - _pluginOperationClaims = new ConcurrentDictionary>>>(); - _pluginUtilities = new ConcurrentDictionary>( - StringComparer.OrdinalIgnoreCase); - } - - private async Task> GetPluginsForPackageSourceAsync( - string packageSourceRepository, - ServiceIndexResourceV3 serviceIndex, - IEnumerable results, - CancellationToken cancellationToken) - { - var pluginCreationResults = new List(); - var serviceIndexJson = JObject.Parse(serviceIndex.Json); - - foreach (var result in results) - { - PluginCreationResult pluginCreationResult = null; - - if (result.PluginFile.State == PluginFileState.Valid) - { - var plugin = await _pluginFactory.GetOrCreateAsync( - result.PluginFile.Path, - PluginConstants.PluginArguments, - new RequestHandlers(), - ConnectionOptions.CreateDefault(), - cancellationToken); - - var utilities = _pluginUtilities.GetOrAdd( - plugin.Id, - path => new Lazy( - () => new PluginMulticlientUtilities())); - - await utilities.Value.DoOncePerPluginLifetimeAsync( - MessageMethod.MonitorNuGetProcessExit.ToString(), - () => plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.MonitorNuGetProcessExit, - new MonitorNuGetProcessExitRequest(_currentProcessId.Value), - cancellationToken), - cancellationToken); - - await utilities.Value.DoOncePerPluginLifetimeAsync( - MessageMethod.Initialize.ToString(), - () => InitializePluginAsync(plugin, _requestTimeout, cancellationToken), - cancellationToken); - - var lazyOperationClaims = _pluginOperationClaims.GetOrAdd( - new PluginPackageSourceKey(result.PluginFile.Path, packageSourceRepository), - key => new Lazy>>(() => GetPluginOperationClaimsAsync( - plugin, - packageSourceRepository, - serviceIndexJson, - cancellationToken))); - - await lazyOperationClaims.Value; - - pluginCreationResult = new PluginCreationResult( - plugin, - utilities.Value, - lazyOperationClaims.Value.Result); - } - else - { - pluginCreationResult = new PluginCreationResult(result.Message); - } - - pluginCreationResults.Add(pluginCreationResult); - } - - return pluginCreationResults; - } - - private async Task> GetPluginOperationClaimsAsync( - IPlugin plugin, - string packageSourceRepository, - JObject serviceIndex, - CancellationToken cancellationToken) - { - var payload = new GetOperationClaimsRequest(packageSourceRepository, serviceIndex); - - var response = await plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.GetOperationClaims, - payload, - cancellationToken); - - if (response == null) - { - return new List(); - } - - return response.Claims; - } - - private PluginDiscoverer InitializeDiscoverer() - { - var verifier = EmbeddedSignatureVerifier.Create(); - - return new PluginDiscoverer(_rawPluginPaths, verifier); - } - - private bool IsPluginPossiblyAvailable() - { - return !string.IsNullOrEmpty(_rawPluginPaths); - } - - private static int GetCurrentProcessId() - { - using (var process = Process.GetCurrentProcess()) - { - return process.Id; - } - } - - private static TimeSpan GetRequestTimeout(string requestTimeoutInSeconds) - { - int seconds; - if (int.TryParse(requestTimeoutInSeconds, out seconds)) - { - try - { - var requestTimeout = TimeSpan.FromSeconds(seconds); - - if (TimeoutUtilities.IsValid(requestTimeout)) - { - return requestTimeout; - } - } - catch (Exception) - { - } - } - - return PluginConstants.RequestTimeout; - } - - private static async Task InitializePluginAsync( - IPlugin plugin, - TimeSpan requestTimeout, - CancellationToken cancellationToken) - { - var clientVersion = MinClientVersionUtility.GetNuGetClientVersion().ToNormalizedString(); - var culture = CultureInfo.CurrentCulture.Name; - var payload = new InitializeRequest( - clientVersion, - culture, - requestTimeout); - - var response = await plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.Initialize, - payload, - cancellationToken); - - if (response != null && response.ResponseCode != MessageResponseCode.Success) - { - throw new PluginException(Strings.Plugin_InitializationFailed); - } - - plugin.Connection.Options.SetRequestTimeout(requestTimeout); - } - - private sealed class PluginPackageSourceKey : IEquatable - { - internal string PluginFilePath { get; } - internal string PackageSourceRepository { get; } - - internal PluginPackageSourceKey(string pluginFilePath, string packageSourceRepository) - { - PluginFilePath = pluginFilePath; - PackageSourceRepository = packageSourceRepository; - } - - public override bool Equals(object obj) - { - return Equals(obj as PluginPackageSourceKey); - } - - public override int GetHashCode() - { - return HashCodeCombiner.GetHashCode(PluginFilePath, PackageSourceRepository); - } - - public bool Equals(PluginPackageSourceKey other) - { - if (ReferenceEquals(this, other)) - { - return true; - } - - if (ReferenceEquals(null, other)) - { - return false; - } - - return string.Equals( - PluginFilePath, - other.PluginFilePath, - StringComparison.OrdinalIgnoreCase) - && string.Equals( - PackageSourceRepository, - other.PackageSourceRepository, - StringComparison.OrdinalIgnoreCase); - } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/RemotePackageArchiveDownloader.cs b/src/NuGet.Core/NuGet.Protocol/RemotePackageArchiveDownloader.cs deleted file mode 100644 index 2b2df010128..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/RemotePackageArchiveDownloader.cs +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Common; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; - -namespace NuGet.Protocol -{ - /// - /// A remote package downloader. - /// - public sealed class RemotePackageArchiveDownloader : IPackageDownloader - { - private readonly SourceCacheContext _cacheContext; - private string _destinationFilePath; - private bool _isDisposed; - private readonly ILogger _logger; - private readonly PackageIdentity _packageIdentity; - private Lazy _packageReader; - private readonly FindPackageByIdResource _resource; - - /// - /// Gets an asynchronous package content reader. - /// - /// Thrown if this object is disposed. - public IAsyncPackageContentReader ContentReader - { - get - { - ThrowIfDisposed(); - - return _packageReader.Value; - } - } - - /// - /// Gets an asynchronous package core reader. - /// - /// Thrown if this object is disposed. - public IAsyncPackageCoreReader CoreReader - { - get - { - ThrowIfDisposed(); - - return _packageReader.Value; - } - } - - /// - /// Initializes a new class. - /// - /// A resource. - /// A package identity. - /// A source cache context. - /// A logger. - /// Thrown if is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if is null. - public RemotePackageArchiveDownloader( - FindPackageByIdResource resource, - PackageIdentity packageIdentity, - SourceCacheContext cacheContext, - ILogger logger) - { - if (resource == null) - { - throw new ArgumentNullException(nameof(resource)); - } - - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - _resource = resource; - _packageIdentity = packageIdentity; - _cacheContext = cacheContext; - _logger = logger; - _packageReader = new Lazy(GetPackageReader); - } - - /// - /// Disposes this instance. - /// - public void Dispose() - { - if (!_isDisposed) - { - if (_packageReader.IsValueCreated) - { - _packageReader.Value.Dispose(); - } - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - /// - /// Asynchronously copies a .nupkg to a target file path. - /// - /// The destination file path. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// indicating whether or not the copy was successful. - /// Thrown if this object is disposed. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. - public async Task CopyNupkgFileToAsync(string destinationFilePath, CancellationToken cancellationToken) - { - ThrowIfDisposed(); - - if (string.IsNullOrEmpty(destinationFilePath)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(destinationFilePath)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - using (var destination = new FileStream( - destinationFilePath, - FileMode.Create, - FileAccess.ReadWrite, - FileShare.ReadWrite | FileShare.Delete, - bufferSize: 4096, - useAsync: true)) - { - var result = await _resource.CopyNupkgToStreamAsync( - _packageIdentity.Id, - _packageIdentity.Version, - destination, - _cacheContext, - _logger, - cancellationToken); - - _destinationFilePath = destinationFilePath; - - return result; - } - } - - /// - /// Asynchronously gets a package hash. - /// - /// The hash algorithm. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a - /// representing the package hash. - /// Thrown if this object is disposed. - /// Thrown if - /// is either null or empty. - /// Thrown if - /// is cancelled. - public Task GetPackageHashAsync(string hashAlgorithm, CancellationToken cancellationToken) - { - ThrowIfDisposed(); - - if (string.IsNullOrEmpty(hashAlgorithm)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(hashAlgorithm)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - using (var stream = GetDestinationStream()) - { - var bytes = new CryptoHashProvider(hashAlgorithm).CalculateHash(stream); - var packageHash = Convert.ToBase64String(bytes); - - return Task.FromResult(packageHash); - } - } - - private PackageArchiveReader GetPackageReader() - { - var stream = GetDestinationStream(); - - return new PackageArchiveReader(stream); - } - - private FileStream GetDestinationStream() - { - ThrowIfDisposed(); - - if (string.IsNullOrEmpty(_destinationFilePath)) - { - throw new InvalidOperationException(); - } - - return new FileStream( - _destinationFilePath, - FileMode.Open, - FileAccess.Read, - FileShare.Read, - bufferSize: 4096, - useAsync: true); - } - - private void ThrowIfDisposed() - { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(RemotePackageArchiveDownloader)); - } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/HttpFileSystemBasedFindPackageByIdResource.cs b/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/HttpFileSystemBasedFindPackageByIdResource.cs index d616629e971..1d8f37a8a04 100644 --- a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/HttpFileSystemBasedFindPackageByIdResource.cs +++ b/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/HttpFileSystemBasedFindPackageByIdResource.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -10,7 +10,6 @@ using System.Threading; using System.Threading.Tasks; using NuGet.Common; -using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Protocol.Core.Types; using NuGet.Versioning; @@ -36,14 +35,6 @@ public class HttpFileSystemBasedFindPackageByIdResource : FindPackageByIdResourc private readonly IReadOnlyList _baseUris; private readonly FindPackagesByIdNupkgDownloader _nupkgDownloader; - /// - /// Initializes a new class. - /// - /// Base URI's. - /// An HTTP source. - /// Thrown if is null. - /// Thrown if is empty. - /// Thrown if is null. public HttpFileSystemBasedFindPackageByIdResource( IReadOnlyList baseUris, HttpSource httpSource) @@ -58,11 +49,6 @@ public HttpFileSystemBasedFindPackageByIdResource( throw new ArgumentException(Strings.OneOrMoreUrisMustBeSpecified, nameof(baseUris)); } - if (httpSource == null) - { - throw new ArgumentNullException(nameof(httpSource)); - } - _baseUris = baseUris .Take(MaxRetries) .Select(uri => uri.OriginalString.EndsWith("/", StringComparison.Ordinal) ? uri : new Uri(uri.OriginalString + "/")) @@ -72,68 +58,16 @@ public HttpFileSystemBasedFindPackageByIdResource( _nupkgDownloader = new FindPackagesByIdNupkgDownloader(httpSource); } - /// - /// Asynchronously gets all package versions for a package ID. - /// - /// A package ID. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override async Task> GetAllVersionsAsync( string id, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - var packageInfos = await EnsurePackagesAsync(id, cacheContext, logger, cancellationToken); - return packageInfos.Keys; } - /// - /// Asynchronously gets dependency information for a specific package. - /// - /// A package id. - /// A package version. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override async Task GetDependencyInfoAsync( string id, NuGetVersion version, @@ -141,28 +75,6 @@ public override async Task GetDependencyInfoAsync ILogger logger, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - var packageInfos = await EnsurePackagesAsync(id, cacheContext, logger, cancellationToken); PackageInfo packageInfo; @@ -181,26 +93,6 @@ public override async Task GetDependencyInfoAsync return null; } - /// - /// Asynchronously copies a .nupkg to a stream. - /// - /// A package ID. - /// A package version. - /// A destination stream. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// indicating whether or not the .nupkg file was copied. - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override async Task CopyNupkgToStreamAsync( string id, NuGetVersion version, @@ -209,33 +101,6 @@ public override async Task CopyNupkgToStreamAsync( ILogger logger, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } - - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - var packageInfos = await EnsurePackagesAsync(id, cacheContext, logger, cancellationToken); PackageInfo packageInfo; @@ -253,54 +118,6 @@ public override async Task CopyNupkgToStreamAsync( return false; } - /// - /// Asynchronously gets a package downloader for a package identity. - /// - /// A package identity. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an . - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. - public override async Task GetPackageDownloaderAsync( - PackageIdentity packageIdentity, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken) - { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var packageInfos = await EnsurePackagesAsync(packageIdentity.Id, cacheContext, logger, cancellationToken); - - PackageInfo packageInfo; - if (packageInfos.TryGetValue(packageIdentity.Version, out packageInfo)) - { - return new RemotePackageArchiveDownloader(this, packageInfo.Identity, cacheContext, logger); - } - - return null; - } - private async Task> EnsurePackagesAsync( string id, SourceCacheContext cacheContext, @@ -310,12 +127,11 @@ private async Task> EnsurePackagesAs AsyncLazy> result = null; Func>> findPackages = - (keyId) => new AsyncLazy>( - () => FindPackagesByIdAsync( - keyId, - cacheContext, - logger, - cancellationToken)); + (keyId) => new AsyncLazy>(() => FindPackagesByIdAsync( + keyId, + cacheContext, + logger, + cancellationToken)); if (cacheContext.RefreshMemoryCache) { @@ -452,4 +268,4 @@ private class PackageInfo public string ContentUri { get; set; } } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/PluginFindPackageByIdResource.cs b/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/PluginFindPackageByIdResource.cs deleted file mode 100644 index 4c4bb693024..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/PluginFindPackageByIdResource.cs +++ /dev/null @@ -1,416 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Protocol.Plugins; -using NuGet.Versioning; - -namespace NuGet.Protocol.Core.Types -{ - /// - /// A for plugins. - /// - public sealed class PluginFindPackageByIdResource : FindPackageByIdResource - { - private readonly ConcurrentDictionary>> _packageInfoCache = - new ConcurrentDictionary>>(StringComparer.OrdinalIgnoreCase); - private readonly PackageSource _packageSource; - private readonly IPlugin _plugin; - private readonly IPluginMulticlientUtilities _utilities; - - /// - /// Instantiates a new class. - /// - /// A plugin. - /// A plugin multiclient utilities. - /// A package source. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - public PluginFindPackageByIdResource( - IPlugin plugin, - IPluginMulticlientUtilities utilities, - PackageSource packageSource) - { - if (plugin == null) - { - throw new ArgumentNullException(nameof(plugin)); - } - - if (utilities == null) - { - throw new ArgumentNullException(nameof(utilities)); - } - - if (packageSource == null) - { - throw new ArgumentNullException(nameof(packageSource)); - } - - _plugin = plugin; - _utilities = utilities; - _packageSource = packageSource; - } - - /// - /// Asynchronously copies a .nupkg to a stream. - /// - /// A package ID. - /// A package version. - /// A destination stream. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// indicating whether or not the .nupkg file was copied. - /// Thrown always. - public override Task CopyNupkgToStreamAsync( - string id, - NuGetVersion version, - Stream destination, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - /// - /// Asynchronously gets a package downloader for a package identity. - /// - /// A package identity. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an . - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. - public override Task GetPackageDownloaderAsync( - PackageIdentity packageIdentity, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken) - { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var packageReader = new PluginPackageReader(_plugin, packageIdentity, _packageSource.Source); - var packageDependency = new PluginPackageDownloader(_plugin, packageIdentity, packageReader, _packageSource.Source); - - return Task.FromResult(packageDependency); - } - - /// - /// Asynchronously gets all package versions for a package ID. - /// - /// A package ID. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. - public override async Task> GetAllVersionsAsync( - string id, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - AddOrUpdateLogger(_plugin, logger); - - await _utilities.DoOncePerPluginLifetimeAsync( - MessageMethod.SetLogLevel.ToString(), - () => SetLogLevelAsync(logger, cancellationToken), - cancellationToken); - - var packageInfos = await EnsurePackagesAsync(id, cacheContext, logger, cancellationToken); - - return packageInfos.Keys; - } - - /// - /// Asynchronously gets dependency information for a specific package. - /// - /// A package id. - /// A package version. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. - public override async Task GetDependencyInfoAsync( - string id, - NuGetVersion version, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var packageInfos = await EnsurePackagesAsync(id, cacheContext, logger, cancellationToken); - - PackageInfo packageInfo; - - if (packageInfos.TryGetValue(version, out packageInfo)) - { - AddOrUpdateLogger(_plugin, logger); - - await _utilities.DoOncePerPluginLifetimeAsync( - MessageMethod.SetLogLevel.ToString(), - () => SetLogLevelAsync(logger, cancellationToken), - cancellationToken); - - var response = await _plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.PrefetchPackage, - new PrefetchPackageRequest( - _packageSource.Source, - packageInfo.Identity.Id, - packageInfo.Identity.Version.ToNormalizedString()), - cancellationToken); - - if (response != null && response.ResponseCode == MessageResponseCode.Success) - { - using (var packageReader = new PluginPackageReader(_plugin, packageInfo.Identity, _packageSource.Source)) - { - var nuspecReader = await packageReader.GetNuspecReaderAsync(cancellationToken); - - return GetDependencyInfo(nuspecReader); - } - } - } - - return null; - } - - private async Task> EnsurePackagesAsync( - string id, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken) - { - AsyncLazy> result = null; - - Func>> findPackages = - (keyId) => new AsyncLazy>( - () => FindPackagesByIdAsync( - keyId, - cacheContext, - logger, - cancellationToken)); - - if (cacheContext.RefreshMemoryCache) - { - // Update the cache - result = _packageInfoCache.AddOrUpdate(id, findPackages, (k, v) => findPackages(id)); - } - else - { - // Read the cache if it exists - result = _packageInfoCache.GetOrAdd(id, findPackages); - } - - return await result; - } - - private async Task> FindPackagesByIdAsync( - string id, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken) - { - var uri = _packageSource.Source; - var request = new GetPackageVersionsRequest(uri, id); - - try - { - var response = await _plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.GetPackageVersions, - request, - cancellationToken); - - if (response != null) - { - switch (response.ResponseCode) - { - case MessageResponseCode.Success: - var versions = response.Versions.Select(v => NuGetVersion.Parse(v)); - - return ParsePackageVersions(response.Versions, id, uri); - - case MessageResponseCode.Error: - throw new PluginException( - string.Format( - CultureInfo.CurrentCulture, - Strings.Plugin_FailureQueryingPackageVersions, - id, - _plugin.FilePath)); - - case MessageResponseCode.NotFound: - default: - break; - } - } - - return new SortedDictionary(); - } - catch (Exception ex) - { - var message = string.Format( - CultureInfo.CurrentCulture, - Strings.Log_FailedToRetrievePackage, - id, - uri); - - throw new FatalProtocolException(message, ex); - } - } - - private SortedDictionary ParsePackageVersions( - IEnumerable versions, - string id, - string baseUri) - { - var results = new SortedDictionary(); - - foreach (var packageInfo in versions - .Select(version => CreatePackageInfo(baseUri, id, version)) - .Where(version => version != null)) - { - if (!results.ContainsKey(packageInfo.Identity.Version)) - { - results.Add(packageInfo.Identity.Version, packageInfo); - } - } - - return results; - } - - private PackageInfo CreatePackageInfo(string baseUri, string id, string version) - { - var parsedVersion = NuGetVersion.Parse(version); - var normalizedVersionString = parsedVersion.ToNormalizedString(); - - return new PackageInfo - { - Identity = new PackageIdentity(id, parsedVersion), - ContentUri = $"{baseUri}{id.ToLowerInvariant()}/{normalizedVersionString}/{id.ToLowerInvariant()}.{normalizedVersionString}{PackagingCoreConstants.NupkgExtension}", - }; - } - - private void AddOrUpdateLogger(IPlugin plugin, ILogger logger) - { - plugin.Connection.MessageDispatcher.RequestHandlers.AddOrUpdate( - MessageMethod.Log, - () => new LogRequestHandler(logger), - existingHandler => - { - ((LogRequestHandler)existingHandler).SetLogger(logger); - - return existingHandler; - }); - } - - private async Task SetLogLevelAsync(ILogger logger, CancellationToken cancellationToken) - { - var logLevel = LogRequestHandler.GetLogLevel(logger); - - await _plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.SetLogLevel, - new SetLogLevelRequest(logLevel), - cancellationToken); - } - - private class PackageInfo - { - public PackageIdentity Identity { get; set; } - - public string Path { get; set; } - - public string ContentUri { get; set; } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/PluginFindPackageByIdResourceProvider.cs b/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/PluginFindPackageByIdResourceProvider.cs deleted file mode 100644 index 39e23733290..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/PluginFindPackageByIdResourceProvider.cs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Protocol.Core.Types; -using NuGet.Protocol.Plugins; - -namespace NuGet.Protocol -{ - /// - /// A FindPackageByIdResource provider for plugins. - /// - public sealed class PluginFindPackageByIdResourceProvider : ResourceProvider - { - /// - /// Instantiates a new class. - /// - public PluginFindPackageByIdResourceProvider() - : base(typeof(FindPackageByIdResource), - nameof(PluginFindPackageByIdResourceProvider), - before: nameof(HttpFileSystemBasedFindPackageByIdResourceProvider)) - { - } - - /// - /// Asynchronously attempts to create a resource for the specified source repository. - /// - /// A source repository. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a Tuple<bool, INuGetResource> - /// Thrown if is null. - /// Thrown if - /// is cancelled. - public override async Task> TryCreate( - SourceRepository source, - CancellationToken cancellationToken) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - PluginFindPackageByIdResource resource = null; - - var pluginResource = await source.GetResourceAsync(cancellationToken); - - if (pluginResource != null) - { - var serviceIndexResource = await source.GetResourceAsync(cancellationToken); - var httpHandlerResource = await source.GetResourceAsync(cancellationToken); - - if (serviceIndexResource != null && httpHandlerResource != null) - { - var result = await pluginResource.GetPluginAsync(OperationClaim.DownloadPackage, cancellationToken); - - if (result != null) - { - AddOrUpdateGetCredentialsRequestHandler(result.Plugin, source, httpHandlerResource); - AddOrUpdateGetServiceIndexRequestHandler(result.Plugin, source); - - resource = new PluginFindPackageByIdResource( - result.Plugin, - result.PluginMulticlientUtilities, - source.PackageSource); - } - } - } - - return new Tuple(resource != null, resource); - } - - private static void AddOrUpdateGetCredentialsRequestHandler( - IPlugin plugin, - SourceRepository source, - HttpHandlerResource httpHandlerResource) - { - plugin.Connection.MessageDispatcher.RequestHandlers.AddOrUpdate( - MessageMethod.GetCredentials, - () => new GetCredentialsRequestHandler( - plugin, - httpHandlerResource.ClientHandler?.Proxy, - HttpHandlerResourceV3.CredentialService), - existingHandler => - { - var handler = (GetCredentialsRequestHandler)existingHandler; - - handler.AddOrUpdateSourceRepository(source); - - return handler; - }); - } - - private static void AddOrUpdateGetServiceIndexRequestHandler(IPlugin plugin, SourceRepository source) - { - plugin.Connection.MessageDispatcher.RequestHandlers.AddOrUpdate( - MessageMethod.GetServiceIndex, - () => new GetServiceIndexRequestHandler(plugin), - existingHandler => - { - var handler = (GetServiceIndexRequestHandler)existingHandler; - - handler.AddOrUpdateSourceRepository(source); - - return handler; - }); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/RemoteV2FindPackageByIdResource.cs b/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/RemoteV2FindPackageByIdResource.cs index c359deca717..c16e68fb8f3 100644 --- a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/RemoteV2FindPackageByIdResource.cs +++ b/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/RemoteV2FindPackageByIdResource.cs @@ -1,7 +1,8 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -12,16 +13,12 @@ using System.Xml.Linq; using NuGet.Common; using NuGet.Configuration; -using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Protocol.Core.Types; using NuGet.Versioning; namespace NuGet.Protocol { - /// - /// A resource capable of fetching packages, package versions and package dependency information. - /// public class RemoteV2FindPackageByIdResource : FindPackageByIdResource { private static readonly XName _xnameEntry = XName.Get("entry", "http://www.w3.org/2005/Atom"); @@ -40,27 +37,8 @@ public class RemoteV2FindPackageByIdResource : FindPackageByIdResource private readonly Dictionary>> _packageVersionsCache = new Dictionary>>(StringComparer.OrdinalIgnoreCase); private readonly FindPackagesByIdNupkgDownloader _nupkgDownloader; - /// - /// Initializes a new class. - /// - /// A package source. - /// An HTTP source. - /// Thrown if - /// is null. - /// Thrown if - /// is null. public RemoteV2FindPackageByIdResource(PackageSource packageSource, HttpSource httpSource) { - if (packageSource == null) - { - throw new ArgumentNullException(nameof(packageSource)); - } - - if (httpSource == null) - { - throw new ArgumentNullException(nameof(httpSource)); - } - _baseUri = packageSource.Source.EndsWith("/") ? packageSource.Source : (packageSource.Source + "/"); _httpSource = httpSource; _nupkgDownloader = new FindPackagesByIdNupkgDownloader(_httpSource); @@ -68,73 +46,18 @@ public RemoteV2FindPackageByIdResource(PackageSource packageSource, HttpSource h PackageSource = packageSource; } - /// - /// Gets the package source. - /// public PackageSource PackageSource { get; } - /// - /// Asynchronously gets all package versions for a package ID. - /// - /// A package ID. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override async Task> GetAllVersionsAsync( string id, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - var result = await EnsurePackagesAsync(id, cacheContext, logger, cancellationToken); - return result.Select(item => item.Identity.Version); } - /// - /// Asynchronously gets dependency information for a specific package. - /// - /// A package id. - /// A package version. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override async Task GetDependencyInfoAsync( string id, NuGetVersion version, @@ -142,28 +65,6 @@ public override async Task GetDependencyInfoAsync ILogger logger, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - var packageInfo = await GetPackageInfoAsync(id, version, cacheContext, logger, cancellationToken); if (packageInfo == null) { @@ -181,62 +82,15 @@ public override async Task GetDependencyInfoAsync return GetDependencyInfo(reader); } - /// - /// Asynchronously copies a .nupkg to a stream. - /// - /// A package ID. - /// A package version. - /// A destination stream. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// indicating whether or not the .nupkg file was copied. - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override async Task CopyNupkgToStreamAsync( string id, NuGetVersion version, Stream destination, SourceCacheContext cacheContext, ILogger logger, - CancellationToken cancellationToken) + CancellationToken token) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } - - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var packageInfo = await GetPackageInfoAsync(id, version, cacheContext, logger, cancellationToken); + var packageInfo = await GetPackageInfoAsync(id, version, cacheContext, logger, token); if (packageInfo == null) { return false; @@ -248,59 +102,7 @@ public override async Task CopyNupkgToStreamAsync( destination, cacheContext, logger, - cancellationToken); - } - - /// - /// Asynchronously gets a package downloader for a package identity. - /// - /// A package identity. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an . - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. - public override async Task GetPackageDownloaderAsync( - PackageIdentity packageIdentity, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken) - { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var packageInfo = await GetPackageInfoAsync( - packageIdentity.Id, - packageIdentity.Version, - cacheContext, - logger, - cancellationToken); - - if (packageInfo == null) - { - return null; - } - - return new RemotePackageArchiveDownloader(this, packageInfo.Identity, cacheContext, logger); + token); } private async Task GetPackageInfoAsync( @@ -467,4 +269,4 @@ private class PackageInfo public string ContentUri { get; set; } } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/RemoteV3FindPackageByIdResource.cs b/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/RemoteV3FindPackageByIdResource.cs index 17811a26ff9..602be466579 100644 --- a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/RemoteV3FindPackageByIdResource.cs +++ b/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/RemoteV3FindPackageByIdResource.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -8,121 +8,43 @@ using System.Threading; using System.Threading.Tasks; using NuGet.Common; -using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Protocol.Core.Types; using NuGet.Versioning; namespace NuGet.Protocol { - /// - /// A resource capable of fetching packages, package versions and package dependency information. - /// public class RemoteV3FindPackageByIdResource : FindPackageByIdResource { private readonly SemaphoreSlim _dependencyInfoSemaphore = new SemaphoreSlim(initialCount: 1); private readonly Dictionary>> _packageVersionsCache = new Dictionary>>(StringComparer.OrdinalIgnoreCase); - + private readonly HttpSource _httpSource; private readonly FindPackagesByIdNupkgDownloader _nupkgDownloader; private DependencyInfoResource _dependencyInfoResource; - /// - /// Initializes a new class. - /// - /// A source repository. - /// An HTTP source. - /// Thrown if - /// is null. - /// Thrown if - /// is null. public RemoteV3FindPackageByIdResource(SourceRepository sourceRepository, HttpSource httpSource) { - if (sourceRepository == null) - { - throw new ArgumentNullException(nameof(sourceRepository)); - } - - if (httpSource == null) - { - throw new ArgumentNullException(nameof(httpSource)); - } - SourceRepository = sourceRepository; _httpSource = httpSource; _nupkgDownloader = new FindPackagesByIdNupkgDownloader(httpSource); } - /// - /// Gets the source repository. - /// public SourceRepository SourceRepository { get; } - - /// - /// Asynchronously gets all package versions for a package ID. - /// - /// A package ID. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. + public override async Task> GetAllVersionsAsync( string id, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - var result = await EnsurePackagesAsync(id, cacheContext, logger, cancellationToken); - return result.Select(item => item.Identity.Version); } - /// - /// Asynchronously gets dependency information for a specific package. - /// - /// A package id. - /// A package version. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override async Task GetDependencyInfoAsync( string id, NuGetVersion version, @@ -130,28 +52,6 @@ public override async Task GetDependencyInfoAsync ILogger logger, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - var packageInfo = await GetPackageInfoAsync(id, version, cacheContext, logger, cancellationToken); if (packageInfo == null) { @@ -168,26 +68,6 @@ public override async Task GetDependencyInfoAsync return GetDependencyInfo(reader); } - /// - /// Asynchronously copies a .nupkg to a stream. - /// - /// A package ID. - /// A package version. - /// A destination stream. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// indicating whether or not the .nupkg file was copied. - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public override async Task CopyNupkgToStreamAsync( string id, NuGetVersion version, @@ -196,33 +76,6 @@ public override async Task CopyNupkgToStreamAsync( ILogger logger, CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(id)); - } - - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } - - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - var packageInfo = await GetPackageInfoAsync(id, version, cacheContext, logger, cancellationToken); if (packageInfo == null) { @@ -238,58 +91,6 @@ public override async Task CopyNupkgToStreamAsync( cancellationToken); } - /// - /// Asynchronously gets a package downloader for a package identity. - /// - /// A package identity. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an . - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. - public override async Task GetPackageDownloaderAsync( - PackageIdentity packageIdentity, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken) - { - if (packageIdentity == null) - { - throw new ArgumentNullException(nameof(packageIdentity)); - } - - if (cacheContext == null) - { - throw new ArgumentNullException(nameof(cacheContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - var packageInfo = await GetPackageInfoAsync( - packageIdentity.Id, - packageIdentity.Version, - cacheContext, - logger, - cancellationToken); - - if (packageInfo == null) - { - return null; - } - - return new RemotePackageArchiveDownloader(this, packageInfo.Identity, cacheContext, logger); - } - private async Task GetPackageInfoAsync( string id, NuGetVersion version, diff --git a/src/NuGet.Core/NuGet.Protocol/ResourceProvider.cs b/src/NuGet.Core/NuGet.Protocol/ResourceProvider.cs index 7ba5d77a5ba..740ec4346a5 100644 --- a/src/NuGet.Core/NuGet.Protocol/ResourceProvider.cs +++ b/src/NuGet.Core/NuGet.Protocol/ResourceProvider.cs @@ -65,22 +65,22 @@ public ResourceProvider(Type resourceType, string name, IEnumerable befo _after = after; } - public virtual IEnumerable After + public IEnumerable After { get { return _after; } } - public virtual IEnumerable Before + public IEnumerable Before { get { return _before; } } - public virtual string Name + public string Name { get { return _name; } } - public virtual Type ResourceType + public Type ResourceType { get { return _resourceType; } } diff --git a/src/NuGet.Core/NuGet.Protocol/Resources/DownloadResourcePlugin.cs b/src/NuGet.Core/NuGet.Protocol/Resources/DownloadResourcePlugin.cs deleted file mode 100644 index 1acdadbae69..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Resources/DownloadResourcePlugin.cs +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; -using NuGet.Protocol.Plugins; - -namespace NuGet.Protocol -{ - /// - /// A download resource for plugins. - /// - public sealed class DownloadResourcePlugin : DownloadResource - { - private readonly IPlugin _plugin; - private readonly PackageSource _packageSource; - private readonly IPluginMulticlientUtilities _utilities; - - /// - /// Instantiates a new class. - /// - /// A plugin. - /// A plugin multiclient utilities. - /// A package source. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - public DownloadResourcePlugin( - IPlugin plugin, - IPluginMulticlientUtilities utilities, - PackageSource packageSource) - { - if (plugin == null) - { - throw new ArgumentNullException(nameof(plugin)); - } - - if (utilities == null) - { - throw new ArgumentNullException(nameof(utilities)); - } - - if (packageSource == null) - { - throw new ArgumentNullException(nameof(packageSource)); - } - - _plugin = plugin; - _utilities = utilities; - _packageSource = packageSource; - } - - /// - /// Asynchronously downloads a package. - /// - /// The package identity. - /// A package download context. - /// The path to the global packages folder. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns - /// a . - /// Thrown if is null. - /// Thrown if - /// is null. - /// Thrown if is null. - /// Thrown if - /// is cancelled. - public async override Task GetDownloadResourceResultAsync( - PackageIdentity identity, - PackageDownloadContext downloadContext, - string globalPackagesFolder, - ILogger logger, - CancellationToken cancellationToken) - { - if (identity == null) - { - throw new ArgumentNullException(nameof(identity)); - } - - if (downloadContext == null) - { - throw new ArgumentNullException(nameof(downloadContext)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - AddOrUpdateLogger(_plugin, logger); - - await _utilities.DoOncePerPluginLifetimeAsync( - MessageMethod.SetLogLevel.ToString(), - () => SetLogLevelAsync(logger, cancellationToken), - cancellationToken); - - var response = await _plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.PrefetchPackage, - new PrefetchPackageRequest(_packageSource.Source, identity.Id, identity.Version.ToNormalizedString()), - cancellationToken); - - if (response != null) - { - if (response.ResponseCode == MessageResponseCode.Success) - { - var packageReader = new PluginPackageReader(_plugin, identity, _packageSource.Source); - - return new DownloadResourceResult(packageReader, _packageSource.Source); - } - - if (response.ResponseCode == MessageResponseCode.NotFound) - { - return new DownloadResourceResult(DownloadResourceResultStatus.NotFound); - } - } - - throw new PluginException( - string.Format(CultureInfo.CurrentCulture, - Strings.Plugin_PackageDownloadFailed, - _plugin.Name, - $"{identity.Id}.{identity.Version.ToNormalizedString()}")); - } - - private void AddOrUpdateLogger(IPlugin plugin, ILogger logger) - { - plugin.Connection.MessageDispatcher.RequestHandlers.AddOrUpdate( - MessageMethod.Log, - () => new LogRequestHandler(logger), - existingHandler => - { - ((LogRequestHandler)existingHandler).SetLogger(logger); - - return existingHandler; - }); - } - - private async Task SetLogLevelAsync(ILogger logger, CancellationToken cancellationToken) - { - var logLevel = LogRequestHandler.GetLogLevel(logger); - - await _plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.SetLogLevel, - new SetLogLevelRequest(logLevel), - cancellationToken); - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Resources/FindPackageByIdResource.cs b/src/NuGet.Core/NuGet.Protocol/Resources/FindPackageByIdResource.cs index 1816d51ad24..0cd89402a82 100644 --- a/src/NuGet.Core/NuGet.Protocol/Resources/FindPackageByIdResource.cs +++ b/src/NuGet.Core/NuGet.Protocol/Resources/FindPackageByIdResource.cs @@ -1,117 +1,51 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using NuGet.Common; using NuGet.Packaging; -using NuGet.Packaging.Core; using NuGet.Versioning; namespace NuGet.Protocol.Core.Types { - /// - /// A resource capable of fetching packages, package versions and package dependency information. - /// public abstract class FindPackageByIdResource : INuGetResource { - /// - /// Asynchronously gets all package versions for a package ID. - /// - /// A package ID. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public abstract Task> GetAllVersionsAsync( string id, SourceCacheContext cacheContext, ILogger logger, - CancellationToken cancellationToken); + CancellationToken token); /// - /// Asynchronously gets dependency information for a specific package. + /// Gets the for a specific package. /// - /// A package id. - /// A package version. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// . - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. + /// The packag id. + /// The package version. + /// The source cache context. + /// The logger. + /// The . + /// + /// A that on completion returns a of the + /// package, if found, + /// null otherwise. + /// public abstract Task GetDependencyInfoAsync( string id, NuGetVersion version, SourceCacheContext cacheContext, ILogger logger, - CancellationToken cancellationToken); + CancellationToken token); - /// - /// Asynchronously copies a .nupkg to a stream. - /// - /// A package ID. - /// A package version. - /// A destination stream. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an - /// indicating whether or not the .nupkg file was copied. - /// Thrown if - /// is either null or an empty string. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. public abstract Task CopyNupkgToStreamAsync( string id, NuGetVersion version, Stream destination, SourceCacheContext cacheContext, ILogger logger, - CancellationToken cancellationToken); - - /// - /// Asynchronously gets a package downloader for a package identity. - /// - /// A package identity. - /// A source cache context. - /// A logger. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns an . - /// Thrown if null. - /// Thrown if null. - /// Thrown if null. - /// Thrown if - /// is cancelled. - public abstract Task GetPackageDownloaderAsync( - PackageIdentity packageIdentity, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken); + CancellationToken token); /// /// Read dependency info from a nuspec. @@ -130,4 +64,4 @@ protected static FindPackageByIdDependencyInfo GetDependencyInfo(NuspecReader re reader.GetFrameworkReferenceGroups()); } } -} \ No newline at end of file +} diff --git a/src/NuGet.Core/NuGet.Protocol/Resources/PluginResource.cs b/src/NuGet.Core/NuGet.Protocol/Resources/PluginResource.cs deleted file mode 100644 index 5e03c69ec72..00000000000 --- a/src/NuGet.Core/NuGet.Protocol/Resources/PluginResource.cs +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Configuration; -using NuGet.Protocol.Plugins; - -namespace NuGet.Protocol.Core.Types -{ - /// - /// Represents a plugin resource. - /// - public sealed class PluginResource : INuGetResource - { - private const string _basicAuthenticationType = "Basic"; - - private readonly ICredentialService _credentialService; - private readonly PackageSource _packageSource; - private readonly IReadOnlyList _pluginCreationResults; - - /// - /// Instantiates a new class. - /// - /// Plugin creation results. - /// Thrown if - /// is null. - /// Thrown if - /// is null. - public PluginResource( - IEnumerable pluginCreationResults, - PackageSource packageSource, - ICredentialService credentialService) - { - if (pluginCreationResults == null) - { - throw new ArgumentNullException(nameof(pluginCreationResults)); - } - - if (packageSource == null) - { - throw new ArgumentNullException(nameof(packageSource)); - } - - _pluginCreationResults = pluginCreationResults.ToArray(); - _packageSource = packageSource; - _credentialService = credentialService; - } - - /// - /// Gets the first plugin satisfying the required operation claims for the current package source. - /// - /// The required operation claim. - /// A cancellation token. - /// A task that represents the asynchronous operation. - /// The task result () returns a . - /// Thrown if - /// is cancelled. - public async Task GetPluginAsync( - OperationClaim requiredClaim, - CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var messages = new List(); - - foreach (var result in _pluginCreationResults) - { - if (!string.IsNullOrEmpty(result.Message)) - { - throw new PluginException(result.Message); - } - - if (result.Claims.Contains(requiredClaim)) - { - var key = $"{MessageMethod.SetCredentials}.{_packageSource.SourceUri}"; - - await result.PluginMulticlientUtilities.DoOncePerPluginLifetimeAsync( - key, - () => SetPackageSourceCredentialsAsync(result.Plugin, cancellationToken), - cancellationToken); - - return new GetPluginResult(result.Plugin, result.PluginMulticlientUtilities); - } - } - - return null; - } - - private async Task SetPackageSourceCredentialsAsync(IPlugin plugin, CancellationToken cancellationToken) - { - var payload = CreateRequest(); - - await plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.SetCredentials, - payload, - cancellationToken); - } - - private SetCredentialsRequest CreateRequest() - { - var sourceUri = _packageSource.SourceUri; - string proxyUsername = null; - string proxyPassword = null; - string username = null; - string password = null; - ICredentials credentials; - - if (TryGetCachedCredentials(sourceUri, isProxy: true, credentials: out credentials)) - { - var proxyCredential = credentials.GetCredential(sourceUri, _basicAuthenticationType); - - if (proxyCredential != null) - { - proxyUsername = proxyCredential.UserName; - proxyPassword = proxyCredential.Password; - } - } - - if (TryGetCachedCredentials(sourceUri, isProxy: false, credentials: out credentials)) - { - var packageSourceCredential = credentials.GetCredential(sourceUri, authType: null); - - if (packageSourceCredential != null) - { - username = packageSourceCredential.UserName; - password = packageSourceCredential.Password; - } - } - - return new SetCredentialsRequest( - _packageSource.Source, - proxyUsername, - proxyPassword, - username, - password); - } - - private bool TryGetCachedCredentials(Uri uri, bool isProxy, out ICredentials credentials) - { - credentials = null; - - if (_credentialService == null) - { - return false; - } - - return _credentialService.TryGetLastKnownGoodCredentialsFromCache(uri, isProxy, out credentials); - } - - public sealed class GetPluginResult - { - public IPlugin Plugin { get; } - public IPluginMulticlientUtilities PluginMulticlientUtilities { get; } - - internal GetPluginResult(IPlugin plugin, IPluginMulticlientUtilities utilities) - { - Plugin = plugin; - PluginMulticlientUtilities = utilities; - } - } - } -} \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Resources/ServiceIndexResourceV3.cs b/src/NuGet.Core/NuGet.Protocol/Resources/ServiceIndexResourceV3.cs index c3d9cde1779..3557d6d0a08 100644 --- a/src/NuGet.Core/NuGet.Protocol/Resources/ServiceIndexResourceV3.cs +++ b/src/NuGet.Core/NuGet.Protocol/Resources/ServiceIndexResourceV3.cs @@ -16,7 +16,6 @@ namespace NuGet.Protocol /// public class ServiceIndexResourceV3 : INuGetResource { - private readonly string _json; private readonly IDictionary> _index; private readonly DateTime _requestTime; private static readonly IReadOnlyList _emptyEntries = new List(); @@ -25,7 +24,6 @@ public class ServiceIndexResourceV3 : INuGetResource public ServiceIndexResourceV3(JObject index, DateTime requestTime) { - _json = index.ToString(); _index = MakeLookup(index); _requestTime = requestTime; } @@ -49,14 +47,6 @@ public virtual IReadOnlyList Entries } } - public virtual string Json - { - get - { - return _json; - } - } - /// /// Get the list of service entries that best match the current clientVersion and type. /// diff --git a/src/NuGet.Core/NuGet.Protocol/Strings.Designer.cs b/src/NuGet.Core/NuGet.Protocol/Strings.Designer.cs index 2804a08b85c..3e7aa2f4fd3 100644 --- a/src/NuGet.Core/NuGet.Protocol/Strings.Designer.cs +++ b/src/NuGet.Core/NuGet.Protocol/Strings.Designer.cs @@ -20,7 +20,7 @@ namespace NuGet.Protocol { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Strings { @@ -520,231 +520,6 @@ internal static string Path_Invalid_NotFileNotUnc { } } - /// - /// Looks up a localized string similar to A connection has already been started.. - /// - internal static string Plugin_ConnectionAlreadyStarted { - get { - return ResourceManager.GetString("Plugin_ConnectionAlreadyStarted", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The plugin connection is closed.. - /// - internal static string Plugin_ConnectionIsClosed { - get { - return ResourceManager.GetString("Plugin_ConnectionIsClosed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Plugin '{0}' failed with the exception: {1}. - /// - internal static string Plugin_Exception { - get { - return ResourceManager.GetString("Plugin_Exception", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Plugin '{0}' failed a {1} operation for package {2}.{3}.. - /// - internal static string Plugin_FailedOperationForPackage { - get { - return ResourceManager.GetString("Plugin_FailedOperationForPackage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to A failure occurred while attempting to query plugin operation claims for the plugin at '{0}'. Exception: {1}. - /// - internal static string Plugin_FailedToQueryPluginOperationsClaims { - get { - return ResourceManager.GetString("Plugin_FailedToQueryPluginOperationsClaims", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to A failure occurred while attempting to query package versions for package '{0}' using the plugin at '{1}'.. - /// - internal static string Plugin_FailureQueryingPackageVersions { - get { - return ResourceManager.GetString("Plugin_FailureQueryingPackageVersions", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to A plugin was not found at path '{0}'.. - /// - internal static string Plugin_FileNotFound { - get { - return ResourceManager.GetString("Plugin_FileNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The plugin handshake failed.. - /// - internal static string Plugin_HandshakeFailed { - get { - return ResourceManager.GetString("Plugin_HandshakeFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to A handshake request handler already exists.. - /// - internal static string Plugin_HandshakeRequestHandlerAlreadyExists { - get { - return ResourceManager.GetString("Plugin_HandshakeRequestHandlerAlreadyExists", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The idle timeout must be greater than or equal to System.Threading.Timeout.InfiniteTimeSpan.. - /// - internal static string Plugin_IdleTimeoutMustBeGreaterThanOrEqualToInfiniteTimeSpan { - get { - return ResourceManager.GetString("Plugin_IdleTimeoutMustBeGreaterThanOrEqualToInfiniteTimeSpan", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to An illegal message type was received during handshake.. - /// - internal static string Plugin_IllegalMessageWhileHandshaking { - get { - return ResourceManager.GetString("Plugin_IllegalMessageWhileHandshaking", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Plugin initialization failed.. - /// - internal static string Plugin_InitializationFailed { - get { - return ResourceManager.GetString("Plugin_InitializationFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The plugin at '{0}' did not have a valid embedded signature.. - /// - internal static string Plugin_InvalidEmbeddedSignature { - get { - return ResourceManager.GetString("Plugin_InvalidEmbeddedSignature", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The message type '{0}' is invalid at this time.. - /// - internal static string Plugin_InvalidMessageType { - get { - return ResourceManager.GetString("Plugin_InvalidMessageType", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The plugin file path '{0}' is invalid.. - /// - internal static string Plugin_InvalidPluginFilePath { - get { - return ResourceManager.GetString("Plugin_InvalidPluginFilePath", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to A plugin is not connected.. - /// - internal static string Plugin_NotConnected { - get { - return ResourceManager.GetString("Plugin_NotConnected", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Plugin '{0}' failed to download package '{1}'.. - /// - internal static string Plugin_PackageDownloadFailed { - get { - return ResourceManager.GetString("Plugin_PackageDownloadFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to A plugin protocol exception occurred.. - /// - internal static string Plugin_ProtocolException { - get { - return ResourceManager.GetString("Plugin_ProtocolException", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to A protocol version is not supported on error.. - /// - internal static string Plugin_ProtocolVersionNotSupportedOnError { - get { - return ResourceManager.GetString("Plugin_ProtocolVersionNotSupportedOnError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' must be greater than or equal to '{1}'.. - /// - internal static string Plugin_ProtocolVersionOutOfRange { - get { - return ResourceManager.GetString("Plugin_ProtocolVersionOutOfRange", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Request context does not exist for request ID '{0}'.. - /// - internal static string Plugin_RequestContextDoesNotExist { - get { - return ResourceManager.GetString("Plugin_RequestContextDoesNotExist", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to A request handler does not exist for the message method '{0}'.. - /// - internal static string Plugin_RequestHandlerDoesNotExist { - get { - return ResourceManager.GetString("Plugin_RequestHandlerDoesNotExist", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Timeout must be greater than TimeSpan.Zero and less than or equal to TimeSpan.FromMilliseconds(int.MaxValue).. - /// - internal static string Plugin_TimeoutOutOfRange { - get { - return ResourceManager.GetString("Plugin_TimeoutOutOfRange", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The enum value '{0}' is unrecognized.. - /// - internal static string Plugin_UnrecognizedEnumValue { - get { - return ResourceManager.GetString("Plugin_UnrecognizedEnumValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The operation claims are unrecognized: {0}.. - /// - internal static string Plugin_UnrecognizedOperationClaims { - get { - return ResourceManager.GetString("Plugin_UnrecognizedOperationClaims", resourceCulture); - } - } - /// /// Looks up a localized string similar to The project '{0}' is not one of the projects targetted by this object.. /// diff --git a/src/NuGet.Core/NuGet.Protocol/Strings.resx b/src/NuGet.Core/NuGet.Protocol/Strings.resx index 70bf6263f72..ebc6a7027f2 100644 --- a/src/NuGet.Core/NuGet.Protocol/Strings.resx +++ b/src/NuGet.Core/NuGet.Protocol/Strings.resx @@ -1,64 +1,5 @@  - @@ -357,108 +298,55 @@ The "ms" should be localized to the abbreviation for milliseconds. Failed to validate the file '{0}'. {0} is the file path. - - API v2 (legacy) - - - API v3 - - - A connection has already been started. - - - Plugin '{0}' failed with the exception: {1} - {0} is the plugin name -{1} is the message from a caught exception - - - The plugin handshake failed. - - - An illegal message type was received during handshake. - - - A protocol version is not supported on error. - - - '{0}' must be greater than or equal to '{1}'. - {0} is a parameter name -{1} is a parameter name - - - Request context does not exist for request ID '{0}'. - {0} is a request ID - - - A request handler does not exist for the message method '{0}'. - {0} is a message method - - - Timeout must be greater than TimeSpan.Zero and less than or equal to TimeSpan.FromMilliseconds(int.MaxValue). - Do not localize: TimeSpan.Zero, TimeSpan.FromMilliseconds(int.MaxValue) + + Install failed. Rolling back... - - The enum value '{0}' is unrecognized. - {0} is an undefined enum value + + Unrecognized Package Action '{0}'. - - The message type '{0}' is invalid at this time. - {0} is a message type enum value + + Unsupported Dependency Behavior '{0}'. - - The operation claims are unrecognized: {0}. - {0} is a comma-delimited list of unrecognized enum values. + + The download URL for {0} '{1}' is invalid. - - A plugin is not connected. + + No download URL could be found for {0}. - - A failure occurred while attempting to query plugin operation claims for the plugin at '{0}'. Exception: {1} - {0} is a file system path -{1} is the message from a caught exception + + Cannot create a NuGet Repository from the Aggregate Source - - A plugin was not found at path '{0}'. - {0} is a file system path + + The {0} service is not supported by this object. - - The plugin at '{0}' did not have a valid embedded signature. - {0} is a file system path + + Unrecognized Package Action '{0}'. - - Plugin initialization failed. + + The project '{0}' is not one of the projects targetted by this object. - - A handshake request handler already exists. + + Service index document is missing the 'resources' property. - - The idle timeout must be greater than or equal to System.Threading.Timeout.InfiniteTimeSpan. + + The source does not have a Registration Base Url defined! - - A plugin protocol exception occurred. + + The source does not have a Search service! - - Plugin '{0}' failed to download package '{1}'. - {0} is the plugin name -{1} is the package identity + + The '{0}' installation feature was required by a package but is not supported on the current host. - - The plugin connection is closed. + + The installation host does not support a feature required by this package. - - A failure occurred while attempting to query package versions for package '{0}' using the plugin at '{1}'. - {0} is a package ID -{0} is a file system path + + The path '{0}' for the selected source could not be resolved. - - The plugin file path '{0}' is invalid. - {0} is a file system path. + + API v2 (legacy) - - Plugin '{0}' failed a {1} operation for package {2}.{3}. - {0} is the plugin name -{1} is a plugin operation name -{2} is a package ID -{3} is a package version + + API v3 \ No newline at end of file diff --git a/src/NuGet.Core/NuGet.Protocol/Utility/GetDownloadResultUtility.cs b/src/NuGet.Core/NuGet.Protocol/Utility/GetDownloadResultUtility.cs index fa65fead19b..fe5ddfa9a4c 100644 --- a/src/NuGet.Core/NuGet.Protocol/Utility/GetDownloadResultUtility.cs +++ b/src/NuGet.Core/NuGet.Protocol/Utility/GetDownloadResultUtility.cs @@ -1,9 +1,10 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Globalization; using System.IO; +using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using NuGet.Common; @@ -102,14 +103,14 @@ public static async Task GetDownloadResultAsync( } catch (Exception ex) when (retry < 2) { - var message = string.Format(CultureInfo.CurrentCulture, Strings.Log_ErrorDownloading, identity, uri) + string message = string.Format(CultureInfo.CurrentCulture, Strings.Log_ErrorDownloading, identity, uri) + Environment.NewLine + ExceptionUtilities.DisplayMessage(ex); logger.LogWarning(message); } catch (Exception ex) { - var message = string.Format(CultureInfo.CurrentCulture, Strings.Log_ErrorDownloading, identity, uri); + string message = string.Format(CultureInfo.CurrentCulture, Strings.Log_ErrorDownloading, identity, uri); throw new FatalProtocolException(message, ex); } diff --git a/src/NuGet.Core/NuGet.Protocol/Utility/OfflineFeedUtility.cs b/src/NuGet.Core/NuGet.Protocol/Utility/OfflineFeedUtility.cs index 10c944548e2..a30c1f81417 100644 --- a/src/NuGet.Core/NuGet.Protocol/Utility/OfflineFeedUtility.cs +++ b/src/NuGet.Core/NuGet.Protocol/Utility/OfflineFeedUtility.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -33,9 +33,9 @@ public static bool PackageExists( } var versionFolderPathResolver = new VersionFolderPathResolver(offlineFeed); - var nupkgFilePath = versionFolderPathResolver.GetPackageFilePath(packageIdentity.Id, packageIdentity.Version); - var hashFilePath = versionFolderPathResolver.GetHashPath(packageIdentity.Id, packageIdentity.Version); - var nuspecFilePath = versionFolderPathResolver.GetManifestFilePath(packageIdentity.Id, packageIdentity.Version); + string nupkgFilePath = versionFolderPathResolver.GetPackageFilePath(packageIdentity.Id, packageIdentity.Version); + string hashFilePath = versionFolderPathResolver.GetHashPath(packageIdentity.Id, packageIdentity.Version); + string nuspecFilePath = versionFolderPathResolver.GetManifestFilePath(packageIdentity.Id, packageIdentity.Version); var nupkgFileExists = File.Exists(nupkgFilePath); @@ -66,7 +66,6 @@ public static bool PackageExists( isValidPackage = false; return false; } - public static string GetPackageDirectory(PackageIdentity packageIdentity, string offlineFeed) { var versionFolderPathResolver = new VersionFolderPathResolver(offlineFeed); @@ -76,7 +75,7 @@ public static string GetPackageDirectory(PackageIdentity packageIdentity, string public static void ThrowIfInvalid(string path) { - var pathUri = UriUtility.TryCreateSourceUri(path, UriKind.RelativeOrAbsolute); + Uri pathUri = UriUtility.TryCreateSourceUri(path, UriKind.RelativeOrAbsolute); if (pathUri == null) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, @@ -131,13 +130,6 @@ public static async Task AddPackageToSource( OfflineFeedAddContext offlineFeedAddContext, CancellationToken token) { - if (offlineFeedAddContext == null) - { - throw new ArgumentNullException(nameof(offlineFeedAddContext)); - } - - token.ThrowIfCancellationRequested(); - var packagePath = offlineFeedAddContext.PackagePath; var source = offlineFeedAddContext.Source; var logger = offlineFeedAddContext.Logger; @@ -189,6 +181,7 @@ public static async Task AddPackageToSource( } else { + packageStream.Seek(0, SeekOrigin.Begin); var packageSaveMode = offlineFeedAddContext.Expand ? PackageSaveMode.Defaultv3 : PackageSaveMode.Nuspec | PackageSaveMode.Nupkg; @@ -200,16 +193,10 @@ public static async Task AddPackageToSource( packageSaveMode: packageSaveMode, xmlDocFileSaveMode: PackageExtractionBehavior.XmlDocFileSaveMode); - using (var packageDownloader = new LocalPackageArchiveDownloader( - packagePath, - packageIdentity, - logger)) - { - await PackageExtractor.InstallFromSourceAsync( - packageDownloader, - versionFolderPathContext, - token); - } + await PackageExtractor.InstallFromSourceAsync( + stream => packageStream.CopyToAsync(stream), + versionFolderPathContext, + token); var message = string.Format( CultureInfo.CurrentCulture, @@ -259,4 +246,4 @@ private static string GetHash(string nupkgFilePath) return packageHash; } } -} \ No newline at end of file +} diff --git a/test/NuGet.Core.FuncTests/NuGet.Commands.FuncTest/RestoreCommandTests.cs b/test/NuGet.Core.FuncTests/NuGet.Commands.FuncTest/RestoreCommandTests.cs index b8cd16a138b..610808d9091 100644 --- a/test/NuGet.Core.FuncTests/NuGet.Commands.FuncTest/RestoreCommandTests.cs +++ b/test/NuGet.Core.FuncTests/NuGet.Commands.FuncTest/RestoreCommandTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -440,15 +440,10 @@ public async Task RestoreCommand_VerifyMinClientVersionAlreadyInstalled() SimpleTestPackageUtility.CreatePackages(workingDir, packageContext); // install the package - var packageIdentity = new PackageIdentity("packageA", NuGetVersion.Parse("1.0.0")); - - using (var packageDownloader = new LocalPackageArchiveDownloader( - packagePath, - packageIdentity, - logger)) + using (var fileStream = File.OpenRead(packagePath)) { - await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + await PackageExtractor.InstallFromSourceAsync((stream) => + fileStream.CopyToAsync(stream, 4096, CancellationToken.None), new VersionFolderPathContext( new PackageIdentity("packageA", NuGetVersion.Parse("1.0.0")), packagesDir, diff --git a/test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/Helpers/PluginStub.cs b/test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/Helpers/PluginStub.cs deleted file mode 100644 index 9345ed4de25..00000000000 --- a/test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/Helpers/PluginStub.cs +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.IO; -using System.Net; -using System.Net.Sockets; -using System.Text; - -namespace NuGet.Protocol.FuncTest -{ - internal sealed class PluginStub : IDisposable - { - private readonly Process _process; - private readonly Socket _socket; - private bool _isDisposed; - - internal StreamWriter StandardInput { get; } - internal StreamReader StandardOutput { get; } - - private PluginStub(Process process, Socket socket) - { - _process = process; - _socket = socket; - - StandardInput = process.StandardInput; - StandardOutput = process.StandardOutput; - } - - public void Dispose() - { - if (_isDisposed) - { - return; - } - - _socket.Shutdown(SocketShutdown.Both); - _socket.Dispose(); - - Kill(_process); - - _process.Dispose(); - - _isDisposed = true; - } - - public void SendResponse(string data) - { - var bytes = Encoding.UTF8.GetBytes(data); - var bytesSent = _socket.Send(bytes); - - Debug.Assert(bytesSent == bytes.Length); - } - - public static PluginStub Create(string filePath, ushort portNumber) - { - var endPoint = new IPEndPoint(IPAddress.Loopback, portNumber); - var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - Process process = null; - - try - { - process = StartPluginStub(filePath, portNumber); - - socket.Connect(endPoint); - } - catch (Exception) - { - if (process != null) - { - Kill(process); - process.Dispose(); - } - - throw; - } - - return new PluginStub(process, socket); - } - - private static void Kill(Process process) - { - try - { - if (!process.HasExited) - { - process.Kill(); - } - } - catch (InvalidOperationException) - { - } - } - - private static Process StartPluginStub(string filePath, ushort portNumber) - { - var startInfo = new ProcessStartInfo(filePath) - { - Arguments = $"-Plugin -PortNumber {portNumber}", - UseShellExecute = false, - RedirectStandardError = false, - RedirectStandardInput = true, - RedirectStandardOutput = true, - StandardOutputEncoding = Encoding.UTF8 - }; - - return Process.Start(startInfo); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/NuGet.Protocol.FuncTest.csproj b/test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/NuGet.Protocol.FuncTest.csproj index d701ac919ee..57009f8dd92 100644 --- a/test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/NuGet.Protocol.FuncTest.csproj +++ b/test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/NuGet.Protocol.FuncTest.csproj @@ -10,7 +10,6 @@ - @@ -28,11 +27,5 @@ - - - xcopy /diye $(ArtifactsDirectory)TestablePlugin\$(VisualStudioVersion)\bin\$(Configuration)\$(TargetFramework)\win7-x64\* $(MSBuildProjectDirectory)\bin\$(Configuration)\$(TargetFramework)\win7-x64\TestablePlugin\ - - - diff --git a/test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/PluginTests.cs b/test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/PluginTests.cs deleted file mode 100644 index bc5e2a3936d..00000000000 --- a/test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/PluginTests.cs +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; -using NuGet.Packaging; -using NuGet.Protocol.Plugins; -using NuGet.Test.Utility; -using Xunit; -using Xunit.Abstractions; -using PluginProtocolConstants = NuGet.Protocol.Plugins.ProtocolConstants; - -namespace NuGet.Protocol.FuncTest -{ - public class PluginTests - { - private static readonly FileInfo _pluginFile; - private static readonly ushort _portNumber = 11000; - private static readonly IEnumerable _pluginArguments = PluginConstants.PluginArguments - .Concat(new[] { $"-PortNumber {_portNumber} -TestRunnerProcessId {GetCurrentProcessId()}" }); - - static PluginTests() - { - var filePath = Path.Combine(Directory.GetCurrentDirectory(), "TestablePlugin", "Plugin.Testable.exe"); - - _pluginFile = new FileInfo(filePath); - } - - public PluginTests(ITestOutputHelper logger) - { - logger.WriteLine($"Plugin file path: {_pluginFile.FullName}"); - } - - [PlatformFact(Platform.Windows)] - public async Task GetOrCreateAsync_SuccessfullyHandshakes() - { - using (var test = await PluginTest.CreateAsync()) - { - Assert.Equal(PluginProtocolConstants.CurrentVersion, test.Plugin.Connection.ProtocolVersion); - } - } - - [PlatformFact(Platform.Windows)] - public async Task Initialize_Succeeds() - { - using (var test = await PluginTest.CreateAsync()) - { - Assert.Equal(PluginProtocolConstants.CurrentVersion, test.Plugin.Connection.ProtocolVersion); - - // Send canned response - var responseSenderTask = Task.Run(() => test.ResponseSender.StartSendingAsync(test.CancellationToken)); - await test.ResponseSender.SendAsync( - MessageType.Response, - MessageMethod.Initialize, - new InitializeResponse(MessageResponseCode.Success)); - - var clientVersion = MinClientVersionUtility.GetNuGetClientVersion().ToNormalizedString(); - var culture = CultureInfo.CurrentCulture.Name; - var payload = new InitializeRequest( - clientVersion, - culture, - PluginConstants.RequestTimeout); - - var response = await test.Plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.Initialize, - payload, - test.CancellationToken); - - Assert.NotNull(response); - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - } - } - - [PlatformFact(Platform.Windows)] - public async Task GetOperationClaims_ReturnsSupportedClaims() - { - using (var test = await PluginTest.CreateAsync()) - { - Assert.Equal(PluginProtocolConstants.CurrentVersion, test.Plugin.Connection.ProtocolVersion); - - // Send canned response - var responseSenderTask = Task.Run(() => test.ResponseSender.StartSendingAsync(test.CancellationToken)); - await test.ResponseSender.SendAsync( - MessageType.Response, - MessageMethod.GetOperationClaims, - new GetOperationClaimsResponse(new OperationClaim[] { OperationClaim.DownloadPackage })); - - var serviceIndex = JObject.Parse("{}"); - var payload = new GetOperationClaimsRequest(packageSourceRepository: "a", serviceIndex: serviceIndex); - - var response = await test.Plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.GetOperationClaims, - payload, - test.CancellationToken); - - Assert.NotNull(response); - Assert.Equal(1, response.Claims.Count); - Assert.Equal(OperationClaim.DownloadPackage, response.Claims[0]); - } - } - - [PlatformFact(Platform.Windows)] - public async Task SendRequestAndReceiveResponseAsync_TimesOut() - { - using (var test = await PluginTest.CreateAsync()) - { - Assert.Equal(PluginProtocolConstants.CurrentVersion, test.Plugin.Connection.ProtocolVersion); - - // Send canned response - var serviceIndex = JObject.Parse("{}"); - var payload = new GetOperationClaimsRequest(packageSourceRepository: "a", serviceIndex: serviceIndex); - - var stopwatch = Stopwatch.StartNew(); - - await Assert.ThrowsAsync( - () => test.Plugin.Connection.SendRequestAndReceiveResponseAsync( - MessageMethod.Initialize, - payload, - test.CancellationToken)); - - var requestTimeout = test.Plugin.Connection.Options.RequestTimeout; - - var low = requestTimeout.Add(TimeSpan.FromSeconds(-2)); - var high = TimeSpan.FromSeconds(requestTimeout.TotalSeconds * 2); - - Assert.InRange(stopwatch.Elapsed, low, high); - } - } - - private static int GetCurrentProcessId() - { - using (var process = Process.GetCurrentProcess()) - { - return process.Id; - } - } - - private sealed class PluginTest : IDisposable - { - private readonly CancellationTokenSource _cancellationTokenSource; - private bool _isDisposed; - private readonly PluginFactory _pluginFactory; - - internal CancellationToken CancellationToken => _cancellationTokenSource.Token; - internal IPlugin Plugin { get; } - internal ResponseSender ResponseSender { get; } - - private PluginTest(PluginFactory pluginFactory, - IPlugin plugin, - ResponseSender responseSender, - CancellationTokenSource cancellationTokenSource) - { - Plugin = plugin; - _pluginFactory = pluginFactory; - ResponseSender = responseSender; - _cancellationTokenSource = cancellationTokenSource; - } - - public void Dispose() - { - if (!_isDisposed) - { - using (_cancellationTokenSource) - { - _cancellationTokenSource.Cancel(); - - ResponseSender.Dispose(); - Plugin.Dispose(); - _pluginFactory.Dispose(); - } - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - internal static async Task CreateAsync() - { - var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(10)); - var pluginFactory = new PluginFactory(PluginConstants.IdleTimeout); - var options = ConnectionOptions.CreateDefault(); - var plugin = await pluginFactory.GetOrCreateAsync( - _pluginFile.FullName, - _pluginArguments, - new RequestHandlers(), - options, - cancellationTokenSource.Token); - var responseSender = new ResponseSender(_portNumber); - - return new PluginTest(pluginFactory, plugin, responseSender, cancellationTokenSource); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/ResponseSender.cs b/test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/ResponseSender.cs deleted file mode 100644 index 5ce20e722f9..00000000000 --- a/test/NuGet.Core.FuncTests/NuGet.Protocol.FuncTest/ResponseSender.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.IO; -using System.Net; -using System.Net.Sockets; -using System.Threading; -using System.Threading.Tasks; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using NuGet.Protocol.Plugins; - -namespace NuGet.Protocol.FuncTest -{ - internal sealed class ResponseSender : IDisposable - { - private bool _isDisposed; - private readonly ushort _portNumber; - private readonly BlockingCollection _responses; - - internal ResponseSender(ushort portNumber) - { - _portNumber = portNumber; - _responses = new BlockingCollection(); - } - - public void Dispose() - { - if (!_isDisposed) - { - _responses.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - internal Task StartSendingAsync(CancellationToken cancellationToken) - { - var localEndPoint = new IPEndPoint(IPAddress.Loopback, _portNumber); - - using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - { - socket.Connect(localEndPoint); - - using (var stream = new NetworkStream(socket, ownsSocket: true)) - using (var streamWriter = new StreamWriter(stream)) - { - streamWriter.AutoFlush = true; - - foreach (var response in _responses.GetConsumingEnumerable(cancellationToken)) - { - var json = Serialize(response); - - streamWriter.WriteLine(json); - } - } - } - - return Task.FromResult(0); - } - - internal Task SendAsync(MessageType type, MessageMethod method, TPayload payload) - where TPayload : class - { - var response = new Response() - { - Type = type, - Method = method, - Payload = payload == null ? null : JObject.FromObject(payload) - }; - - _responses.Add(response); - - return Task.FromResult(0); - } - - private static string Serialize(object value) - { - using (var stringWriter = new StringWriter()) - using (var jsonWriter = new JsonTextWriter(stringWriter)) - { - JsonSerializationUtilities.Serialize(jsonWriter, value); - - return stringWriter.ToString(); - } - } - - private sealed class Response - { - [JsonRequired] - public MessageType Type { get; set; } - - [JsonRequired] - public MessageMethod Method { get; set; } - - public JObject Payload { get; set; } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Commands.Test/RestoreCommand/OriginalCaseGlobalPackageFolderTests.cs b/test/NuGet.Core.Tests/NuGet.Commands.Test/RestoreCommand/OriginalCaseGlobalPackageFolderTests.cs index 608e88561a9..4f5c304162c 100644 --- a/test/NuGet.Core.Tests/NuGet.Commands.Test/RestoreCommand/OriginalCaseGlobalPackageFolderTests.cs +++ b/test/NuGet.Core.Tests/NuGet.Commands.Test/RestoreCommand/OriginalCaseGlobalPackageFolderTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.IO; @@ -15,7 +15,6 @@ using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.ProjectModel; -using NuGet.Protocol; using NuGet.Protocol.Core.Types; using NuGet.Test.Utility; using NuGet.Versioning; @@ -26,7 +25,7 @@ namespace NuGet.Commands.Test public class OriginalCaseGlobalPackageFolderTests { [Fact] - public async Task CopyPackagesToOriginalCaseAsync_WhenPackageMustComeFromProvider_ConvertsPackages() + public async Task OriginalCaseGlobalPackagesFolder_WhenPackageMustComeFromProvider_ConvertsPackages() { // Arrange using (var workingDirectory = TestDirectory.Create()) @@ -61,7 +60,7 @@ await target.CopyPackagesToOriginalCaseAsync( } [Fact] - public async Task CopyPackagesToOriginalCaseAsync_WhenPackageComesFromLocalFolder_ConvertsPackages() + public async Task OriginalCaseGlobalPackagesFolder_WhenPackageComesFromLocalFolder_ConvertsPackages() { // Arrange using (var workingDirectory = TestDirectory.Create()) @@ -102,7 +101,7 @@ await target.CopyPackagesToOriginalCaseAsync( } [Fact] - public async Task CopyPackagesToOriginalCaseAsync_DoesNothingIfPackageIsAlreadyInstalled() + public async Task OriginalCaseGlobalPackagesFolder_DoesNothingIfPackageIsAlreadyInstalled() { // Arrange using (var workingDirectory = TestDirectory.Create()) @@ -142,7 +141,7 @@ await target.CopyPackagesToOriginalCaseAsync( } [Fact] - public async Task CopyPackagesToOriginalCaseAsync_OnlyInstallsPackagesOnce() + public async Task OriginalCaseGlobalPackagesFolder_OnlyInstallsPackagesOnce() { // Arrange using (var workingDirectory = TestDirectory.Create()) @@ -177,7 +176,7 @@ await target.CopyPackagesToOriginalCaseAsync( } [Fact] - public void ConvertLockFileToOriginalCase_ConvertsPackagesPathsInLockFile() + public void OriginalCaseGlobalPackagesFolder_ConvertsPackagesPathsInLockFile() { // Arrange var logger = new TestLogger(); @@ -224,50 +223,47 @@ private static RestoreRequest GetRestoreRequest(string packagesDirectory, TestLo }; } - private static RestoreTargetGraph GetRestoreTargetGraph( - PackageIdentity identity, - FileInfo packagePath, - TestLogger logger) + private static RestoreTargetGraph GetRestoreTargetGraph(PackageIdentity identity, FileInfo packagePath, TestLogger logger) { var libraryRange = new LibraryRange { Name = identity.Id }; var libraryIdentity = new LibraryIdentity(identity.Id, identity.Version, LibraryType.Package); var dependencyProvider = new Mock(); - IPackageDownloader packageDependency = null; dependencyProvider - .Setup(x => x.GetPackageDownloaderAsync( - It.IsAny(), + .Setup(x => x.CopyToAsync( + It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Callback( - (callbackIdentity, sourceCacheContext, callbackLogger, cancellationToken) => + .Callback( + (_, destination, __, ___, ____) => { - packageDependency = new LocalPackageArchiveDownloader( - packagePath.FullName, - callbackIdentity, - callbackLogger); + using (var package = File.OpenRead(packagePath.FullName)) + { + package.CopyTo(destination); + } }) - .Returns(() => Task.FromResult(packageDependency)); + .Returns(Task.CompletedTask); var graph = RestoreTargetGraph.Create( new[] { - new GraphNode(libraryRange) - { - Item = new GraphItem(libraryIdentity) + new GraphNode(libraryRange) { - Data = new RemoteResolveResult + Item = new GraphItem(libraryIdentity) { - Match = new RemoteMatch + Data = new RemoteResolveResult { - Library = libraryIdentity, - Provider = dependencyProvider.Object + Match = new RemoteMatch + { + Library = libraryIdentity, + Provider = dependencyProvider.Object + } } } } - } }, new TestRemoteWalkContext(), logger, @@ -276,4 +272,4 @@ private static RestoreTargetGraph GetRestoreTargetGraph( return graph; } } -} \ No newline at end of file +} diff --git a/test/NuGet.Core.Tests/NuGet.Commands.Test/SourceRepositoryDependencyProviderTests.cs b/test/NuGet.Core.Tests/NuGet.Commands.Test/SourceRepositoryDependencyProviderTests.cs index bbf14ff05a6..bc7aac9a257 100644 --- a/test/NuGet.Core.Tests/NuGet.Commands.Test/SourceRepositoryDependencyProviderTests.cs +++ b/test/NuGet.Core.Tests/NuGet.Commands.Test/SourceRepositoryDependencyProviderTests.cs @@ -1,7 +1,6 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -23,168 +22,18 @@ namespace NuGet.Commands.Test public class SourceRepositoryDependencyProviderTests { [Fact] - public void Constructor_ThrowsForNullSourceRepository() - { - using (var sourceCacheContext = new SourceCacheContext()) - { - var exception = Assert.Throws( - () => new SourceRepositoryDependencyProvider( - sourceRepository: null, - logger: NullLogger.Instance, - cacheContext: sourceCacheContext, - ignoreFailedSources: true, - ignoreWarning: true)); - - Assert.Equal("sourceRepository", exception.ParamName); - } - } - - [Fact] - public void Constructor_ThrowsForNullLogger() - { - using (var sourceCacheContext = new SourceCacheContext()) - { - var exception = Assert.Throws( - () => new SourceRepositoryDependencyProvider( - Mock.Of(), - logger: null, - cacheContext: sourceCacheContext, - ignoreFailedSources: true, - ignoreWarning: true)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public void Constructor_ThrowsForNullSourceCacheContext() - { - var exception = Assert.Throws( - () => new SourceRepositoryDependencyProvider( - Mock.Of(), - NullLogger.Instance, - cacheContext: null, - ignoreFailedSources: true, - ignoreWarning: true)); - - Assert.Equal("cacheContext", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - Assert.Equal(test.PackageSource.IsHttp, test.Provider.IsHttp); - Assert.Same(test.PackageSource, test.Provider.Source); - } - } - - [Fact] - public async Task GetDependenciesAsync_ThrowsForNullLibraryIdentity() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - var exception = await Assert.ThrowsAsync( - () => test.Provider.GetDependenciesAsync( - libraryIdentity: null, - targetFramework: NuGetFramework.Parse("net45"), - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("libraryIdentity", exception.ParamName); - } - } - - [Fact] - public async Task GetDependenciesAsync_ThrowsForNullTargetFramework() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - var exception = await Assert.ThrowsAsync( - () => test.Provider.GetDependenciesAsync( - new LibraryIdentity("a", NuGetVersion.Parse("1.0.0"), LibraryType.Package), - targetFramework: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("targetFramework", exception.ParamName); - } - } - - [Fact] - public async Task GetDependenciesAsync_ThrowsForNullSourceCacheContext() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - var exception = await Assert.ThrowsAsync( - () => test.Provider.GetDependenciesAsync( - new LibraryIdentity("a", NuGetVersion.Parse("1.0.0"), LibraryType.Package), - NuGetFramework.Parse("net45"), - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetDependenciesAsync_ThrowsForNullLogger() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - var exception = await Assert.ThrowsAsync( - () => test.Provider.GetDependenciesAsync( - new LibraryIdentity("a", NuGetVersion.Parse("1.0.0"), LibraryType.Package), - NuGetFramework.Parse("net45"), - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetDependenciesAsync_ThrowsIfCancelled() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - await Assert.ThrowsAsync( - () => test.Provider.GetDependenciesAsync( - new LibraryIdentity("a", NuGetVersion.Parse("1.0.0"), LibraryType.Package), - NuGetFramework.Parse("net45"), - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetDependenciesAsync_ThrowsWhenListedPackageIsMissing() + public async Task SourceRepositoryDependencyProvider_VerifyGetDependencyInfoAsyncThrowsWhenListedPackageIsMissing() { // Arrange var testLogger = new TestLogger(); var cacheContext = new SourceCacheContext(); var findResource = new Mock(); - findResource.Setup(s => s.GetAllVersionsAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .ReturnsAsync(new[] { NuGetVersion.Parse("1.0.0"), NuGetVersion.Parse("2.0.0") }); + findResource.Setup(s => s.GetAllVersionsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new[] { NuGetVersion.Parse("1.0.0"), NuGetVersion.Parse("2.0.0") }); - findResource.Setup(s => s.GetDependencyInfoAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .ThrowsAsync(new PackageNotFoundProtocolException(new PackageIdentity("x", NuGetVersion.Parse("1.0.0")))); + findResource.Setup(s => s.GetDependencyInfoAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ThrowsAsync(new PackageNotFoundProtocolException(new PackageIdentity("x", NuGetVersion.Parse("1.0.0")))); var source = new Mock(); source.Setup(s => s.GetResourceAsync()) @@ -192,49 +41,32 @@ public async Task GetDependenciesAsync_ThrowsWhenListedPackageIsMissing() source.SetupGet(s => s.PackageSource) .Returns(new PackageSource("http://test/index.json")); - var libraryRange = new LibraryRange( - "x", - new VersionRange(new NuGetVersion(1, 0, 0)), - LibraryDependencyTarget.Package); - var provider = new SourceRepositoryDependencyProvider( - source.Object, - testLogger, - cacheContext, - ignoreFailedSources: true, - ignoreWarning: true); + var libraryRange = new LibraryRange("x", new VersionRange(new NuGetVersion(1, 0, 0)), LibraryDependencyTarget.Package); + var provider = new SourceRepositoryDependencyProvider(source.Object, testLogger, cacheContext, ignoreFailedSources: true, ignoreWarning: true); // Act && Assert // Verify the exception it thrown even with ignoreFailedSources: true - await Assert.ThrowsAsync( - async () => await provider.GetDependenciesAsync( - new LibraryIdentity("x", NuGetVersion.Parse("1.0.0"), LibraryType.Package), - NuGetFramework.Parse("net45"), - cacheContext, - testLogger, - CancellationToken.None)); + await Assert.ThrowsAsync(async () => + await provider.GetDependenciesAsync(new LibraryIdentity("x", NuGetVersion.Parse("1.0.0"), + LibraryType.Package), + NuGetFramework.Parse("net45"), + cacheContext, + testLogger, + CancellationToken.None)); } [Fact] - public async Task GetDependenciesAsync_ReturnsOriginalIdentity() + public async Task SourceRepositoryDependencyProvider_VerifyGetDependenciesAsyncReturnsOriginalIdentity() { // Arrange var testLogger = new TestLogger(); var cacheContext = new SourceCacheContext(); var findResource = new Mock(); - findResource.Setup(s => s.GetAllVersionsAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .ReturnsAsync(new[] { NuGetVersion.Parse("1.0.0-beta"), NuGetVersion.Parse("2.0.0") }); + findResource.Setup(s => s.GetAllVersionsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new[] { NuGetVersion.Parse("1.0.0-beta"), NuGetVersion.Parse("2.0.0") }); - findResource.Setup(s => s.GetDependencyInfoAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) + findResource.Setup(s => s.GetDependencyInfoAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(new FindPackageByIdDependencyInfo( new PackageIdentity("X", NuGetVersion.Parse("1.0.0-bEta")), Enumerable.Empty(), @@ -246,16 +78,8 @@ public async Task GetDependenciesAsync_ReturnsOriginalIdentity() source.SetupGet(s => s.PackageSource) .Returns(new PackageSource("http://test/index.json")); - var libraryRange = new LibraryRange( - "x", - new VersionRange(new NuGetVersion(1, 0, 0, "beta")), - LibraryDependencyTarget.Package); - var provider = new SourceRepositoryDependencyProvider( - source.Object, - testLogger, - cacheContext, - ignoreFailedSources: true, - ignoreWarning: true); + var libraryRange = new LibraryRange("x", new VersionRange(new NuGetVersion(1, 0, 0, "beta")), LibraryDependencyTarget.Package); + var provider = new SourceRepositoryDependencyProvider(source.Object, testLogger, cacheContext, ignoreFailedSources: true, ignoreWarning: true); // Act var library = await provider.GetDependenciesAsync( @@ -271,21 +95,22 @@ public async Task GetDependenciesAsync_ReturnsOriginalIdentity() } [Fact] - public async Task GetDependenciesAsync_ValuesAreCachedAndFindResourceIsHitOnce() + public async Task SourceRepositoryDependencyProvider_VerifyValuesAreCachedAndFindResourceIsHitOnce() { // Arrange var testLogger = new TestLogger(); var cacheContext = new SourceCacheContext(); + + var versionsHitCount = 0; + var findResource = new Mock(); + findResource.Setup(s => s.GetAllVersionsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new[] { NuGetVersion.Parse("1.0.0-beta"), NuGetVersion.Parse("2.0.0") }) + .Callback(() => versionsHitCount++); var dependencyHitCount = 0; - findResource.Setup(s => s.GetDependencyInfoAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) + findResource.Setup(s => s.GetDependencyInfoAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(new FindPackageByIdDependencyInfo( new PackageIdentity("x", NuGetVersion.Parse("1.0.0-beta")), Enumerable.Empty(), @@ -298,16 +123,8 @@ public async Task GetDependenciesAsync_ValuesAreCachedAndFindResourceIsHitOnce() source.SetupGet(s => s.PackageSource) .Returns(new PackageSource("http://test/index.json")); - var libraryRange = new LibraryRange( - "x", - new VersionRange(new NuGetVersion(1, 0, 0, "beta")), - LibraryDependencyTarget.Package); - var provider = new SourceRepositoryDependencyProvider( - source.Object, - testLogger, - cacheContext, - ignoreFailedSources: true, - ignoreWarning: true); + var libraryRange = new LibraryRange("x", new VersionRange(new NuGetVersion(1, 0, 0, "beta")), LibraryDependencyTarget.Package); + var provider = new SourceRepositoryDependencyProvider(source.Object, testLogger, cacheContext, ignoreFailedSources: true, ignoreWarning: true); // Act var library = await provider.GetDependenciesAsync( @@ -324,129 +141,6 @@ public async Task GetDependenciesAsync_ValuesAreCachedAndFindResourceIsHitOnce() testLogger, CancellationToken.None); - // Assert - Assert.Equal(1, dependencyHitCount); - } - - [Fact] - public async Task FindLibraryAsync_ThrowsForNullLibraryRange() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - var exception = await Assert.ThrowsAsync( - () => test.Provider.FindLibraryAsync( - libraryRange: null, - targetFramework: NuGetFramework.Parse("net45"), - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("libraryRange", exception.ParamName); - } - } - - [Fact] - public async Task FindLibraryAsync_ThrowsForNullTargetFramework() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - var exception = await Assert.ThrowsAsync( - () => test.Provider.FindLibraryAsync( - new LibraryIdentity("a", NuGetVersion.Parse("1.0.0"), LibraryType.Package), - targetFramework: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("targetFramework", exception.ParamName); - } - } - - [Fact] - public async Task FindLibraryAsync_ThrowsForNullSourceCacheContext() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - var exception = await Assert.ThrowsAsync( - () => test.Provider.FindLibraryAsync( - new LibraryIdentity("a", NuGetVersion.Parse("1.0.0"), LibraryType.Package), - NuGetFramework.Parse("net45"), - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task FindLibraryAsync_ThrowsForNullLogger() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - var exception = await Assert.ThrowsAsync( - () => test.Provider.FindLibraryAsync( - new LibraryIdentity("a", NuGetVersion.Parse("1.0.0"), LibraryType.Package), - NuGetFramework.Parse("net45"), - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task FindLibraryAsync_ThrowsIfCancelled() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - await Assert.ThrowsAsync( - () => test.Provider.FindLibraryAsync( - new LibraryIdentity("a", NuGetVersion.Parse("1.0.0"), LibraryType.Package), - NuGetFramework.Parse("net45"), - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task FindLibraryAsync_ValuesAreCachedAndFindResourceIsHitOnce() - { - // Arrange - var testLogger = new TestLogger(); - var cacheContext = new SourceCacheContext(); - - var versionsHitCount = 0; - - var findResource = new Mock(); - findResource.Setup(s => s.GetAllVersionsAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .ReturnsAsync(new[] { NuGetVersion.Parse("1.0.0-beta"), NuGetVersion.Parse("2.0.0") }) - .Callback(() => versionsHitCount++); - - var source = new Mock(); - source.Setup(s => s.GetResourceAsync()) - .ReturnsAsync(findResource.Object); - source.SetupGet(s => s.PackageSource) - .Returns(new PackageSource("http://test/index.json")); - - var libraryRange = new LibraryRange( - "x", - new VersionRange(new NuGetVersion(1, 0, 0, "beta")), - LibraryDependencyTarget.Package); - var provider = new SourceRepositoryDependencyProvider( - source.Object, - testLogger, - cacheContext, - ignoreFailedSources: true, - ignoreWarning: true); - - // Act var versions = await provider.FindLibraryAsync( new LibraryIdentity("x", NuGetVersion.Parse("1.0.0-beta"), LibraryType.Package), NuGetFramework.Parse("net45"), @@ -463,239 +157,7 @@ public async Task FindLibraryAsync_ValuesAreCachedAndFindResourceIsHitOnce() // Assert Assert.Equal(1, versionsHitCount); - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullPackageIdentity() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - var exception = await Assert.ThrowsAsync( - () => test.Provider.GetPackageDownloaderAsync( - packageIdentity: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullSourceCacheContext() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - var exception = await Assert.ThrowsAsync( - () => test.Provider.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullLogger() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - var exception = await Assert.ThrowsAsync( - () => test.Provider.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsIfCancelled() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - await Assert.ThrowsAsync( - () => test.Provider.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForFailedSourceIfIgnoreFailedSourcesIsFalse() - { - using (var test = SourceRepositoryDependencyProviderTest.Create(ignoreFailedSources: false)) - { - var resource = new Mock(); - - resource.Setup(x => x.GetPackageDownloaderAsync( - It.IsNotNull(), - It.IsNotNull(), - It.IsNotNull(), - It.IsAny())) - .ThrowsAsync(new FatalProtocolException("simulated")); - - test.SourceRepository.Setup(s => s.GetResourceAsync()) - .ReturnsAsync(resource.Object); - - await Assert.ThrowsAsync( - () => test.Provider.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsNullForFailedSourceIfIgnoreFailedSourcesIsTrue() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - var resource = new Mock(); - - resource.Setup(x => x.GetPackageDownloaderAsync( - It.IsNotNull(), - It.IsNotNull(), - It.IsNotNull(), - It.IsAny())) - .ThrowsAsync(new FatalProtocolException("simulated")); - - test.SourceRepository.Setup(s => s.GetResourceAsync()) - .ReturnsAsync(resource.Object); - - var packageDownloader = await test.Provider.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Null(packageDownloader); - } - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public async Task GetPackageDownloaderAsync_IgnoreWarningControlsWarningLogging(bool ignoreWarning) - { - using (var test = SourceRepositoryDependencyProviderTest.Create(ignoreWarning: ignoreWarning)) - { - var resource = new Mock(); - - resource.Setup(x => x.GetPackageDownloaderAsync( - It.IsNotNull(), - It.IsNotNull(), - It.IsNotNull(), - It.IsAny())) - .ThrowsAsync(new FatalProtocolException("simulated")); - - test.SourceRepository.Setup(s => s.GetResourceAsync()) - .ReturnsAsync(resource.Object); - - Assert.Equal(0, test.Logger.Warnings); - - await test.Provider.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - var expectedWarningCount = ignoreWarning ? 0 : 1; - - Assert.Equal(expectedWarningCount, test.Logger.Warnings); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsPackageDownloader() - { - using (var test = SourceRepositoryDependencyProviderTest.Create()) - { - var expectedPackageDownloader = Mock.Of(); - var resource = new Mock(); - - resource.Setup(x => x.GetPackageDownloaderAsync( - It.IsNotNull(), - It.IsNotNull(), - It.IsNotNull(), - It.IsAny())) - .ReturnsAsync(expectedPackageDownloader); - - test.SourceRepository.Setup(s => s.GetResourceAsync()) - .ReturnsAsync(resource.Object); - - var actualPackageDownloader = await test.Provider.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Same(expectedPackageDownloader, actualPackageDownloader); - } - } - - private sealed class SourceRepositoryDependencyProviderTest : IDisposable - { - internal TestLogger Logger { get; } - internal PackageSource PackageSource { get; } - internal SourceRepositoryDependencyProvider Provider { get; } - internal SourceCacheContext SourceCacheContext { get; } - internal Mock SourceRepository { get; } - - private SourceRepositoryDependencyProviderTest( - TestLogger logger, - PackageSource packageSource, - Mock sourceRepository, - SourceCacheContext sourceCacheContext, - SourceRepositoryDependencyProvider provider) - { - Logger = logger; - PackageSource = packageSource; - SourceRepository = sourceRepository; - SourceCacheContext = sourceCacheContext; - Provider = provider; - } - - public void Dispose() - { - SourceCacheContext.Dispose(); - - GC.SuppressFinalize(this); - } - - internal static SourceRepositoryDependencyProviderTest Create( - bool ignoreFailedSources = true, - bool ignoreWarning = true) - { - var logger = new TestLogger(); - var packageSource = new PackageSource("https://unit.test"); - var sourceRepository = new Mock(); - var sourceCacheContext = new SourceCacheContext(); - - sourceRepository.SetupGet(s => s.PackageSource) - .Returns(packageSource); - - var provider = new SourceRepositoryDependencyProvider( - sourceRepository.Object, - logger, - sourceCacheContext, - ignoreFailedSources, - ignoreWarning); - - return new SourceRepositoryDependencyProviderTest( - logger, - packageSource, - sourceRepository, - sourceCacheContext, - provider); - } + Assert.Equal(1, dependencyHitCount); } } -} \ No newline at end of file +} diff --git a/test/NuGet.Core.Tests/NuGet.Common.Test/PreprocessorTests.cs b/test/NuGet.Core.Tests/NuGet.Common.Test/PreprocessorTests.cs deleted file mode 100644 index fde09fe4b00..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Common.Test/PreprocessorTests.cs +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Xunit; - -namespace NuGet.Common.Test -{ - public class PreprocessorTests - { - [Fact] - public void Process_ThrowsForNullStream() - { - var exception = Assert.Throws( - () => Preprocessor.Process(stream: null, tokenReplacement: t => t)); - - Assert.Equal("stream", exception.ParamName); - } - - [Fact] - public void Process_ThrowsForNullTokenReplacement() - { - var exception = Assert.Throws( - () => Preprocessor.Process(Stream.Null, tokenReplacement: null)); - - Assert.Equal("tokenReplacement", exception.ParamName); - } - - [Fact] - public void Process_ReplacesNoTokens() - { - var rawText = "a b c"; - - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(rawText))) - { - var actualResult = Preprocessor.Process(stream, token => token); - - Assert.Equal(rawText, actualResult); - } - } - - [Fact] - public void Process_ReplacesOneToken() - { - var rawText = "a $b$ c"; - - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(rawText))) - { - var actualResult = Preprocessor.Process(stream, token => "d"); - - Assert.Equal("a d c", actualResult); - } - } - - [Fact] - public void Process_ReplacesTwoTokens() - { - var rawText = "$a$ b $c$"; - - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(rawText))) - { - var actualResult = Preprocessor.Process(stream, token => - { - switch (token) - { - case "a": - return "d"; - - case "c": - return "e"; - - default: - return "f"; - } - }); - - Assert.Equal("d b e", actualResult); - } - } - - [Fact] - public async Task ProcessAsync_ThrowsForNullStreamTaskFactory() - { - var exception = await Assert.ThrowsAsync( - () => Preprocessor.ProcessAsync( - streamTaskFactory: null, - tokenReplacement: t => t, - cancellationToken: CancellationToken.None)); - - Assert.Equal("streamTaskFactory", exception.ParamName); - } - - [Fact] - public async Task ProcessAsync_ThrowsForNullTokenReplacement() - { - var exception = await Assert.ThrowsAsync( - () => Preprocessor.ProcessAsync( - () => Task.FromResult(Stream.Null), - tokenReplacement: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("tokenReplacement", exception.ParamName); - } - - [Fact] - public async Task ProcessAsync_ThrowsIfCanelled() - { - await Assert.ThrowsAsync( - () => Preprocessor.ProcessAsync( - () => Task.FromResult(Stream.Null), - t => t, - new CancellationToken(canceled: true))); - } - - [Fact] - public async Task ProcessAsync_ReplacesNoTokens() - { - var rawText = "a b c"; - - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(rawText))) - { - var actualResult = await Preprocessor.ProcessAsync( - () => Task.FromResult(stream), - token => token, - CancellationToken.None); - - Assert.Equal(rawText, actualResult); - } - } - - [Fact] - public async Task ProcessAsync_ReplacesOneToken() - { - var rawText = "a $b$ c"; - - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(rawText))) - { - var actualResult = await Preprocessor.ProcessAsync( - () => Task.FromResult(stream), - token => "d", - CancellationToken.None); - - Assert.Equal("a d c", actualResult); - } - } - - [Fact] - public async Task ProcessAsync_ReplacesTwoTokens() - { - var rawText = "$a$ b $c$"; - - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(rawText))) - { - var actualResult = await Preprocessor.ProcessAsync( - () => Task.FromResult(stream), - token => - { - switch (token) - { - case "a": - return "d"; - - case "c": - return "e"; - - default: - return "f"; - } - }, - CancellationToken.None); - - Assert.Equal("d b e", actualResult); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.DependencyResolver.Core.Tests/LocalDependencyProviderTests.cs b/test/NuGet.Core.Tests/NuGet.DependencyResolver.Core.Tests/LocalDependencyProviderTests.cs deleted file mode 100644 index 9905a881a0a..00000000000 --- a/test/NuGet.Core.Tests/NuGet.DependencyResolver.Core.Tests/LocalDependencyProviderTests.cs +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Common; -using NuGet.Frameworks; -using NuGet.LibraryModel; -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.DependencyResolver.Tests -{ - public class LocalDependencyProviderTests - { - [Fact] - public void Constructor_ThrowsForNullDependencyProvider() - { - var exception = Assert.Throws( - () => new LocalDependencyProvider(dependencyProvider: null)); - - Assert.Equal("dependencyProvider", exception.ParamName); - } - - [Fact] - public void IsHttp_IsFalse() - { - var provider = new LocalDependencyProvider(Mock.Of()); - - Assert.False(provider.IsHttp); - } - - [Fact] - public void Source_IsNull() - { - var provider = new LocalDependencyProvider(Mock.Of()); - - Assert.Null(provider.Source); - } - - [Fact] - public async Task FindPackageAsync_ThrowsForNullLibraryRange() - { - var provider = new LocalDependencyProvider(Mock.Of()); - - using (var sourceCacheContext = new SourceCacheContext()) - { - var exception = await Assert.ThrowsAsync( - () => provider.FindLibraryAsync( - libraryRange: null, - targetFramework: NuGetFramework.Parse("net45"), - cacheContext: sourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("libraryRange", exception.ParamName); - } - } - - [Fact] - public async Task FindPackageAsync_ThrowsForNullTargetFramework() - { - var provider = new LocalDependencyProvider(Mock.Of()); - - using (var sourceCacheContext = new SourceCacheContext()) - { - var exception = await Assert.ThrowsAsync( - () => provider.FindLibraryAsync( - new LibraryRange(name: "a", typeConstraint: new LibraryDependencyTarget()), - targetFramework: null, - cacheContext: sourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("targetFramework", exception.ParamName); - } - } - - [Fact] - public async Task FindPackageAsync_ReturnsNullIfDependencyProviderReturnsNull() - { - var dependencyProvider = new Mock(); - - dependencyProvider.Setup(x => x.GetLibrary( - It.IsNotNull(), - It.IsNotNull())) - .Returns(null); - - var provider = new LocalDependencyProvider(dependencyProvider.Object); - - using (var sourceCacheContext = new SourceCacheContext()) - { - var libraryIdentity = await provider.FindLibraryAsync( - new LibraryRange(name: "a", typeConstraint: new LibraryDependencyTarget()), - NuGetFramework.Parse("net45"), - sourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Null(libraryIdentity); - } - } - - [Fact] - public async Task FindPackageAsync_ReturnsLibraryIdentity() - { - var library = new Library() - { - Identity = new LibraryIdentity() - }; - var dependencyProvider = new Mock(); - - dependencyProvider.Setup(x => x.GetLibrary( - It.IsNotNull(), - It.IsNotNull())) - .Returns(library); - - var provider = new LocalDependencyProvider(dependencyProvider.Object); - - using (var sourceCacheContext = new SourceCacheContext()) - { - var libraryIdentity = await provider.FindLibraryAsync( - new LibraryRange(name: "a", typeConstraint: new LibraryDependencyTarget()), - NuGetFramework.Parse("net45"), - sourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Same(library.Identity, libraryIdentity); - } - } - - [Fact] - public async Task GetDependenciesAsync_ThrowsForNullLibraryIdentity() - { - var provider = new LocalDependencyProvider(Mock.Of()); - - using (var sourceCacheContext = new SourceCacheContext()) - { - var exception = await Assert.ThrowsAsync( - () => provider.GetDependenciesAsync( - libraryIdentity: null, - targetFramework: NuGetFramework.Parse("net45"), - cacheContext: sourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("libraryIdentity", exception.ParamName); - } - } - - [Fact] - public async Task GetDependenciesAsync_ThrowsForNullTargetFramework() - { - var provider = new LocalDependencyProvider(Mock.Of()); - - using (var sourceCacheContext = new SourceCacheContext()) - { - var exception = await Assert.ThrowsAsync( - () => provider.GetDependenciesAsync( - new LibraryIdentity(name: "a", version: NuGetVersion.Parse("1.0.0"), type: LibraryType.Package), - targetFramework: null, - cacheContext: sourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("targetFramework", exception.ParamName); - } - } - - [Fact] - public async Task GetDependenciesAsync_ReturnsLibraryIdentity() - { - var library = new Library() - { - Identity = new LibraryIdentity( - name: "a", - version: NuGetVersion.Parse("1.0.0"), - type: LibraryType.Package), - Dependencies = new List() - { - new LibraryDependency() - } - }; - var dependencyProvider = new Mock(); - - dependencyProvider.Setup(x => x.GetLibrary( - It.IsNotNull(), - It.IsNotNull())) - .Returns(library); - - var provider = new LocalDependencyProvider(dependencyProvider.Object); - - using (var sourceCacheContext = new SourceCacheContext()) - { - var targetFramework = NuGetFramework.Parse("net45"); - - var dependencyInfo = await provider.GetDependenciesAsync( - library.Identity, - targetFramework, - sourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.NotNull(dependencyInfo); - Assert.Same(library.Dependencies, dependencyInfo.Dependencies); - Assert.Equal(targetFramework, dependencyInfo.Framework); - Assert.Same(library.Identity, dependencyInfo.Library); - Assert.False(dependencyInfo.Resolved); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_Throws() - { - var provider = new LocalDependencyProvider(Mock.Of()); - - using (var sourceCacheContext = new SourceCacheContext()) - { - await Assert.ThrowsAsync( - () => provider.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - sourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.DependencyResolver.Core.Tests/RemoteDependencyWalkerTests.cs b/test/NuGet.Core.Tests/NuGet.DependencyResolver.Core.Tests/RemoteDependencyWalkerTests.cs index 3ff25a95684..fa0d1379bf3 100644 --- a/test/NuGet.Core.Tests/NuGet.DependencyResolver.Core.Tests/RemoteDependencyWalkerTests.cs +++ b/test/NuGet.Core.Tests/NuGet.DependencyResolver.Core.Tests/RemoteDependencyWalkerTests.cs @@ -1,8 +1,9 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -10,8 +11,6 @@ using NuGet.Configuration; using NuGet.Frameworks; using NuGet.LibraryModel; -using NuGet.Packaging; -using NuGet.Packaging.Core; using NuGet.Protocol.Core.Types; using NuGet.Versioning; using Xunit; @@ -832,8 +831,9 @@ public bool IsHttp public PackageSource Source => new PackageSource("Test"); - public Task GetPackageDownloaderAsync( - PackageIdentity packageIdentity, + public Task CopyToAsync( + LibraryIdentity match, + Stream stream, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken) diff --git a/test/NuGet.Core.Tests/NuGet.DependencyResolver.Core.Tests/ResolverFacts.cs b/test/NuGet.Core.Tests/NuGet.DependencyResolver.Core.Tests/ResolverFacts.cs index 9d2688297c2..9663663dc5b 100644 --- a/test/NuGet.Core.Tests/NuGet.DependencyResolver.Core.Tests/ResolverFacts.cs +++ b/test/NuGet.Core.Tests/NuGet.DependencyResolver.Core.Tests/ResolverFacts.cs @@ -1,8 +1,9 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -11,8 +12,6 @@ using NuGet.DependencyResolver.Tests; using NuGet.Frameworks; using NuGet.LibraryModel; -using NuGet.Packaging; -using NuGet.Packaging.Core; using NuGet.Protocol.Core.Types; using NuGet.Versioning; using Xunit; @@ -120,6 +119,16 @@ public void AddLibrary(LibraryIdentity identity) public PackageSource Source => new PackageSource("Test"); + public Task CopyToAsync( + LibraryIdentity match, + Stream stream, + SourceCacheContext cacheContext, + ILogger logger, + CancellationToken cancellationToken) + { + throw new NotImplementedException(); + } + public async Task FindLibraryAsync( LibraryRange libraryRange, NuGetFramework targetFramework, @@ -145,23 +154,10 @@ public Task GetDependenciesAsync( return Task.FromResult(LibraryDependencyInfo.Create(match, targetFramework, Enumerable.Empty())); } - public Task> GetAllVersionsAsync( - string id, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken token) + public Task> GetAllVersionsAsync(string id, SourceCacheContext cacheContext, ILogger logger, CancellationToken token) { return Task.FromResult(_libraries.Select(e => e.Version)); } - - public Task GetPackageDownloaderAsync( - PackageIdentity packageIdentity, - SourceCacheContext cacheContext, - ILogger logger, - CancellationToken cancellationToken) - { - throw new NotImplementedException(); - } } } -} \ No newline at end of file +} diff --git a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/FileModifiers/PreprocessorTests.cs b/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/FileModifiers/PreprocessorTests.cs deleted file mode 100644 index e682d619e67..00000000000 --- a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/FileModifiers/PreprocessorTests.cs +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.ProjectManagement; -using NuGet.Test.Utility; -using Xunit; - -namespace NuGet.PackageManagement.Test -{ - public class PreprocessorTests - { - private readonly Preprocessor _processor; - - public PreprocessorTests() - { - _processor = new Preprocessor(); - } - - [Fact] - public async Task TransformFileAsync_ThrowsForNullStreamTaskFactory() - { - var exception = await Assert.ThrowsAsync( - () => _processor.TransformFileAsync( - streamTaskFactory: null, - targetPath: "a", - projectSystem: Mock.Of(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("streamTaskFactory", exception.ParamName); - } - - [Fact] - public async Task TransformFileAsync_ThrowsForNullProjectSystem() - { - var exception = await Assert.ThrowsAsync( - () => _processor.TransformFileAsync( - () => Task.FromResult(Stream.Null), - targetPath: "a", - projectSystem: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("projectSystem", exception.ParamName); - } - - [Fact] - public async Task TransformFileAsync_ThrowsIfCancelled() - { - await Assert.ThrowsAsync( - () => _processor.TransformFileAsync( - () => Task.FromResult(Stream.Null), - targetPath: "a", - projectSystem: Mock.Of(), - cancellationToken: new CancellationToken(canceled: true))); - } - - [Fact] - public async Task TransformFileAsync_AddsFileToProject() - { - using (var test = new PreprocessorTest("a")) - { - test.ProjectSystem.Setup(x => x.FileExistsInProject(It.IsNotNull())) - .Returns(false); - - test.ProjectSystem.Setup(x => x.AddFile(It.IsNotNull(), It.IsNotNull())) - .Callback( - (filePath, stream) => - { - Assert.Equal(test.TargetFile.FullName, filePath); - - stream.Seek(offset: 0, origin: SeekOrigin.Begin); - - using (var reader = new StreamReader(stream)) - { - var actualStreamContent = reader.ReadToEnd(); - - Assert.Equal(test.StreamContent, actualStreamContent); - } - }); - - await test.Processor.TransformFileAsync( - test.StreamTaskFactory, - test.TargetFile.FullName, - test.ProjectSystem.Object, - CancellationToken.None); - } - } - - [Fact] - public async Task RevertFileAsync_ThrowsForNullStreamTaskFactory() - { - var exception = await Assert.ThrowsAsync( - () => _processor.RevertFileAsync( - streamTaskFactory: null, - targetPath: "a", - matchingFiles: Enumerable.Empty(), - projectSystem: Mock.Of(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("streamTaskFactory", exception.ParamName); - } - - [Fact] - public async Task RevertFileAsync_ThrowsForNullProjectSystem() - { - var exception = await Assert.ThrowsAsync( - () => _processor.RevertFileAsync( - () => Task.FromResult(Stream.Null), - targetPath: "a", - matchingFiles: Enumerable.Empty(), - projectSystem: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("projectSystem", exception.ParamName); - } - - [Fact] - public async Task RevertFileAsync_ThrowsIfCancelled() - { - await Assert.ThrowsAsync( - () => _processor.RevertFileAsync( - () => Task.FromResult(Stream.Null), - targetPath: "a", - matchingFiles: Enumerable.Empty(), - projectSystem: Mock.Of(), - cancellationToken: new CancellationToken(canceled: true))); - } - - [Fact] - public async Task RevertFileAsync_RemovesFileFromProject() - { - using (var test = new PreprocessorTest("a")) - { - File.WriteAllText(test.TargetFile.FullName, test.StreamContent); - - test.ProjectSystem.Setup(x => x.FileExistsInProject(It.IsNotNull())) - .Returns(true); - - test.ProjectSystem.SetupGet(x => x.ProjectFullPath) - .Returns(test.TargetFile.DirectoryName); - - test.ProjectSystem.SetupGet(x => x.NuGetProjectContext) - .Returns((INuGetProjectContext)null); - - test.ProjectSystem.Setup(x => x.RemoveFile(It.IsNotNull())) - .Callback( - (filePath) => - { - Assert.Equal(test.TargetFile.FullName, filePath); - }); - - await test.Processor.RevertFileAsync( - test.StreamTaskFactory, - test.TargetFile.FullName, - Enumerable.Empty(), - test.ProjectSystem.Object, - CancellationToken.None); - } - } - - private sealed class PreprocessorTest : IDisposable - { - private readonly MemoryStream _stream; - - internal Preprocessor Processor { get; } - internal Mock ProjectSystem { get; } - internal string StreamContent { get; } - internal Func> StreamTaskFactory { get; } - internal FileInfo TargetFile { get; } - internal TestDirectory TestDirectory { get; } - - internal PreprocessorTest(string streamContent) - { - _stream = new MemoryStream(Encoding.UTF8.GetBytes(streamContent)); - - StreamContent = streamContent; - StreamTaskFactory = () => Task.FromResult(_stream); - Processor = new Preprocessor(); - ProjectSystem = new Mock(MockBehavior.Strict); - TestDirectory = TestDirectory.Create(); - TargetFile = new FileInfo(Path.Combine(TestDirectory.Path, "target.file")); - } - - public void Dispose() - { - _stream.Dispose(); - TestDirectory.Dispose(); - - GC.SuppressFinalize(this); - - ProjectSystem.Verify(); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/FileModifiers/XdtTransformerTests.cs b/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/FileModifiers/XdtTransformerTests.cs deleted file mode 100644 index 2a598909482..00000000000 --- a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/FileModifiers/XdtTransformerTests.cs +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using System.IO; -using System.IO.Compression; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.ProjectManagement; -using NuGet.Test.Utility; -using Xunit; - -namespace NuGet.PackageManagement.Test -{ - public class XdtTransformerTests - { - private readonly XdtTransformer _transformer; - - public XdtTransformerTests() - { - _transformer = new XdtTransformer(); - } - - [Fact] - public async Task TransformFileAsync_ThrowsForNullStreamTaskFactory() - { - var exception = await Assert.ThrowsAsync( - () => _transformer.TransformFileAsync( - streamTaskFactory: null, - targetPath: "a", - projectSystem: Mock.Of(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("streamTaskFactory", exception.ParamName); - } - - [Fact] - public async Task TransformFileAsync_ThrowsForNullProjectSystem() - { - var exception = await Assert.ThrowsAsync( - () => _transformer.TransformFileAsync( - () => Task.FromResult(Stream.Null), - targetPath: "a", - projectSystem: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("projectSystem", exception.ParamName); - } - - [Fact] - public async Task TransformFileAsync_ThrowsIfCancelled() - { - await Assert.ThrowsAsync( - () => _transformer.TransformFileAsync( - () => Task.FromResult(Stream.Null), - targetPath: "a", - projectSystem: Mock.Of(), - cancellationToken: new CancellationToken(canceled: true))); - } - - [Fact] - public async Task TransformFileAsync_TransformsFile() - { - using (var test = new XdtTransformerTest("$c$")) - { - var projectFileOriginalContent = ""; - - File.WriteAllText(test.TargetFile.FullName, projectFileOriginalContent); - - test.ProjectSystem.SetupGet(x => x.ProjectFullPath) - .Returns(test.TargetFile.DirectoryName); - test.ProjectSystem.SetupGet(x => x.ProjectName) - .Returns("ProjectName"); - test.ProjectSystem.Setup(x => x.GetPropertyValue(It.IsNotNull())) - .Returns("d"); - test.ProjectSystem.Setup(x => x.AddFile(It.IsNotNull(), It.IsNotNull())) - .Callback( - (targetFilePath, stream) => - { - Assert.Equal(test.TargetFile.Name, targetFilePath); - - stream.Seek(offset: 0, origin: SeekOrigin.Begin); - - using (var reader = new StreamReader(stream)) - { - var actualResult = reader.ReadToEnd(); - var expectedResult = "\t\t\t\t\td\t\t\t"; - - Assert.Equal(expectedResult, actualResult); - } - }); - - await test.Transformer.TransformFileAsync( - test.StreamTaskFactory, - test.TargetFile.Name, - test.ProjectSystem.Object, - CancellationToken.None); - } - } - - [Fact] - public async Task RevertFileAsync_ThrowsForNullStreamTaskFactory() - { - var exception = await Assert.ThrowsAsync( - () => _transformer.RevertFileAsync( - streamTaskFactory: null, - targetPath: "a", - matchingFiles: Enumerable.Empty(), - projectSystem: Mock.Of(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("streamTaskFactory", exception.ParamName); - } - - [Fact] - public async Task RevertFileAsync_ThrowsForNullProjectSystem() - { - var exception = await Assert.ThrowsAsync( - () => _transformer.RevertFileAsync( - () => Task.FromResult(Stream.Null), - targetPath: "a", - matchingFiles: Enumerable.Empty(), - projectSystem: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("projectSystem", exception.ParamName); - } - - [Fact] - public async Task RevertFileAsync_ThrowsIfCancelled() - { - await Assert.ThrowsAsync( - () => _transformer.RevertFileAsync( - () => Task.FromResult(Stream.Null), - targetPath: "a", - matchingFiles: Enumerable.Empty(), - projectSystem: Mock.Of(), - cancellationToken: new CancellationToken(canceled: true))); - } - - [Fact] - public async Task RevertFileAsync_RevertsFile() - { - var projectFileContent = string.Format( - CultureInfo.InvariantCulture, - "{0} {0} d{0} {0} d{0} {0} {0}", - Environment.NewLine); - - using (var test = new XdtTransformerTest("$c$")) - { - var zipArchiveFilePath = Path.Combine(test.TestDirectory.Path, "archive.zip"); - var zipFileInfo = new InternalZipFileInfo(zipArchiveFilePath, "install.xdt"); - - using (var zipFileStream = File.OpenWrite(zipArchiveFilePath)) - using (var zipArchive = new ZipArchive(zipFileStream, ZipArchiveMode.Create)) - { - var content = Encoding.UTF8.GetBytes("$c$"); - - zipArchive.AddEntry(zipFileInfo.ZipArchiveEntryFullName, content); - } - - File.WriteAllText(test.TargetFile.FullName, projectFileContent); - - test.ProjectSystem.SetupGet(x => x.ProjectFullPath) - .Returns(test.TargetFile.DirectoryName); - test.ProjectSystem.SetupGet(x => x.ProjectName) - .Returns("ProjectName"); - test.ProjectSystem.Setup(x => x.GetPropertyValue(It.IsNotNull())) - .Returns("d"); - test.ProjectSystem.Setup(x => x.AddFile(It.IsNotNull(), It.IsNotNull())) - .Callback( - (targetFilePath, stream) => - { - Assert.Equal(test.TargetFile.Name, targetFilePath); - - stream.Seek(offset: 0, origin: SeekOrigin.Begin); - - using (var reader = new StreamReader(stream)) - { - var actualResult = reader.ReadToEnd(); - var expectedResult = string.Format( - CultureInfo.InvariantCulture, - "{0} {0} d{0} {0}", - Environment.NewLine); - - Assert.Equal(expectedResult, actualResult); - } - }); - - await test.Transformer.RevertFileAsync( - test.StreamTaskFactory, - test.TargetFile.Name, - new[] { zipFileInfo }, - test.ProjectSystem.Object, - CancellationToken.None); - } - } - - private sealed class XdtTransformerTest : IDisposable - { - private readonly MemoryStream _stream; - - internal Mock ProjectSystem { get; } - internal Func> StreamTaskFactory { get; } - internal FileInfo TargetFile { get; } - internal TestDirectory TestDirectory { get; } - internal XdtTransformer Transformer { get; } - internal string TransformStreamContent { get; } - - internal XdtTransformerTest(string transformStreamContent) - { - _stream = new MemoryStream(Encoding.UTF8.GetBytes(transformStreamContent)); - - TransformStreamContent = transformStreamContent; - StreamTaskFactory = () => Task.FromResult(_stream); - Transformer = new XdtTransformer(); - ProjectSystem = new Mock(MockBehavior.Strict); - TestDirectory = TestDirectory.Create(); - TargetFile = new FileInfo(Path.Combine(TestDirectory.Path, "target.file")); - } - - public void Dispose() - { - _stream.Dispose(); - TestDirectory.Dispose(); - - GC.SuppressFinalize(this); - - ProjectSystem.Verify(); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/FileModifiers/XmlTransformerTests.cs b/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/FileModifiers/XmlTransformerTests.cs deleted file mode 100644 index 34973ae7c0e..00000000000 --- a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/FileModifiers/XmlTransformerTests.cs +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.IO.Compression; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Xml.Linq; -using Moq; -using NuGet.ProjectManagement; -using NuGet.Test.Utility; -using Xunit; - -namespace NuGet.PackageManagement.Test -{ - public class XmlTransformerTests - { - private readonly XmlTransformer _transformer; - - public XmlTransformerTests() - { - _transformer = new XmlTransformer(new Dictionary> - { - { "x", (parent, element) => parent.AddFirst(element) } - }); - } - - [Fact] - public void Constructor_ThrowsForNullNodeActions() - { - var exception = Assert.Throws( - () => new XmlTransformer(nodeActions: null)); - - Assert.Equal("nodeActions", exception.ParamName); - } - - [Fact] - public async Task TransformFileAsync_ThrowsForNullStreamTaskFactory() - { - var exception = await Assert.ThrowsAsync( - () => _transformer.TransformFileAsync( - streamTaskFactory: null, - targetPath: "a", - projectSystem: Mock.Of(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("streamTaskFactory", exception.ParamName); - } - - [Fact] - public async Task TransformFileAsync_ThrowsForNullProjectSystem() - { - var exception = await Assert.ThrowsAsync( - () => _transformer.TransformFileAsync( - () => Task.FromResult(Stream.Null), - targetPath: "a", - projectSystem: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("projectSystem", exception.ParamName); - } - - [Fact] - public async Task TransformFileAsync_ThrowsIfCancelled() - { - await Assert.ThrowsAsync( - () => _transformer.TransformFileAsync( - () => Task.FromResult(Stream.Null), - targetPath: "a", - projectSystem: Mock.Of(), - cancellationToken: new CancellationToken(canceled: true))); - } - - [Fact] - public async Task TransformFileAsync_TransformsFile() - { - using (var test = new XmlTransformerTest("$c$")) - { - var projectFileOriginalContent = ""; - - File.WriteAllText(test.TargetFile.FullName, projectFileOriginalContent); - - test.ProjectSystem.Setup(x => x.FileExistsInProject(It.IsNotNull())) - .Returns(false); - test.ProjectSystem.SetupGet(x => x.ProjectFullPath) - .Returns(test.TargetFile.DirectoryName); - test.ProjectSystem.SetupGet(x => x.NuGetProjectContext) - .Returns(Mock.Of()); - test.ProjectSystem.Setup(x => x.GetPropertyValue(It.IsNotNull())) - .Returns("d"); - test.ProjectSystem.Setup(x => x.AddFile(It.IsNotNull(), It.IsNotNull())) - .Callback( - (targetFilePath, stream) => - { - Assert.Equal(test.TargetFile.Name, targetFilePath); - - stream.Seek(offset: 0, origin: SeekOrigin.Begin); - - using (var reader = new StreamReader(stream)) - { - var actualResult = reader.ReadToEnd(); - var expectedResult = string.Format( - CultureInfo.InvariantCulture, - "{0}{0} {0} {0} {0} d{0}", - Environment.NewLine); - - Assert.Equal(expectedResult, actualResult); - } - }); - - await test.Transformer.TransformFileAsync( - test.StreamTaskFactory, - test.TargetFile.Name, - test.ProjectSystem.Object, - CancellationToken.None); - } - } - - [Fact] - public async Task RevertFileAsync_ThrowsForNullStreamTaskFactory() - { - var exception = await Assert.ThrowsAsync( - () => _transformer.RevertFileAsync( - streamTaskFactory: null, - targetPath: "a", - matchingFiles: Enumerable.Empty(), - projectSystem: Mock.Of(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("streamTaskFactory", exception.ParamName); - } - - [Fact] - public async Task RevertFileAsync_ThrowsForNullProjectSystem() - { - var exception = await Assert.ThrowsAsync( - () => _transformer.RevertFileAsync( - () => Task.FromResult(Stream.Null), - targetPath: "a", - matchingFiles: Enumerable.Empty(), - projectSystem: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("projectSystem", exception.ParamName); - } - - [Fact] - public async Task RevertFileAsync_ThrowsIfCancelled() - { - await Assert.ThrowsAsync( - () => _transformer.RevertFileAsync( - () => Task.FromResult(Stream.Null), - targetPath: "a", - matchingFiles: Enumerable.Empty(), - projectSystem: Mock.Of(), - cancellationToken: new CancellationToken(canceled: true))); - } - - [Fact] - public async Task RevertFileAsync_RevertsFile() - { - var projectFileContent = string.Format( - CultureInfo.InvariantCulture, - "{0}{0} {0} {0} d{0} {0} d{0}", - Environment.NewLine); - - using (var test = new XmlTransformerTest(projectFileContent)) - { - var zipArchiveFilePath = Path.Combine(test.TestDirectory.Path, "archive.zip"); - var zipFileInfo = new InternalZipFileInfo(zipArchiveFilePath, "xml.transform"); - - using (var zipFileStream = File.OpenWrite(zipArchiveFilePath)) - using (var zipArchive = new ZipArchive(zipFileStream, ZipArchiveMode.Create)) - { - var content = Encoding.UTF8.GetBytes("$c$"); - - zipArchive.AddEntry(zipFileInfo.ZipArchiveEntryFullName, content); - } - - File.WriteAllText(test.TargetFile.FullName, projectFileContent); - - test.ProjectSystem.Setup(x => x.FileExistsInProject(It.IsNotNull())) - .Returns(true); - test.ProjectSystem.SetupGet(x => x.ProjectFullPath) - .Returns(test.TargetFile.DirectoryName); - test.ProjectSystem.SetupGet(x => x.NuGetProjectContext) - .Returns(Mock.Of()); - test.ProjectSystem.Setup(x => x.GetPropertyValue(It.IsNotNull())) - .Returns("d"); - test.ProjectSystem.Setup(x => x.RemoveFile(It.IsNotNull())); - - await test.Transformer.RevertFileAsync( - test.StreamTaskFactory, - test.TargetFile.Name, - new[] { zipFileInfo }, - test.ProjectSystem.Object, - CancellationToken.None); - - var expectedResult = string.Format( - CultureInfo.InvariantCulture, - "{0}{0} {0} {0} d{0} {0} {0}", - Environment.NewLine); - var actualResult = File.ReadAllText(test.TargetFile.FullName); - - Assert.Equal(expectedResult, actualResult); - } - } - - private sealed class XmlTransformerTest : IDisposable - { - private readonly MemoryStream _stream; - - internal Mock ProjectSystem { get; } - internal Func> StreamTaskFactory { get; } - internal FileInfo TargetFile { get; } - internal TestDirectory TestDirectory { get; } - internal XmlTransformer Transformer { get; } - internal string TransformStreamContent { get; } - - internal XmlTransformerTest(string transformStreamContent) - { - _stream = new MemoryStream(Encoding.UTF8.GetBytes(transformStreamContent)); - - TransformStreamContent = transformStreamContent; - StreamTaskFactory = () => Task.FromResult(_stream); - Transformer = new XmlTransformer(new Dictionary> - { - { "x", (parent, element) => parent.AddFirst(element) } - }); - ProjectSystem = new Mock(MockBehavior.Strict); - TestDirectory = TestDirectory.Create(); - TargetFile = new FileInfo(Path.Combine(TestDirectory.Path, "target.file")); - } - - public void Dispose() - { - _stream.Dispose(); - TestDirectory.Dispose(); - - GC.SuppressFinalize(this); - - ProjectSystem.Verify(); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/InstallationCompatibilityTests.cs b/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/InstallationCompatibilityTests.cs index cb2c27e30ab..e30bc5d22f8 100644 --- a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/InstallationCompatibilityTests.cs +++ b/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/InstallationCompatibilityTests.cs @@ -1,11 +1,10 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Moq; @@ -31,57 +30,7 @@ namespace NuGet.PackageManagement.Test public class InstallationCompatibilityTests { [Fact] - public async Task EnsurePackageCompatibilityAsync_ThrowsForNullNuGetProject() - { - var exception = await Assert.ThrowsAsync( - () => InstallationCompatibility.Instance.EnsurePackageCompatibilityAsync( - nuGetProject: null, - packageIdentity: new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - resourceResult: new DownloadResourceResult(DownloadResourceResultStatus.NotFound), - cancellationToken: CancellationToken.None)); - - Assert.Equal("nuGetProject", exception.ParamName); - } - - [Fact] - public async Task EnsurePackageCompatibilityAsync_ThrowsForNullPackageIdentity() - { - var exception = await Assert.ThrowsAsync( - () => InstallationCompatibility.Instance.EnsurePackageCompatibilityAsync( - Mock.Of(), - packageIdentity: null, - resourceResult: new DownloadResourceResult(DownloadResourceResultStatus.NotFound), - cancellationToken: CancellationToken.None)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - - [Fact] - public async Task EnsurePackageCompatibilityAsync_ThrowsForNullResourceResult() - { - var exception = await Assert.ThrowsAsync( - () => InstallationCompatibility.Instance.EnsurePackageCompatibilityAsync( - Mock.Of(), - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - resourceResult: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("resourceResult", exception.ParamName); - } - - [Fact] - public async Task EnsurePackageCompatibilityAsync_ThrowsIfCancelled() - { - await Assert.ThrowsAsync( - () => InstallationCompatibility.Instance.EnsurePackageCompatibilityAsync( - Mock.Of(), - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - new DownloadResourceResult(DownloadResourceResultStatus.NotFound), - new CancellationToken(canceled: true))); - } - - [Fact] - public async Task EnsurePackageCompatibilityAsync_WithLowerMinClientVersion_Fails() + public void InstallationCompatibility_WithLowerMinClientVersion_Fails() { // Arrange var tc = new TestContext(); @@ -89,12 +38,11 @@ public async Task EnsurePackageCompatibilityAsync_WithLowerMinClientVersion_Fail var result = new DownloadResourceResult(Stream.Null, tc.PackageReader.Object); // Act & Assert - var ex = await Assert.ThrowsAsync(() => - tc.Target.EnsurePackageCompatibilityAsync( + var ex = Assert.Throws(() => + tc.Target.EnsurePackageCompatibility( tc.NuGetProject, tc.PackageIdentityA, - result, - CancellationToken.None)); + result)); Assert.Equal( "The 'PackageA 1.0.0' package requires NuGet client version '10.0.0' or above, " + @@ -109,7 +57,7 @@ public async Task EnsurePackageCompatibilityAsync_WithLowerMinClientVersion_Fail } [Fact] - public async Task EnsurePackageCompatibility_WithValidProjectActions_Succeeds() + public async Task InstallationCompatibility_WithValidProjectActions_Succeeds() { // Arrange using (var userPackageFolder = TestDirectory.Create()) @@ -156,7 +104,7 @@ await SimpleTestPackageUtility.CreateFolderFeedV3( } [Fact] - public async Task EnsurePackageCompatibility_WithInvalidProjectActions_Fails() + public async Task InstallationCompatibility_WithInvalidProjectActions_Fails() { // Arrange using (var userPackageFolder = TestDirectory.Create()) @@ -192,33 +140,33 @@ await SimpleTestPackageUtility.CreateFolderFeedV3( } [Fact] - public async Task EnsurePackageCompatibilityAsync_WithNuGetProject_WithInvalidType_Fails() + public void InstallationCompatibility_WithNuGetProject_WithInvalidType_Fails() { // Arrange var tc = new TestContext(); tc.PackageTypes.Add(tc.InvalidPackageType); // Act & Assert - await tc.VerifyFailureAsync( + tc.VerifyFailure( tc.NuGetProject, "Package 'PackageA 1.0.0' has a package type 'Invalid 1.2' that is not supported by project 'TestNuGetProject'."); } [Fact] - public async Task EnsurePackageCompatibilityAsync_WithNuGetProject_WithInvalidTypeAndEmptyVersion_Fails() + public void InstallationCompatibility_WithNuGetProject_WithInvalidTypeAndEmptyVersion_Fails() { // Arrange var tc = new TestContext(); tc.PackageTypes.Add(new PackageType("Invalid", PackageType.EmptyVersion)); // Act & Assert - await tc.VerifyFailureAsync( + tc.VerifyFailure( tc.NuGetProject, "Package 'PackageA 1.0.0' has a package type 'Invalid' that is not supported by project 'TestNuGetProject'."); } [Fact] - public async Task EnsurePackageCompatibilityAsync_WithNuGetProject_WitMultipleTypes_Fails() + public void InstallationCompatibility_WithNuGetProject_WitMultipleTypes_Fails() { // Arrange var tc = new TestContext(); @@ -226,61 +174,61 @@ public async Task EnsurePackageCompatibilityAsync_WithNuGetProject_WitMultipleTy tc.PackageTypes.Add(PackageType.Dependency); // Act & Assert - await tc.VerifyFailureAsync( + tc.VerifyFailure( tc.NuGetProject, "Package 'PackageA 1.0.0' has multiple package types, which is not supported."); } [Fact] - public async Task EnsurePackageCompatibilityAsync_WithNuGetProject_WithDotnetCliToolType_Fails() + public void InstallationCompatibility_WithNuGetProject_WithDotnetCliToolType_Fails() { // Arrange var tc = new TestContext(); tc.PackageTypes.Add(PackageType.DotnetCliTool); // Act & Assert - await tc.VerifyFailureAsync( + tc.VerifyFailure( tc.NuGetProject, "Package 'PackageA 1.0.0' has a package type 'DotnetCliTool' that is not supported by project 'TestNuGetProject'."); } [Fact] - public async Task EnsurePackageCompatibilityAsync_WithNuGetProject_WithLegacyType_Succeeds() + public void InstallationCompatibility_WithNuGetProject_WithLegacyType_Succeeds() { // Arrange var tc = new TestContext(); tc.PackageTypes.Add(PackageType.Legacy); // Act & Assert - await tc.VerifySuccessAsync(tc.NuGetProject); + tc.VerifySuccess(tc.NuGetProject); } [Fact] - public async Task EnsurePackageCompatibilityAsync_WithNuGetProject_WithDependency_Succeeds() + public void InstallationCompatibility_WithNuGetProject_WithDependency_Succeeds() { // Arrange var tc = new TestContext(); tc.PackageTypes.Add(PackageType.Dependency); // Act & Assert - await tc.VerifySuccessAsync(tc.NuGetProject); + tc.VerifySuccess(tc.NuGetProject); } [Fact] - public async Task EnsurePackageCompatibilityAsync_WithProjectKProject_WithInvalidType_Fails() + public void InstallationCompatibility_WithProjectKProject_WithInvalidType_Fails() { // Arrange var tc = new TestContext(); tc.PackageTypes.Add(tc.InvalidPackageType); // Act & Assert - await tc.VerifyFailureAsync( + tc.VerifyFailure( tc.ProjectKProject, "Package 'PackageA 1.0.0' has a package type 'Invalid 1.2' that is not supported by project 'TestProjectKNuGetProject'."); } [Fact] - public async Task EnsurePackageCompatibilityAsync_WithProjectKProject_WithMultipleTypes_Fails() + public void InstallationCompatibility_WithProjectKProject_WithMultipleTypes_Fails() { // Arrange var tc = new TestContext(); @@ -288,42 +236,42 @@ public async Task EnsurePackageCompatibilityAsync_WithProjectKProject_WithMultip tc.PackageTypes.Add(PackageType.Dependency); // Act & Assert - await tc.VerifyFailureAsync( + tc.VerifyFailure( tc.ProjectKProject, "Package 'PackageA 1.0.0' has multiple package types, which is not supported."); } [Fact] - public async Task EnsurePackageCompatibilityAsync_WithProjectKProject_WithDotnetCliToolType_Succeeds() + public void InstallationCompatibility_WithProjectKProject_WithDotnetCliToolType_Succeeds() { // Arrange var tc = new TestContext(); tc.PackageTypes.Add(PackageType.DotnetCliTool); // Act & Assert - await tc.VerifySuccessAsync(tc.ProjectKProject); + tc.VerifySuccess(tc.ProjectKProject); } [Fact] - public async Task EnsurePackageCompatibilityAsync_WithProjectKProject_WithLegacyType_Succeeds() + public void InstallationCompatibility_WithProjectKProject_WithLegacyType_Succeeds() { // Arrange var tc = new TestContext(); tc.PackageTypes.Add(PackageType.Legacy); // Act & Assert - await tc.VerifySuccessAsync(tc.ProjectKProject); + tc.VerifySuccess(tc.ProjectKProject); } [Fact] - public async Task EnsurePackageCompatibilityAsync_WithProjectKProject_WithDependency_Succeeds() + public void InstallationCompatibility_WithProjectKProject_WithDependency_Succeeds() { // Arrange var tc = new TestContext(); tc.PackageTypes.Add(PackageType.Dependency); // Act & Assert - await tc.VerifySuccessAsync(tc.ProjectKProject); + tc.VerifySuccess(tc.ProjectKProject); } private class TestContext @@ -404,7 +352,7 @@ public TestContext(string userPackageFolder = null) public InstallationCompatibility Target { get; } public PackageType InvalidPackageType { get; } - public async Task VerifyFailureAsync( + public void VerifyFailure( NuGetProject nugetProject, string expected) { @@ -412,12 +360,11 @@ public async Task VerifyFailureAsync( var result = new DownloadResourceResult(Stream.Null, PackageReader.Object); // Act & Assert - var ex = await Assert.ThrowsAsync(() => - Target.EnsurePackageCompatibilityAsync( + var ex = Assert.Throws(() => + Target.EnsurePackageCompatibility( nugetProject, PackageIdentityA, - result, - CancellationToken.None)); + result)); Assert.Equal(expected, ex.Message); PackageReader.Verify(x => x.GetMinClientVersion(), Times.Never); @@ -426,17 +373,16 @@ public async Task VerifyFailureAsync( NuspecReader.Verify(x => x.GetPackageTypes(), Times.Once); } - public async Task VerifySuccessAsync(NuGetProject nugetProject) + public void VerifySuccess(NuGetProject nugetProject) { // Arrange var result = new DownloadResourceResult(Stream.Null, PackageReader.Object); // Act & Assert - await Target.EnsurePackageCompatibilityAsync( + Target.EnsurePackageCompatibility( nugetProject, PackageIdentityA, - result, - CancellationToken.None); + result); PackageReader.Verify(x => x.GetMinClientVersion(), Times.Never); PackageReader.Verify(x => x.GetPackageTypes(), Times.Never); @@ -513,4 +459,4 @@ public RestoreResult GetRestoreResult(IEnumerable identities) } } } -} \ No newline at end of file +} diff --git a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/NuGetPackageManagerTests.cs b/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/NuGetPackageManagerTests.cs index ad9c5e636dc..d5335e64cfc 100644 --- a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/NuGetPackageManagerTests.cs +++ b/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/NuGetPackageManagerTests.cs @@ -121,7 +121,7 @@ public async Task TestPacManInstallAndRequestInstalledPackages() // Act // Install and Uninstall 50 times while polling for installed packages - for (var i = 0; i < 50; i++) + for (int i = 0; i < 50; i++) { // Install await nuGetPackageManager.InstallPackageAsync(projectA, "packageA", @@ -198,11 +198,10 @@ await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdenti // Ensure that installation compatibility was checked. installationCompatibility.Verify( - x => x.EnsurePackageCompatibilityAsync( + x => x.EnsurePackageCompatibility( msBuildNuGetProject, packageIdentity, - It.IsAny(), - It.IsAny()), + It.IsAny()), Times.Once); installationCompatibility.Verify( x => x.EnsurePackageCompatibility( @@ -5547,9 +5546,9 @@ public async Task TestPacMan_PreviewUpdatePackage_DeepDependencies() // Set up Package Dependencies var dependencies = new List(); - for (var j = 1; j < 3; j++) + for (int j = 1; j < 3; j++) { - for (var i = 2; i <= 30; i++) + for (int i = 2; i <= 30; i++) { dependencies.Add(new PackageDependency($"Package{i}", new VersionRange(new NuGetVersion(j, 0, 0)))); } @@ -5557,10 +5556,10 @@ public async Task TestPacMan_PreviewUpdatePackage_DeepDependencies() // Set up Package Source var packages = new List(); - var next = 1; - for (var i = 1; i < 3; i++) + int next = 1; + for (int i = 1; i < 3; i++) { - for (var j = 1; j < 30; j++) + for (int j = 1; j < 30; j++) { next = j + 1; packages.Add(new SourcePackageDependencyInfo($"Package{j}", new NuGetVersion(i, 0, 0), @@ -5584,7 +5583,7 @@ public async Task TestPacMan_PreviewUpdatePackage_DeepDependencies() var fwk45 = NuGetFramework.Parse("net45"); var installedPackages = new List(); - for (var i = 1; i <= 30; i++) + for (int i = 1; i <= 30; i++) { installedPackages.Add(new PackageReference( new PackageIdentity($"Package{i}", new NuGetVersion(1, 0, 0)), fwk45, true)); @@ -5627,7 +5626,7 @@ public async Task TestPacMan_PreviewUpdatePackage_DeepDependencies() var resulting = result.Select(a => Tuple.Create(a.PackageIdentity, a.NuGetProjectActionType)).ToArray(); var expected = new List>(); - for (var i = 1; i <= 30; i++) + for (int i = 1; i <= 30; i++) { Expected(expected, $"Package{i}", new NuGetVersion(1, 0, 0), new NuGetVersion(2, 0, 0)); } @@ -6132,7 +6131,7 @@ private static bool Compare( IEnumerable> lhs, IEnumerable> rhs) { - var ok = true; + bool ok = true; ok &= RhsContainsAllLhs(lhs, rhs); ok &= RhsContainsAllLhs(rhs, lhs); return ok; @@ -6156,8 +6155,8 @@ private class ActionComparer : IEqualityComparer x, Tuple y) { - var f1 = x.Item1.Equals(y.Item1); - var f2 = x.Item2 == y.Item2; + bool f1 = x.Item1.Equals(y.Item1); + bool f2 = x.Item2 == y.Item2; return f1 && f2; } @@ -6167,4 +6166,4 @@ public int GetHashCode(Tuple obj) } } } -} \ No newline at end of file +} diff --git a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/PackageDownloaderTests.cs b/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/PackageDownloaderTests.cs index 530fcd8ac5f..787fff071fa 100644 --- a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/PackageDownloaderTests.cs +++ b/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/PackageDownloaderTests.cs @@ -1,16 +1,13 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; -using System.IO.Compression; using System.Linq; using System.Threading; using System.Threading.Tasks; -using Moq; using NuGet.Common; using NuGet.Configuration; -using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Protocol; using NuGet.Protocol.Core.Types; @@ -23,216 +20,11 @@ namespace NuGet.PackageManagement { public class PackageDownloaderTests { + /// + /// Verifies that download throws when package does not exist in V2 + /// [Fact] - public async Task GetDownloadResourceResultAsync_Sources_ThrowsForNullSources() - { - using (var test = new PackageDownloaderTest()) - { - var exception = await Assert.ThrowsAsync( - () => PackageDownloader.GetDownloadResourceResultAsync( - sources: null, - packageIdentity: test.PackageIdentity, - downloadContext: test.Context, - globalPackagesFolder: "", - logger: NullLogger.Instance, - token: CancellationToken.None)); - - Assert.Equal("sources", exception.ParamName); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_Sources_ThrowsForNullPackageIdentity() - { - using (var test = new PackageDownloaderTest()) - { - var exception = await Assert.ThrowsAsync( - () => PackageDownloader.GetDownloadResourceResultAsync( - Enumerable.Empty(), - packageIdentity: null, - downloadContext: test.Context, - globalPackagesFolder: "", - logger: NullLogger.Instance, - token: CancellationToken.None)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_Sources_ThrowsForNullDownloadContext() - { - using (var test = new PackageDownloaderTest()) - { - var exception = await Assert.ThrowsAsync( - () => PackageDownloader.GetDownloadResourceResultAsync( - Enumerable.Empty(), - test.PackageIdentity, - downloadContext: null, - globalPackagesFolder: "", - logger: NullLogger.Instance, - token: CancellationToken.None)); - - Assert.Equal("downloadContext", exception.ParamName); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_Sources_ThrowsForNullLogger() - { - using (var test = new PackageDownloaderTest()) - { - var exception = await Assert.ThrowsAsync( - () => PackageDownloader.GetDownloadResourceResultAsync( - Enumerable.Empty(), - test.PackageIdentity, - test.Context, - globalPackagesFolder: "", - logger: null, - token: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_Sources_ThrowsIfCancelled() - { - using (var test = new PackageDownloaderTest()) - { - await Assert.ThrowsAsync( - () => PackageDownloader.GetDownloadResourceResultAsync( - Enumerable.Empty(), - test.PackageIdentity, - test.Context, - globalPackagesFolder: "", - logger: NullLogger.Instance, - token: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_Source_ThrowsForNullSourceRepository() - { - using (var test = new PackageDownloaderTest()) - { - var exception = await Assert.ThrowsAsync( - () => PackageDownloader.GetDownloadResourceResultAsync( - sourceRepository: null, - packageIdentity: test.PackageIdentity, - downloadContext: test.Context, - globalPackagesFolder: "", - logger: NullLogger.Instance, - token: CancellationToken.None)); - - Assert.Equal("sourceRepository", exception.ParamName); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_Source_ThrowsForNullPackageIdentity() - { - using (var test = new PackageDownloaderTest()) - { - var exception = await Assert.ThrowsAsync( - () => PackageDownloader.GetDownloadResourceResultAsync( - test.SourceRepository, - packageIdentity: null, - downloadContext: test.Context, - globalPackagesFolder: "", - logger: NullLogger.Instance, - token: CancellationToken.None)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_Source_ThrowsForNullDownloadContext() - { - using (var test = new PackageDownloaderTest()) - { - var exception = await Assert.ThrowsAsync( - () => PackageDownloader.GetDownloadResourceResultAsync( - test.SourceRepository, - test.PackageIdentity, - downloadContext: null, - globalPackagesFolder: "", - logger: NullLogger.Instance, - token: CancellationToken.None)); - - Assert.Equal("downloadContext", exception.ParamName); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_Source_ThrowsForNullLogger() - { - using (var test = new PackageDownloaderTest()) - { - var exception = await Assert.ThrowsAsync( - () => PackageDownloader.GetDownloadResourceResultAsync( - test.SourceRepository, - test.PackageIdentity, - test.Context, - globalPackagesFolder: "", - logger: null, - token: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_Source_ThrowsIfCancelled() - { - using (var test = new PackageDownloaderTest()) - { - var resourceProvider = new Mock(); - - resourceProvider.SetupGet(x => x.Name) - .Returns(nameof(DownloadResource) + "Provider"); - resourceProvider.SetupGet(x => x.ResourceType) - .Returns(typeof(DownloadResource)); - - resourceProvider.Setup(x => x.TryCreate( - It.IsNotNull(), - It.IsAny())) - .ReturnsAsync(new Tuple(true, Mock.Of())); - - var sourceRepository = new SourceRepository( - test.SourceRepository.PackageSource, - new[] { resourceProvider.Object }); - - await Assert.ThrowsAsync( - () => PackageDownloader.GetDownloadResourceResultAsync( - sourceRepository, - test.PackageIdentity, - test.Context, - globalPackagesFolder: "", - logger: NullLogger.Instance, - token: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_Source_ThrowsIfNoDownloadResource() - { - using (var test = new PackageDownloaderTest()) - { - await Assert.ThrowsAsync( - () => PackageDownloader.GetDownloadResourceResultAsync( - test.SourceRepository, - test.PackageIdentity, - test.Context, - globalPackagesFolder: "", - logger: NullLogger.Instance, - token: CancellationToken.None)); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_V2_ThrowIfPackageDoesNotExist() + public async Task TestDownloadThrows_PackageDoesNotExist_InV2() { // Arrange var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV2OnlySourceRepositoryProvider(); @@ -247,8 +39,7 @@ public async Task GetDownloadResourceResultAsync_V2_ThrowIfPackageDoesNotExist() using (var cacheContext = new SourceCacheContext()) using (var packagesDirectory = TestDirectory.Create()) { - await PackageDownloader.GetDownloadResourceResultAsync( - v2sourceRepository, + await PackageDownloader.GetDownloadResourceResultAsync(v2sourceRepository, packageIdentity, new PackageDownloadContext(cacheContext), packagesDirectory, @@ -265,8 +56,11 @@ await PackageDownloader.GetDownloadResourceResultAsync( Assert.NotNull(exception); } + /// + /// Verifies that download throws when package does not exist in V3 + /// [Fact] - public async Task GetDownloadResourceResultAsync_V3_ThrowIfPackageDoesNotExist() + public async Task TestDownloadThrows_PackageDoesNotExist_InV3() { // Arrange var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider(); @@ -281,8 +75,7 @@ public async Task GetDownloadResourceResultAsync_V3_ThrowIfPackageDoesNotExist() using (var cacheContext = new SourceCacheContext()) using (var packagesDirectory = TestDirectory.Create()) { - await PackageDownloader.GetDownloadResourceResultAsync( - v3sourceRepository, + await PackageDownloader.GetDownloadResourceResultAsync(v3sourceRepository, packageIdentity, new PackageDownloadContext(cacheContext), packagesDirectory, @@ -300,7 +93,7 @@ await PackageDownloader.GetDownloadResourceResultAsync( } [Fact] - public async Task GetDownloadResourceResultAsync_V2_DownloadsPackage() + public async Task TestDownloadPackage_InV2() { // Arrange var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV2OnlySourceRepositoryProvider(); @@ -310,8 +103,7 @@ public async Task GetDownloadResourceResultAsync_V2_DownloadsPackage() // Act using (var cacheContext = new SourceCacheContext()) using (var packagesDirectory = TestDirectory.Create()) - using (var downloadResult = await PackageDownloader.GetDownloadResourceResultAsync( - v2sourceRepository, + using (var downloadResult = await PackageDownloader.GetDownloadResourceResultAsync(v2sourceRepository, packageIdentity, new PackageDownloadContext(cacheContext), packagesDirectory, @@ -328,7 +120,7 @@ public async Task GetDownloadResourceResultAsync_V2_DownloadsPackage() } [Fact] - public async Task GetDownloadResourceResultAsync_V3_DownloadsPackage() + public async Task TestDownloadPackage_InV3() { // Arrange var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider(); @@ -338,8 +130,7 @@ public async Task GetDownloadResourceResultAsync_V3_DownloadsPackage() // Act using (var cacheContext = new SourceCacheContext()) using (var packagesDirectory = TestDirectory.Create()) - using (var downloadResult = await PackageDownloader.GetDownloadResourceResultAsync( - v3sourceRepository, + using (var downloadResult = await PackageDownloader.GetDownloadResourceResultAsync(v3sourceRepository, packageIdentity, new PackageDownloadContext(cacheContext), packagesDirectory, @@ -376,7 +167,7 @@ public async Task GetDownloadResourceResultAsync_WithDirectDownloadAndV3Source_S } [Fact] - public async Task GetDownloadResourceResultAsync_MultipleSources_DownloadsPackage() + public async Task TestDownloadPackage_MultipleSources() { // Arrange var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] @@ -391,8 +182,7 @@ public async Task GetDownloadResourceResultAsync_MultipleSources_DownloadsPackag // Act using (var cacheContext = new SourceCacheContext()) using (var packagesDirectory = TestDirectory.Create()) - using (var downloadResult = await PackageDownloader.GetDownloadResourceResultAsync( - sourceRepositoryProvider.GetRepositories(), + using (var downloadResult = await PackageDownloader.GetDownloadResourceResultAsync(sourceRepositoryProvider.GetRepositories(), packageIdentity, new PackageDownloadContext(cacheContext), packagesDirectory, @@ -407,7 +197,7 @@ public async Task GetDownloadResourceResultAsync_MultipleSources_DownloadsPackag } [Fact] - public async Task GetDownloadResourceResultAsync_MultipleSources_PackageNotFound() + public async Task TestDownloadPackage_MultipleSources_NotFound() { // Arrange var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] @@ -421,19 +211,17 @@ public async Task GetDownloadResourceResultAsync_MultipleSources_PackageNotFound using (var packagesDirectory = TestDirectory.Create()) using (var cacheContext = new SourceCacheContext()) { - await Assert.ThrowsAsync( - async () => await PackageDownloader.GetDownloadResourceResultAsync( - sourceRepositoryProvider.GetRepositories(), - packageIdentity, - new PackageDownloadContext(cacheContext), - packagesDirectory, - NullLogger.Instance, - CancellationToken.None)); + await Assert.ThrowsAsync(async () => await PackageDownloader.GetDownloadResourceResultAsync(sourceRepositoryProvider.GetRepositories(), + packageIdentity, + new PackageDownloadContext(cacheContext), + packagesDirectory, + NullLogger.Instance, + CancellationToken.None)); } } [Fact] - public async Task GetDownloadResourceResultAsync_MultipleSources_PackageDownloadedWhenFoundInMultipleSources() + public async Task TestDownloadPackage_MultipleSources_FoundOnMultiple() { // Arrange var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] @@ -465,56 +253,7 @@ public async Task GetDownloadResourceResultAsync_MultipleSources_PackageDownload } } - [Fact] - public async Task GetDownloadResourceResultAsync_SupportsDownloadResultWithoutPackageStream() - { - using (var test = new PackageDownloaderTest()) - using (var stream = new MemoryStream()) - using (var zipArchive = new ZipArchive(stream, ZipArchiveMode.Create)) - using (var packageReader = new PackageArchiveReader(zipArchive)) - { - var resourceProvider = new Mock(); - var resource = new Mock(); - var expectedResult = new DownloadResourceResult( - packageReader, - test.SourceRepository.PackageSource.Source); - - resource.Setup(x => x.GetDownloadResourceResultAsync( - It.IsNotNull(), - It.IsNotNull(), - It.IsAny(), - It.IsNotNull(), - It.IsAny())) - .ReturnsAsync(expectedResult); - - resourceProvider.SetupGet(x => x.Name) - .Returns(nameof(DownloadResource) + "Provider"); - resourceProvider.SetupGet(x => x.ResourceType) - .Returns(typeof(DownloadResource)); - resourceProvider.Setup(x => x.TryCreate( - It.IsNotNull(), - It.IsAny())) - .ReturnsAsync(new Tuple(true, resource.Object)); - - var sourceRepository = new SourceRepository( - test.SourceRepository.PackageSource, - new[] { resourceProvider.Object }); - - var actualResult = await PackageDownloader.GetDownloadResourceResultAsync( - sourceRepository, - test.PackageIdentity, - test.Context, - globalPackagesFolder: "", - logger: NullLogger.Instance, - token: CancellationToken.None); - - Assert.Equal(DownloadResourceResultStatus.AvailableWithoutStream, actualResult.Status); - Assert.Same(expectedResult, actualResult); - } - } - - private static async Task VerifyDirectDownloadSkipsGlobalPackagesFolder( - SourceRepositoryProvider sourceRepositoryProvider) + private static async Task VerifyDirectDownloadSkipsGlobalPackagesFolder(SourceRepositoryProvider sourceRepositoryProvider) { // Arrange var sourceRepository = sourceRepositoryProvider.GetRepositories().First(); @@ -555,30 +294,5 @@ private static async Task VerifyDirectDownloadSkipsGlobalPackagesFolder( Assert.Null(globalPackage); } } - - private sealed class PackageDownloaderTest : IDisposable - { - private readonly SourceCacheContext _sourceCacheContext; - - internal PackageDownloadContext Context { get; } - internal PackageIdentity PackageIdentity { get; } - internal SourceRepository SourceRepository { get; } - - internal PackageDownloaderTest() - { - _sourceCacheContext = new SourceCacheContext(); - Context = new PackageDownloadContext(_sourceCacheContext); - PackageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); - SourceRepository = new SourceRepository( - new PackageSource("https://unit/test"), - Enumerable.Empty()); - } - - public void Dispose() - { - _sourceCacheContext.Dispose(); - GC.SuppressFinalize(this); - } - } } -} \ No newline at end of file +} diff --git a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/ProjectManagement/FolderNuGetProjectTests.cs b/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/ProjectManagement/FolderNuGetProjectTests.cs index aa83da07219..75333812070 100644 --- a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/ProjectManagement/FolderNuGetProjectTests.cs +++ b/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/ProjectManagement/FolderNuGetProjectTests.cs @@ -1,104 +1,37 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.IO; using System.IO.Compression; using System.Linq; using System.Threading; using System.Threading.Tasks; -using Moq; using NuGet.Configuration; using NuGet.Frameworks; using NuGet.Packaging; using NuGet.Packaging.Core; +using NuGet.ProjectManagement; using NuGet.Protocol.Core.Types; using NuGet.Test.Utility; using NuGet.Versioning; using Test.Utility; using Xunit; -namespace NuGet.ProjectManagement.Test +namespace ProjectManagement.Test { public class FolderNuGetProjectTests { [Fact] - public void Constructor_String_ThrowsForNullRoot() - { - var exception = Assert.Throws(() => new FolderNuGetProject(root: null)); - - Assert.Equal("root", exception.ParamName); - } - - [Fact] - public void Constructor_String_InitializesRootProperty() - { - var project = new FolderNuGetProject(root: "a"); - - Assert.Equal("a", project.Root); - } - - [Fact] - public void Constructor_StringPackagePathResolver_ThrowsForNullRoot() - { - var exception = Assert.Throws( - () => new FolderNuGetProject( - root: null, - packagePathResolver: new PackagePathResolver(rootDirectory: "a"))); - - Assert.Equal("root", exception.ParamName); - } - - [Fact] - public void Constructor_StringPackagePathResolver_ThrowsForNullPackagePathResolver() - { - var exception = Assert.Throws( - () => new FolderNuGetProject(root: "a", packagePathResolver: null)); - - Assert.Equal("packagePathResolver", exception.ParamName); - } - - [Fact] - public void Constructor_StringPackagePathResolver_InitializesRootProperty() - { - var project = new FolderNuGetProject( - root: "a", - packagePathResolver: new PackagePathResolver(rootDirectory: "a")); - - Assert.Equal("a", project.Root); - } - - [Fact] - public async Task GetInstalledPackagesAsync_DoesNotThrowIfCancelled() - { - var project = new FolderNuGetProject(root: "a"); - - await project.GetInstalledPackagesAsync(new CancellationToken(canceled: true)); - } - - [Fact] - public async Task GetInstalledPackagesAsync_ReturnsEmptyEnumerable() - { - var project = new FolderNuGetProject(root: "a"); - - var packages = await project.GetInstalledPackagesAsync(CancellationToken.None); - - Assert.Empty(packages); - } - - [Fact] - public async Task InstallPackageAsync_InstallsPackage() + public async Task TestFolderNuGetProjectInstall() { // Arrange + var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0")); using (var randomTestSourcePath = TestDirectory.Create()) using (var randomTestDestinationPath = TestDirectory.Create()) { - var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage( - randomTestSourcePath, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); + var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage(randomTestSourcePath, packageIdentity.Id, packageIdentity.Version.ToNormalizedString()); var folderNuGetProject = new FolderNuGetProject(randomTestDestinationPath); var packagePathResolver = new PackagePathResolver(randomTestDestinationPath); var packageInstallPath = packagePathResolver.GetInstallPath(packageIdentity); @@ -123,7 +56,7 @@ public async Task InstallPackageAsync_InstallsPackage() } [Fact] - public void TryGetMetadata_GetsProjectMetadata() + public void TestFolderNuGetProjectMetadata() { // Arrange using (var randomTestFolder = TestDirectory.Create()) @@ -142,41 +75,14 @@ public void TryGetMetadata_GetsProjectMetadata() } [Fact] - public void GetInstalledManifestFilePath_ThrowsForNullPackageIdentity() - { - using (var test = new FolderNuGetProjectTest()) - { - var exception = Assert.Throws( - () => test.Project.GetInstalledManifestFilePath(packageIdentity: null)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public void GetInstalledPackageFilePath_ThrowsForNullPackageIdentity() - { - using (var test = new FolderNuGetProjectTest()) - { - var exception = Assert.Throws( - () => test.Project.GetInstalledPackageFilePath(packageIdentity: null)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public async Task GetInstalledPackageFilePath_ReturnsInstalledPackageFilePath() + public async Task TestFolderNuGetProjectGetInstalledPackageFilePath() { // Arrange using (var randomTestSourcePath = TestDirectory.Create()) using (var randomTestDestinationPath = TestDirectory.Create()) { var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0")); - var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage( - randomTestSourcePath, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); + var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage(randomTestSourcePath, packageIdentity.Id, packageIdentity.Version.ToNormalizedString()); var folderNuGetProject = new FolderNuGetProject(randomTestDestinationPath); var packagePathResolver = new PackagePathResolver(randomTestDestinationPath); var packageInstallPath = packagePathResolver.GetInstallPath(packageIdentity); @@ -199,8 +105,7 @@ public async Task GetInstalledPackageFilePath_ReturnsInstalledPackageFilePath() } // Main Act - var installedPackageFilePath = folderNuGetProject.GetInstalledPackageFilePath( - new PackageIdentity(packageIdentity.Id, + var installedPackageFilePath = folderNuGetProject.GetInstalledPackageFilePath(new PackageIdentity(packageIdentity.Id, new NuGetVersion(packageIdentity.Version + ".0"))); // Assert @@ -211,29 +116,14 @@ public async Task GetInstalledPackageFilePath_ReturnsInstalledPackageFilePath() } [Fact] - public void GetInstalledPath_ThrowsForNullPackageIdentity() - { - using (var test = new FolderNuGetProjectTest()) - { - var exception = Assert.Throws( - () => test.Project.GetInstalledPath(packageIdentity: null)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public async Task GetInstalledPath_ReturnsInstalledPath() + public async Task TestFolderNuGetProjectGetInstalledPackageDirectoryPath() { // Arrange using (var randomTestSourcePath = TestDirectory.Create()) using (var randomTestDestinationPath = TestDirectory.Create()) { var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0")); - var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage( - randomTestSourcePath, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); + var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage(randomTestSourcePath, packageIdentity.Id, packageIdentity.Version.ToNormalizedString()); var folderNuGetProject = new FolderNuGetProject(randomTestDestinationPath); var packagePathResolver = new PackagePathResolver(randomTestDestinationPath); var packageInstallPath = packagePathResolver.GetInstallPath(packageIdentity); @@ -256,10 +146,8 @@ public async Task GetInstalledPath_ReturnsInstalledPath() } // Main Act - var installedPath = folderNuGetProject.GetInstalledPath( - new PackageIdentity( - packageIdentity.Id, - new NuGetVersion(packageIdentity.Version + ".0"))); + var installedPath = folderNuGetProject.GetInstalledPath(new PackageIdentity(packageIdentity.Id, + new NuGetVersion(packageIdentity.Version + ".0"))); // Assert Assert.NotNull(installedPath); @@ -269,64 +157,14 @@ public async Task GetInstalledPath_ReturnsInstalledPath() } [Fact] - public void PackageExists_PackageIdentity_ThrowsForNullPackageIdentity() - { - var project = new FolderNuGetProject(root: "a"); - - var exception = Assert.Throws(() => project.PackageExists(packageIdentity: null)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void PackageExists_PackageIdentity_ReturnsFalseIfPackageDoesNotExist(bool useSideBySidePaths) - { - using (var test = new FolderNuGetProjectTest(useSideBySidePaths)) - { - Assert.False(test.Project.PackageExists(test.PackageIdentity)); - } - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public async Task PackageExists_PackageIdentity_ReturnsTrueIfPackageExists(bool useSideBySidePaths) - { - using (var test = new FolderNuGetProjectTest(useSideBySidePaths)) - { - await test.InstallAsync(PackageSaveMode.Nupkg); - - Assert.True(test.Project.PackageExists(test.PackageIdentity)); - } - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void PackageExists_PackageIdentity_ReturnsTrueIfPackageDownloadMarkerFileExists(bool useSideBySidePaths) - { - using (var test = new FolderNuGetProjectTest(useSideBySidePaths)) - { - test.CreatePackageDownloadMarkerFile(); - - Assert.True(test.Project.PackageExists(test.PackageIdentity)); - } - } - - [Fact] - public async Task PackageExists_ReturnsTrueIfPackageExists() + public async Task TestFolderNuGetProjectPackageExists() { // Arrange using (var randomTestSourcePath = TestDirectory.Create()) using (var randomTestDestinationPath = TestDirectory.Create()) { var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0")); - var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage( - randomTestSourcePath, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); + var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage(randomTestSourcePath, packageIdentity.Id, packageIdentity.Version.ToNormalizedString()); var folderNuGetProject = new FolderNuGetProject(randomTestDestinationPath); var packagePathResolver = new PackagePathResolver(randomTestDestinationPath); var packageInstallPath = packagePathResolver.GetInstallPath(packageIdentity); @@ -349,8 +187,7 @@ public async Task PackageExists_ReturnsTrueIfPackageExists() } // Main Act - var packageExists = folderNuGetProject.PackageExists( - new PackageIdentity(packageIdentity.Id, + var packageExists = folderNuGetProject.PackageExists(new PackageIdentity(packageIdentity.Id, new NuGetVersion(packageIdentity.Version + ".0"))); // Assert @@ -359,254 +196,14 @@ public async Task PackageExists_ReturnsTrueIfPackageExists() } [Fact] - public void PackageExists_PackageIdentityPackageSaveMode_ThrowsForNullPackageIdentity() - { - var project = new FolderNuGetProject(root: "a"); - - var exception = Assert.Throws( - () => project.PackageExists(packageIdentity: null, packageSaveMode: PackageSaveMode.Nupkg)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void PackageExists_PackageIdentityPackageSaveMode_ReturnsFalseIfPackageDoesNotExist( - bool useSideBySidePaths) - { - using (var test = new FolderNuGetProjectTest(useSideBySidePaths)) - { - Assert.False(test.Project.PackageExists(test.PackageIdentity, PackageSaveMode.Nupkg)); - } - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public async Task PackageExists_PackageIdentityPackageSaveMode_ReturnsTrueIfPackageExists(bool useSideBySidePaths) - { - using (var test = new FolderNuGetProjectTest(useSideBySidePaths)) - { - await test.InstallAsync(PackageSaveMode.Nupkg); - - Assert.True(test.Project.PackageExists(test.PackageIdentity, PackageSaveMode.Nupkg)); - } - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void PackageExists_PackageIdentityPackageSaveMode_ReturnsTrueIfPackageDownloadMarkerFileExists( - bool useSideBySidePaths) - { - using (var test = new FolderNuGetProjectTest(useSideBySidePaths)) - { - test.CreatePackageDownloadMarkerFile(); - - Assert.True(test.Project.PackageExists(test.PackageIdentity, PackageSaveMode.Nupkg)); - } - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void PackageExists_PackageIdentityPackageSaveMode_ReturnsFalseIfNuspecDoesNotExist( - bool useSideBySidePaths) - { - using (var test = new FolderNuGetProjectTest(useSideBySidePaths)) - { - Assert.False(test.Project.PackageExists(test.PackageIdentity, PackageSaveMode.Nuspec)); - } - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public async Task PackageExists_PackageIdentityPackageSaveMode_ReturnsTrueIfNuspecExists( - bool useSideBySidePaths) - { - using (var test = new FolderNuGetProjectTest(useSideBySidePaths)) - { - await test.InstallAsync(PackageSaveMode.Nuspec); - - Assert.True(test.Project.PackageExists(test.PackageIdentity, PackageSaveMode.Nuspec)); - } - } - - [Theory] - [InlineData(PackageSaveMode.None)] - [InlineData(PackageSaveMode.Nuspec)] - [InlineData(PackageSaveMode.Files)] - public async Task PackageExists_PackageIdentityPackageSaveMode_ReturnsFalseIfDefaultv2NotInstalled( - PackageSaveMode packageSaveMode) - { - using (var test = new FolderNuGetProjectTest()) - { - await test.InstallAsync(packageSaveMode); - - Assert.False(test.Project.PackageExists(test.PackageIdentity, PackageSaveMode.Defaultv2)); - } - } - - [Theory] - [InlineData(PackageSaveMode.Nupkg)] - [InlineData(PackageSaveMode.Defaultv2)] - public async Task PackageExists_PackageIdentityPackageSaveMode_ReturnsTrueIfDefaultv2Installed( - PackageSaveMode packageSaveMode) - { - using (var test = new FolderNuGetProjectTest()) - { - await test.InstallAsync(PackageSaveMode.Defaultv2); - - Assert.True(test.Project.PackageExists(test.PackageIdentity, PackageSaveMode.Defaultv2)); - } - } - - [Theory] - [InlineData(PackageSaveMode.None)] - [InlineData(PackageSaveMode.Nuspec)] - [InlineData(PackageSaveMode.Nupkg)] - [InlineData(PackageSaveMode.Files)] - public async Task PackageExists_PackageIdentityPackageSaveMode_ReturnsFalseIfDefaultv3NotInstalled( - PackageSaveMode packageSaveMode) - { - using (var test = new FolderNuGetProjectTest()) - { - await test.InstallAsync(packageSaveMode); - - Assert.False(test.Project.PackageExists(test.PackageIdentity, PackageSaveMode.Defaultv3)); - } - } - - [Theory] - [InlineData(PackageSaveMode.Nupkg | PackageSaveMode.Nuspec)] - [InlineData(PackageSaveMode.Defaultv3)] - public async Task PackageExists_PackageIdentityPackageSaveMode_ReturnsTrueIfDefaultv3Installed( - PackageSaveMode packageSaveMode) - { - using (var test = new FolderNuGetProjectTest()) - { - await test.InstallAsync(packageSaveMode); - - Assert.True(test.Project.PackageExists(test.PackageIdentity, PackageSaveMode.Defaultv3)); - } - } - - [Fact] - public void ManifestExists_ThrowsForNullPackageIdentity() - { - using (var test = new FolderNuGetProjectTest()) - { - var exception = Assert.Throws( - () => test.Project.ManifestExists(packageIdentity: null)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public void ManifestExists_ReturnsFalseIfNuspecNotInstalled() - { - using (var test = new FolderNuGetProjectTest()) - { - var exists = test.Project.ManifestExists(test.PackageIdentity); - - Assert.False(exists); - } - } - - [Fact] - public async Task ManifestExists_ReturnsTrueIfNuspecInstalled() - { - using (var test = new FolderNuGetProjectTest()) - { - await test.InstallAsync(PackageSaveMode.Nuspec); - - var exists = test.Project.ManifestExists(test.PackageIdentity); - - Assert.True(exists); - } - } - - [Fact] - public void PackageAndManifestExists_ThrowsForNullPackageIdentity() - { - using (var test = new FolderNuGetProjectTest()) - { - var exception = Assert.Throws( - () => test.Project.PackageAndManifestExists(packageIdentity: null)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public void PackageAndManifestExists_ReturnsFalseIfNuspecNotInstalled() - { - using (var test = new FolderNuGetProjectTest()) - { - var exists = test.Project.PackageAndManifestExists(test.PackageIdentity); - - Assert.False(exists); - } - } - - [Fact] - public async Task PackageAndManifestExist_ReturnsTrueIfNuspecInstalled() - { - using (var test = new FolderNuGetProjectTest()) - { - await test.InstallAsync(PackageSaveMode.Nupkg | PackageSaveMode.Nuspec); - - var exists = test.Project.PackageAndManifestExists(test.PackageIdentity); - - Assert.True(exists); - } - } - - [Fact] - public async Task DeletePackage_ThrowsForNullPackageIdentity() - { - using (var test = new FolderNuGetProjectTest()) - { - var exception = await Assert.ThrowsAsync( - () => test.Project.DeletePackage( - packageIdentity: null, - nuGetProjectContext: Mock.Of(), - token: CancellationToken.None)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public async Task DeletePackage_ThrowsForNullNuGetProjectContext() - { - using (var test = new FolderNuGetProjectTest()) - { - var exception = await Assert.ThrowsAsync( - () => test.Project.DeletePackage( - test.PackageIdentity, - nuGetProjectContext: null, - token: CancellationToken.None)); - - Assert.Equal("nuGetProjectContext", exception.ParamName); - } - } - - [Fact] - public async Task DeletePackage_DeletesPackage() + public async Task TestFolderNuGetProjectDeletePackage() { // Arrange using (var randomTestSourcePath = TestDirectory.Create()) using (var randomTestDestinationPath = TestDirectory.Create()) { var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0")); - var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyContentPackage( - randomTestSourcePath, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); + var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyContentPackage(randomTestSourcePath, packageIdentity.Id, packageIdentity.Version.ToNormalizedString()); var folderNuGetProject = new FolderNuGetProject(randomTestDestinationPath); var packagePathResolver = new PackagePathResolver(randomTestDestinationPath); var packageInstallPath = packagePathResolver.GetInstallPath(packageIdentity); @@ -646,7 +243,7 @@ public async Task DeletePackage_DeletesPackage() } [Fact] - public async Task InstallPackageAsync_WithSourceControlEnabled() + public async Task TestFolderNuGetProjectInstall_SourceControlEnabled() { // Arrange var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0")); @@ -701,7 +298,7 @@ await folderNuGetProject.InstallPackageAsync( } [Fact] - public async Task InstallPackageAsync_WithSourceControlDisabled() + public async Task TestFolderNuGetProjectInstall_SourceControlDisabled() { // Arrange var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0")); @@ -755,162 +352,9 @@ await folderNuGetProject.InstallPackageAsync( } } - [Fact] - public async Task UninstallPackageAsync_DoesNothing() - { - var project = new FolderNuGetProject(root: "a"); - - var wasUninstalled = await project.UninstallPackageAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - new Mock(MockBehavior.Strict).Object, - CancellationToken.None); - - Assert.True(wasUninstalled); - } - - [Fact] - public void GetPackageDownloadMarkerFilePath_ThrowsForNullPackageIdentity() - { - using (var test = new FolderNuGetProjectTest()) - { - var exception = Assert.Throws( - () => test.Project.GetPackageDownloadMarkerFilePath(packageIdentity: null)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public void GetPackageDownloadMarkerFilePath_ReturnsNullIfFileDoesNotExist() - { - using (var test = new FolderNuGetProjectTest()) - { - var filePath = test.Project.GetPackageDownloadMarkerFilePath(test.PackageIdentity); - - Assert.Null(filePath); - } - } - - [Fact] - public void GetPackageDownloadMarkerFilePath_ReturnsFilePathIfFileExists() - { - using (var test = new FolderNuGetProjectTest()) - { - test.CreatePackageDownloadMarkerFile(); - - var filePath = test.Project.GetPackageDownloadMarkerFilePath(test.PackageIdentity); - - Assert.NotNull(filePath); - Assert.True(File.Exists(filePath)); - } - } - - [Fact] - public async Task CopySatelliteFilesAsync_ThrowsForNullPackageIdentity() - { - using (var test = new FolderNuGetProjectTest()) - { - var exception = await Assert.ThrowsAsync( - () => test.Project.CopySatelliteFilesAsync( - packageIdentity: null, - nuGetProjectContext: Mock.Of(), - token: CancellationToken.None)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public async Task CopySatelliteFilesAsync_ThrowsForNullNuGetProjectContext() - { - using (var test = new FolderNuGetProjectTest()) - { - var exception = await Assert.ThrowsAsync( - () => test.Project.CopySatelliteFilesAsync( - test.PackageIdentity, - nuGetProjectContext: null, - token: CancellationToken.None)); - - Assert.Equal("nuGetProjectContext", exception.ParamName); - } - } - - [Fact] - public async Task CopySatelliteFilesAsync_ThrowsIfCancelled() - { - using (var test = new FolderNuGetProjectTest()) - { - await Assert.ThrowsAsync( - () => test.Project.CopySatelliteFilesAsync( - test.PackageIdentity, - Mock.Of(), - new CancellationToken(canceled: true))); - } - } - private static DownloadResourceResult GetDownloadResourceResult(FileInfo fileInfo) { return new DownloadResourceResult(fileInfo.OpenRead()); } - - private sealed class FolderNuGetProjectTest : IDisposable - { - internal FileInfo Package { get; } - internal PackageIdentity PackageIdentity { get; } - internal FolderNuGetProject Project { get; } - internal DirectoryInfo ProjectDirectory { get; } - internal PackagePathResolver Resolver { get; } - internal TestDirectory TestDirectory { get; } - - internal FolderNuGetProjectTest(bool useSideBySidePaths = true) - { - PackageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); - TestDirectory = TestDirectory.Create(); - ProjectDirectory = Directory.CreateDirectory(Path.Combine(TestDirectory.Path, "project")); - Resolver = new PackagePathResolver(ProjectDirectory.FullName, useSideBySidePaths); - Project = new FolderNuGetProject(ProjectDirectory.FullName, Resolver); - - var sourcePackageDirectoryPath = Path.Combine(TestDirectory.Path, "source"); - - Directory.CreateDirectory(sourcePackageDirectoryPath); - - Package = TestPackagesGroupedByFolder.GetLegacyTestPackage( - sourcePackageDirectoryPath, - PackageIdentity.Id, - PackageIdentity.Version.ToNormalizedString()); - } - - public void Dispose() - { - TestDirectory.Dispose(); - GC.SuppressFinalize(this); - } - - internal void CreatePackageDownloadMarkerFile() - { - var packageDirectory = Resolver.GetInstallPath(PackageIdentity); - var markerFileName = Resolver.GetPackageDownloadMarkerFileName(PackageIdentity); - - Directory.CreateDirectory(packageDirectory); - - File.WriteAllText(Path.Combine(packageDirectory, markerFileName), string.Empty); - } - - internal async Task InstallAsync(PackageSaveMode packageSaveMode) - { - using (var result = GetDownloadResourceResult(Package)) - { - var projectContext = new TestNuGetProjectContext(); - - projectContext.PackageExtractionContext.PackageSaveMode = packageSaveMode; - - await Project.InstallPackageAsync( - PackageIdentity, - result, - projectContext, - CancellationToken.None); - } - } - } } -} \ No newline at end of file +} diff --git a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/Utility/FileSystemUtilityTests.cs b/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/Utility/FileSystemUtilityTests.cs deleted file mode 100644 index 24c2d0a9b22..00000000000 --- a/test/NuGet.Core.Tests/NuGet.PackageManagement.Test/Utility/FileSystemUtilityTests.cs +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Text; -using System.Threading.Tasks; -using NuGet.ProjectManagement; -using NuGet.Test.Utility; -using Xunit; - -namespace NuGet.PackageManagement.Test -{ - public class FileSystemUtilityTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void ContentEquals_ThrowsForNullOrEmptyPath(string path) - { - var exception = Assert.Throws( - () => FileSystemUtility.ContentEquals( - path: null, - streamFactory: () => Stream.Null)); - - Assert.Equal("path", exception.ParamName); - } - - [Fact] - public void ContentEquals_ThrowsForNullStreamTaskFactory() - { - var exception = Assert.Throws( - () => FileSystemUtility.ContentEquals( - path: "a", - streamFactory: null)); - - Assert.Equal("streamFactory", exception.ParamName); - } - - [Fact] - public void ContentEquals_ReturnsFalseIfNotEqual() - { - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("a"))) - using (var testDirectory = TestDirectory.Create()) - { - var filePath = Path.Combine(testDirectory.Path, "file"); - - File.WriteAllText(filePath, "b"); - - var areEqual = FileSystemUtility.ContentEquals(filePath, () => stream); - - Assert.False(areEqual); - } - } - - [Fact] - public void ContentEquals_ReturnsTrueIfEqual() - { - var content = "a"; - - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content))) - using (var testDirectory = TestDirectory.Create()) - { - var filePath = Path.Combine(testDirectory.Path, "file"); - - File.WriteAllText(filePath, content); - - var areEqual = FileSystemUtility.ContentEquals(filePath, () => stream); - - Assert.True(areEqual); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task ContentEqualsAsync_ThrowsForNullOrEmptyPath(string path) - { - var exception = await Assert.ThrowsAsync( - () => FileSystemUtility.ContentEqualsAsync( - path: null, - streamTaskFactory: () => Task.FromResult(Stream.Null))); - - Assert.Equal("path", exception.ParamName); - } - - [Fact] - public async Task ContentEqualsAsync_ThrowsForNullStreamTaskFactory() - { - var exception = await Assert.ThrowsAsync( - () => FileSystemUtility.ContentEqualsAsync( - path: "a", - streamTaskFactory: null)); - - Assert.Equal("streamTaskFactory", exception.ParamName); - } - - [Fact] - public async Task ContentEqualsAsync_ReturnsFalseIfNotEqual() - { - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("a"))) - using (var testDirectory = TestDirectory.Create()) - { - var filePath = Path.Combine(testDirectory.Path, "file"); - - File.WriteAllText(filePath, "b"); - - var areEqual = await FileSystemUtility.ContentEqualsAsync( - filePath, - () => Task.FromResult(stream)); - - Assert.False(areEqual); - } - } - - [Fact] - public async Task ContentEqualsAsync_ReturnsTrueIfEqual() - { - var content = "a"; - - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content))) - using (var testDirectory = TestDirectory.Create()) - { - var filePath = Path.Combine(testDirectory.Path, "file"); - - File.WriteAllText(filePath, content); - - var areEqual = await FileSystemUtility.ContentEqualsAsync( - filePath, - () => Task.FromResult(stream)); - - Assert.True(areEqual); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Packaging.Test/LocalPackageArchiveDownloaderTests.cs b/test/NuGet.Core.Tests/NuGet.Packaging.Test/LocalPackageArchiveDownloaderTests.cs deleted file mode 100644 index 2c959db5815..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Packaging.Test/LocalPackageArchiveDownloaderTests.cs +++ /dev/null @@ -1,311 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using System.Xml.Linq; -using NuGet.Common; -using NuGet.Packaging.Core; -using NuGet.Test.Utility; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Packaging.Test -{ - public class LocalPackageArchiveDownloaderTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageFilePath(string packageFilePath) - { - var exception = Assert.Throws( - () => new LocalPackageArchiveDownloader( - packageFilePath, - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - NullLogger.Instance)); - - Assert.Equal("packageFilePath", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullPackageIdentity() - { - var exception = Assert.Throws( - () => new LocalPackageArchiveDownloader( - packageFilePath: "a", - packageIdentity: null, - logger: NullLogger.Instance)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullLogger() - { - var exception = Assert.Throws( - () => new LocalPackageArchiveDownloader( - packageFilePath: "a", - packageIdentity: new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - logger: null)); - - Assert.Equal("logger", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - using (var test = LocalPackageArchiveDownloaderTest.Create()) - { - Assert.IsType(test.Downloader.ContentReader); - Assert.IsType(test.Downloader.CoreReader); - } - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var test = LocalPackageArchiveDownloaderTest.Create()) - { - test.Downloader.Dispose(); - test.Downloader.Dispose(); - } - } - - [Fact] - public void ContentReader_ThrowsIfDisposed() - { - using (var test = LocalPackageArchiveDownloaderTest.Create()) - { - test.Downloader.Dispose(); - - var exception = Assert.Throws(() => test.Downloader.ContentReader); - - Assert.Equal(nameof(LocalPackageArchiveDownloader), exception.ObjectName); - } - } - - [Fact] - public void CoreReader_ThrowsIfDisposed() - { - using (var test = LocalPackageArchiveDownloaderTest.Create()) - { - test.Downloader.Dispose(); - - var exception = Assert.Throws(() => test.Downloader.CoreReader); - - Assert.Equal(nameof(LocalPackageArchiveDownloader), exception.ObjectName); - } - } - - [Fact] - public async Task CopyNupkgFileToAsync_ThrowsIfDisposed() - { - using (var test = LocalPackageArchiveDownloaderTest.Create()) - { - test.Downloader.Dispose(); - - var exception = await Assert.ThrowsAsync( - () => test.Downloader.CopyNupkgFileToAsync( - destinationFilePath: "a", - cancellationToken: CancellationToken.None)); - - Assert.Equal(nameof(LocalPackageArchiveDownloader), exception.ObjectName); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task CopyNupkgFileToAsync_ThrowsForNullOrEmptyDestinationFilePath(string destinationFilePath) - { - using (var test = LocalPackageArchiveDownloaderTest.Create()) - { - var exception = await Assert.ThrowsAsync( - () => test.Downloader.CopyNupkgFileToAsync( - destinationFilePath, - CancellationToken.None)); - - Assert.Equal("destinationFilePath", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgFileToAsync_ThrowsIfCancelled() - { - using (var test = LocalPackageArchiveDownloaderTest.Create()) - { - await Assert.ThrowsAsync( - () => test.Downloader.CopyNupkgFileToAsync( - destinationFilePath: "a", - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task CopyNupkgFileToAsync_ReturnsPackageHash() - { - using (var test = LocalPackageArchiveDownloaderTest.Create()) - { - var destinationFilePath = Path.Combine(test.TestDirectory.Path, "copied.nupkg"); - - var wasCopied = await test.Downloader.CopyNupkgFileToAsync( - destinationFilePath, - CancellationToken.None); - - Assert.True(wasCopied); - - var sourceBytes = File.ReadAllBytes(test.SourcePackageFile.FullName); - var destinationBytes = File.ReadAllBytes(destinationFilePath); - - Assert.Equal(sourceBytes, destinationBytes); - } - } - - [Fact] - public async Task GetPackageHashAsync_ThrowsIfDisposed() - { - using (var test = LocalPackageArchiveDownloaderTest.Create()) - { - test.Downloader.Dispose(); - - var exception = await Assert.ThrowsAsync( - () => test.Downloader.GetPackageHashAsync( - hashAlgorithm: "SHA512", - cancellationToken: CancellationToken.None)); - - Assert.Equal(nameof(LocalPackageArchiveDownloader), exception.ObjectName); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetPackageHashAsync_ThrowsForNullOrEmptyHashAlgorithm(string hashAlgorithm) - { - using (var test = LocalPackageArchiveDownloaderTest.Create()) - { - var exception = await Assert.ThrowsAsync( - () => test.Downloader.GetPackageHashAsync( - hashAlgorithm, - CancellationToken.None)); - - Assert.Equal("hashAlgorithm", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageHashAsync_ThrowsIfCancelled() - { - using (var test = LocalPackageArchiveDownloaderTest.Create()) - { - await Assert.ThrowsAsync( - () => test.Downloader.GetPackageHashAsync( - hashAlgorithm: "a", - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetPackageHashAsync_ReturnsPackageHash() - { - using (var test = LocalPackageArchiveDownloaderTest.Create()) - { - var hashAlgorithm = "SHA512"; - var expectedPackageHash = CalculatePackageHash(test.SourcePackageFile.FullName, hashAlgorithm); - var actualPackageHash = await test.Downloader.GetPackageHashAsync( - hashAlgorithm, - CancellationToken.None); - - Assert.Equal(expectedPackageHash, actualPackageHash); - } - } - - private static string CalculatePackageHash(string filePath, string hashAlgorithm) - { - string expectedPackageHash; - - using (var stream = File.OpenRead(filePath)) - { - var bytes = new CryptoHashProvider(hashAlgorithm).CalculateHash(stream); - expectedPackageHash = Convert.ToBase64String(bytes); - } - - return expectedPackageHash; - } - - private sealed class LocalPackageArchiveDownloaderTest : IDisposable - { - internal LocalPackageArchiveDownloader Downloader { get; } - internal PackageIdentity PackageIdentity { get; } - internal FileInfo SourcePackageFile { get; } - internal TestDirectory TestDirectory { get; } - - private LocalPackageArchiveDownloaderTest( - TestDirectory testDirectory, - PackageIdentity packageIdentity, - FileInfo sourcePackageFile, - LocalPackageArchiveDownloader downloader) - { - TestDirectory = testDirectory; - PackageIdentity = packageIdentity; - SourcePackageFile = sourcePackageFile; - Downloader = downloader; - } - - public void Dispose() - { - Downloader.Dispose(); - TestDirectory.Dispose(); - - GC.SuppressFinalize(this); - } - - internal static LocalPackageArchiveDownloaderTest Create() - { - var testDirectory = TestDirectory.Create(); - var packageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); - var packageContext = new SimpleTestPackageContext() - { - Id = packageIdentity.Id, - Version = packageIdentity.Version.ToNormalizedString(), - Nuspec = XDocument.Parse($@" - - - {packageIdentity.Id} - {packageIdentity.Version.ToNormalizedString()} - - <frameworkAssemblies> - <frameworkAssembly assemblyName=""System.Runtime"" /> - </frameworkAssemblies> - <contentFiles> - <files include=""lib/net45/{packageIdentity.Id}.dll"" copyToOutput=""true"" flatten=""false"" /> - </contentFiles> - </metadata> - </package>") - }; - - packageContext.AddFile($"lib/net45/{packageIdentity.Id}.dll"); - - SimpleTestPackageUtility.CreatePackages(testDirectory.Path, packageContext); - - var sourcePackageFilePath = Path.Combine( - testDirectory.Path, - $"{packageIdentity.Id}.{packageIdentity.Version.ToNormalizedString()}.nupkg"); - - var downloader = new LocalPackageArchiveDownloader( - sourcePackageFilePath, - packageIdentity, - NullLogger.Instance); - - return new LocalPackageArchiveDownloaderTest( - testDirectory, - packageIdentity, - new FileInfo(sourcePackageFilePath), - downloader); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Packaging.Test/NugetPackageUtilTests.cs b/test/NuGet.Core.Tests/NuGet.Packaging.Test/NugetPackageUtilTests.cs index 92648cc4554..80b75462017 100644 --- a/test/NuGet.Core.Tests/NuGet.Packaging.Test/NugetPackageUtilTests.cs +++ b/test/NuGet.Core.Tests/NuGet.Packaging.Test/NugetPackageUtilTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -41,15 +41,11 @@ public async Task PackageExpander_ExpandsPackage() xmlDocFileSaveMode: XmlDocFileSaveMode.None); // Act - using (var packageDownloader = new LocalPackageArchiveDownloader( - package.File.FullName, - identity, - logger)) + using (var stream = package.File.OpenRead()) { - await PackageExtractor.InstallFromSourceAsync( - packageDownloader, - versionFolderPathContext, - token); + await PackageExtractor.InstallFromSourceAsync(async (d) => await stream.CopyToAsync(d), + versionFolderPathContext, + token); } // Assert @@ -70,6 +66,7 @@ public async Task PackageExpander_ExpandsPackage_WithNupkgCopy() // Arrange using (var package = TestPackagesCore.GetPackageWithNupkgCopy()) { + var version = new NuGetVersion(package.Version); var identity = new PackageIdentity(package.Id, version); @@ -86,15 +83,11 @@ public async Task PackageExpander_ExpandsPackage_WithNupkgCopy() xmlDocFileSaveMode: XmlDocFileSaveMode.None); // Act - using (var packageDownloader = new LocalPackageArchiveDownloader( - package.File.FullName, - identity, - logger)) + using (var stream = package.File.OpenRead()) { - await PackageExtractor.InstallFromSourceAsync( - packageDownloader, - versionFolderPathContext, - token); + await PackageExtractor.InstallFromSourceAsync(async (d) => await stream.CopyToAsync(d), + versionFolderPathContext, + token); } // Assert @@ -142,15 +135,11 @@ public async Task PackageExpander_ExpandsPackage_SkipsIfShaIsThere() Assert.True(File.Exists(shaPath)); // Act - using (var packageDownloader = new LocalPackageArchiveDownloader( - package.File.FullName, - identity, - logger)) + using (var stream = package.File.OpenRead()) { - await PackageExtractor.InstallFromSourceAsync( - packageDownloader, - versionFolderPathContext, - token); + await PackageExtractor.InstallFromSourceAsync(async (d) => await stream.CopyToAsync(d), + versionFolderPathContext, + token); } // Assert @@ -200,15 +189,11 @@ public async Task PackageExpander_CleansExtraFiles() AssertDirectoryExists(randomFolder); // Act - using (var packageDownloader = new LocalPackageArchiveDownloader( - package.File.FullName, - identity, - logger)) + using (var stream = package.File.OpenRead()) { - await PackageExtractor.InstallFromSourceAsync( - packageDownloader, - versionFolderPathContext, - token); + await PackageExtractor.InstallFromSourceAsync(async (d) => await stream.CopyToAsync(d), + versionFolderPathContext, + token); } // Assert @@ -231,6 +216,7 @@ public async Task PackageExpander_Recovers_WhenStreamIsCorrupt() // Arrange using (var package = TestPackagesCore.GetNearestReferenceFilteringPackage()) { + var version = new NuGetVersion(package.Version); var identity = new PackageIdentity(package.Id, version); @@ -250,14 +236,11 @@ public async Task PackageExpander_Recovers_WhenStreamIsCorrupt() Assert.False(Directory.Exists(packageDir), packageDir + " exist"); // Act - using (var packageDownloader = new ThrowingPackageArchiveDownloader( - package.File.FullName, - identity, - logger)) + using (var stream = package.File.OpenRead()) { await Assert.ThrowsAnyAsync<CorruptionException>(async () => await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + async (d) => await new CorruptStreamWrapper(stream).CopyToAsync(d), versionFolderPathContext, token)); } @@ -266,15 +249,11 @@ await PackageExtractor.InstallFromSourceAsync( Assert.NotEmpty(Directory.EnumerateFiles(packageDir)); - using (var packageDownloader = new LocalPackageArchiveDownloader( - package.File.FullName, - identity, - logger)) + using (var stream = package.File.OpenRead()) { - await PackageExtractor.InstallFromSourceAsync( - packageDownloader, - versionFolderPathContext, - token); + await PackageExtractor.InstallFromSourceAsync(async (d) => await stream.CopyToAsync(d), + versionFolderPathContext, + token); } // Assert @@ -292,6 +271,7 @@ public async Task PackageExpander_Recovers_WhenFileIsLocked() // Arrange using (var package = TestPackagesCore.GetNearestReferenceFilteringPackage()) { + var version = new NuGetVersion(package.Version); var identity = new PackageIdentity(package.Id, version); @@ -310,21 +290,17 @@ public async Task PackageExpander_Recovers_WhenFileIsLocked() var packageDir = pathResolver.GetInstallPath(package.Id, identity.Version); Assert.False(Directory.Exists(packageDir), packageDir + " exist"); - var filePathToLock = Path.Combine(packageDir, "lib", "net40", "two.dll"); + string filePathToLock = Path.Combine(packageDir, "lib", "net40", "two.dll"); // Act - using (var packageDownloader = new LocalPackageArchiveDownloader( - package.File.FullName, - identity, - logger)) + using (var stream = package.File.OpenRead()) { var cts = new CancellationTokenSource(DefaultTimeOut); - Func<CancellationToken, Task<bool>> action = (ct) => - { + Func<CancellationToken, Task<bool>> action = (ct) => { Assert.ThrowsAnyAsync<IOException>(async () => await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + str => stream.CopyToAsync(stream, bufferSize: 8192, cancellationToken: token), versionFolderPathContext, token)); @@ -338,15 +314,11 @@ await PackageExtractor.InstallFromSourceAsync( Assert.NotEmpty(Directory.EnumerateFiles(packageDir)); - using (var packageDownloader = new LocalPackageArchiveDownloader( - package.File.FullName, - identity, - logger)) + using (var stream = package.File.OpenRead()) { - await PackageExtractor.InstallFromSourceAsync( - packageDownloader, - versionFolderPathContext, - token); + await PackageExtractor.InstallFromSourceAsync(async (d) => await stream.CopyToAsync(d), + versionFolderPathContext, + token); } // Assert @@ -367,37 +339,34 @@ await PackageExtractor.InstallFromSourceAsync( public async Task Test_ExtractPackage() { // Arrange - var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("2.0.3")); + var package = new PackageIdentity("packageA", new NuGetVersion("2.0.3")); using (var packageFileInfo = TestPackagesCore.GetLegacyTestPackage()) using (var packagesDirectory = TestDirectory.Create()) { var pathResolver = new VersionFolderPathResolver(packagesDirectory); var versionFolderPathContext = new VersionFolderPathContext( - packageIdentity, + package, packagesDirectory, NullLogger.Instance, packageSaveMode: PackageSaveMode.Defaultv3, xmlDocFileSaveMode: XmlDocFileSaveMode.None); // Act - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFileInfo, - packageIdentity, - NullLogger.Instance)) + using (var packageFileStream = File.OpenRead(packageFileInfo)) { await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + stream => packageFileStream.CopyToAsync(stream), versionFolderPathContext, CancellationToken.None); } // Assert - var packageVersionDirectory = pathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version); + var packageVersionDirectory = pathResolver.GetInstallPath(package.Id, package.Version); AssertDirectoryExists(packageVersionDirectory); - AssertFileExists(packageVersionDirectory, pathResolver.GetPackageFileName(packageIdentity.Id, packageIdentity.Version)); - AssertFileExists(packageVersionDirectory, pathResolver.GetManifestFileName(packageIdentity.Id, packageIdentity.Version)); + AssertFileExists(packageVersionDirectory, pathResolver.GetPackageFileName(package.Id, package.Version)); + AssertFileExists(packageVersionDirectory, pathResolver.GetManifestFileName(package.Id, package.Version)); AssertFileExists(packageVersionDirectory, "packagea.2.0.3.nupkg.sha512"); AssertFileExists(packageVersionDirectory, "lib", "test.dll"); @@ -408,37 +377,34 @@ await PackageExtractor.InstallFromSourceAsync( public async Task Test_ExtractNuspecOnly() { // Arrange - var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("2.0.3")); + var package = new PackageIdentity("packageA", new NuGetVersion("2.0.3")); using (var packageFileInfo = TestPackagesCore.GetLegacyTestPackage()) using (var packagesDirectory = TestDirectory.Create()) { var pathResolver = new VersionFolderPathResolver(packagesDirectory); var versionFolderPathContext = new VersionFolderPathContext( - packageIdentity, + package, packagesDirectory, NullLogger.Instance, packageSaveMode: PackageSaveMode.Nuspec | PackageSaveMode.Nupkg, xmlDocFileSaveMode: XmlDocFileSaveMode.None); // Act - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFileInfo, - packageIdentity, - NullLogger.Instance)) + using (var packageFileStream = File.OpenRead(packageFileInfo)) { await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + stream => packageFileStream.CopyToAsync(stream), versionFolderPathContext, CancellationToken.None); } // Assert - var packageVersionDirectory = pathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version); + var packageVersionDirectory = pathResolver.GetInstallPath(package.Id, package.Version); AssertDirectoryExists(packageVersionDirectory); - AssertFileExists(packageVersionDirectory, pathResolver.GetPackageFileName(packageIdentity.Id, packageIdentity.Version)); - AssertFileExists(packageVersionDirectory, pathResolver.GetManifestFileName(packageIdentity.Id, packageIdentity.Version)); + AssertFileExists(packageVersionDirectory, pathResolver.GetPackageFileName(package.Id, package.Version)); + AssertFileExists(packageVersionDirectory, pathResolver.GetManifestFileName(package.Id, package.Version)); AssertFileExists(packageVersionDirectory, "packagea.2.0.3.nupkg.sha512"); Assert.False(File.Exists(Path.Combine(packageVersionDirectory, "lib", "test.dll"))); @@ -449,44 +415,41 @@ await PackageExtractor.InstallFromSourceAsync( public async Task Test_ExtractionIgnoresNupkgHashFile() { // Arrange - var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("2.0.3")); + var package = new PackageIdentity("packageA", new NuGetVersion("2.0.3")); using (var packagesDirectory = TestDirectory.Create()) { var pathResolver = new VersionFolderPathResolver(packagesDirectory); var packageFileInfo = await TestPackagesCore.GetPackageWithSHA512AtRoot( packagesDirectory, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); + package.Id, + package.Version.ToNormalizedString()); var versionFolderPathContext = new VersionFolderPathContext( - packageIdentity, + package, packagesDirectory, NullLogger.Instance, packageSaveMode: PackageSaveMode.Defaultv3, xmlDocFileSaveMode: XmlDocFileSaveMode.None); // Act - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFileInfo.FullName, - packageIdentity, - NullLogger.Instance)) + using (var packageFileStream = packageFileInfo.OpenRead()) { await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + stream => packageFileStream.CopyToAsync(stream), versionFolderPathContext, CancellationToken.None); } // Assert - var packageVersionDirectory = pathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version); + var packageVersionDirectory = pathResolver.GetInstallPath(package.Id, package.Version); AssertDirectoryExists(packageVersionDirectory); - AssertFileExists(packageVersionDirectory, pathResolver.GetPackageFilePath(packageIdentity.Id, packageIdentity.Version)); - AssertFileExists(packageVersionDirectory, pathResolver.GetManifestFileName(packageIdentity.Id, packageIdentity.Version)); + AssertFileExists(packageVersionDirectory, pathResolver.GetPackageFilePath(package.Id, package.Version)); + AssertFileExists(packageVersionDirectory, pathResolver.GetManifestFileName(package.Id, package.Version)); AssertFileExists(packageVersionDirectory, "lib", "net45", "A.dll"); - var hashPath = pathResolver.GetHashPath(packageIdentity.Id, packageIdentity.Version); + var hashPath = pathResolver.GetHashPath(package.Id, package.Version); var hashFileInfo = new FileInfo(hashPath); Assert.True(File.Exists(hashFileInfo.FullName)); Assert.NotEqual(0, hashFileInfo.Length); @@ -507,43 +470,40 @@ await PackageExtractor.InstallFromSourceAsync( public async Task Test_ExtractionIgnoresNupkgFile() { // Arrange - var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("2.0.3")); + var package = new PackageIdentity("packageA", new NuGetVersion("2.0.3")); using (var packagesDirectory = TestDirectory.Create()) { var pathResolver = new VersionFolderPathResolver(packagesDirectory); var packageFileInfo = await TestPackagesCore.GetPackageWithNupkgAtRoot( packagesDirectory, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); + package.Id, + package.Version.ToNormalizedString()); var versionFolderPathContext = new VersionFolderPathContext( - packageIdentity, + package, packagesDirectory, NullLogger.Instance, packageSaveMode: PackageSaveMode.Defaultv3, xmlDocFileSaveMode: XmlDocFileSaveMode.None); // Act - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFileInfo.FullName, - packageIdentity, - NullLogger.Instance)) + using (var packageFileStream = packageFileInfo.OpenRead()) { await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + stream => packageFileStream.CopyToAsync(stream), versionFolderPathContext, CancellationToken.None); } // Assert - var packageVersionDirectory = pathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version); + var packageVersionDirectory = pathResolver.GetInstallPath(package.Id, package.Version); AssertDirectoryExists(packageVersionDirectory); - AssertFileExists(packageVersionDirectory, pathResolver.GetPackageFilePath(packageIdentity.Id, packageIdentity.Version)); - AssertFileExists(packageVersionDirectory, pathResolver.GetManifestFileName(packageIdentity.Id, packageIdentity.Version)); + AssertFileExists(packageVersionDirectory, pathResolver.GetPackageFilePath(package.Id, package.Version)); + AssertFileExists(packageVersionDirectory, pathResolver.GetManifestFileName(package.Id, package.Version)); AssertFileExists(packageVersionDirectory, "lib", "net45", "A.dll"); - var nupkgPath = pathResolver.GetPackageFilePath(packageIdentity.Id, packageIdentity.Version); + var nupkgPath = pathResolver.GetPackageFilePath(package.Id, package.Version); var nupkgFileInfo = new FileInfo(nupkgPath); Assert.True(File.Exists(nupkgFileInfo.FullName)); Assert.NotEqual(0, nupkgFileInfo.Length); @@ -559,39 +519,36 @@ await PackageExtractor.InstallFromSourceAsync( public async Task Test_ExtractionHonorsFileTimestamp() { // Arrange - var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("2.0.3")); + var package = new PackageIdentity("packageA", new NuGetVersion("2.0.3")); var entryModifiedTime = new DateTimeOffset(1985, 11, 20, 12, 0, 0, TimeSpan.FromHours(-7.0)).DateTime; using (var packagesDirectory = TestDirectory.Create()) { var pathResolver = new VersionFolderPathResolver(packagesDirectory); var packageFileInfo = await TestPackagesCore.GeneratePackageAsync( packagesDirectory, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString(), + package.Id, + package.Version.ToNormalizedString(), entryModifiedTime, "lib/net45/A.dll"); var versionFolderPathContext = new VersionFolderPathContext( - packageIdentity, + package, packagesDirectory, NullLogger.Instance, packageSaveMode: PackageSaveMode.Defaultv3, xmlDocFileSaveMode: XmlDocFileSaveMode.None); // Act - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFileInfo.FullName, - packageIdentity, - NullLogger.Instance)) + using (var packageFileStream = packageFileInfo.OpenRead()) { await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + stream => packageFileStream.CopyToAsync(stream), versionFolderPathContext, CancellationToken.None); } // Assert - var packageVersionDirectory = pathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version); + var packageVersionDirectory = pathResolver.GetInstallPath(package.Id, package.Version); AssertDirectoryExists(packageVersionDirectory); var dllPath = Path.Combine(packageVersionDirectory, "lib", "net45", "A.dll"); @@ -605,37 +562,34 @@ await PackageExtractor.InstallFromSourceAsync( public async Task Test_ExtractionDoesNotExtractFiles_IfPackageSaveModeDoesNotIncludeFiles() { // Arrange - var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("2.0.3")); + var package = new PackageIdentity("packageA", new NuGetVersion("2.0.3")); using (var packageFileInfo = TestPackagesCore.GetLegacyTestPackage()) using (var packagesDirectory = TestDirectory.Create()) { var pathResolver = new VersionFolderPathResolver(packagesDirectory); var versionFolderPathContext = new VersionFolderPathContext( - packageIdentity, + package, packagesDirectory, NullLogger.Instance, packageSaveMode: PackageSaveMode.Nupkg | PackageSaveMode.Nuspec, xmlDocFileSaveMode: XmlDocFileSaveMode.None); // Act - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFileInfo, - packageIdentity, - NullLogger.Instance)) + using (var packageFileStream = File.OpenRead(packageFileInfo)) { await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + stream => packageFileStream.CopyToAsync(stream), versionFolderPathContext, CancellationToken.None); } // Assert - var packageVersionDirectory = pathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version); - + var packageVersionDirectory = pathResolver.GetInstallPath(package.Id, package.Version); + AssertDirectoryExists(packageVersionDirectory); - AssertFileExists(packageVersionDirectory, pathResolver.GetPackageFileName(packageIdentity.Id, packageIdentity.Version)); - AssertFileExists(packageVersionDirectory, pathResolver.GetManifestFileName(packageIdentity.Id, packageIdentity.Version)); + AssertFileExists(packageVersionDirectory, pathResolver.GetPackageFileName(package.Id, package.Version)); + AssertFileExists(packageVersionDirectory, pathResolver.GetManifestFileName(package.Id, package.Version)); AssertFileExists(packageVersionDirectory, "packagea.2.0.3.nupkg.sha512"); Assert.False(File.Exists(Path.Combine(packageVersionDirectory, "lib", "test.dll"))); @@ -732,103 +686,31 @@ public override void Write(byte[] buffer, int offset, int count) } } - private class CorruptionException : Exception - { - } - - private sealed class ThrowingPackageArchiveDownloader : IPackageDownloader + private class CorruptStreamWrapper : StreamWrapperBase { - private bool _isDisposed; - private readonly ILogger _logger; - private readonly string _packageFilePath; - private readonly PackageIdentity _packageIdentity; - private Lazy<PackageArchiveReader> _packageReader; - private Lazy<FileStream> _sourceStream; - - public IAsyncPackageContentReader ContentReader => _packageReader.Value; - public IAsyncPackageCoreReader CoreReader => _packageReader.Value; - - internal ThrowingPackageArchiveDownloader( - string packageFilePath, - PackageIdentity packageIdentity, - ILogger logger) - { - _packageFilePath = packageFilePath; - _packageIdentity = packageIdentity; - _logger = logger; - _packageReader = new Lazy<PackageArchiveReader>(GetPackageReader); - _sourceStream = new Lazy<FileStream>(GetSourceStream); - } - - public void Dispose() - { - if (!_isDisposed) - { - if (_packageReader.IsValueCreated) - { - _packageReader.Value.Dispose(); - } - - if (_sourceStream.IsValueCreated) - { - _sourceStream.Value.Dispose(); - } - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - public async Task<bool> CopyNupkgFileToAsync(string destinationFilePath, CancellationToken cancellationToken) + public CorruptStreamWrapper(Stream stream) : base(stream) { - using (var destination = new FileStream( - destinationFilePath, - FileMode.Create, - FileAccess.ReadWrite, - FileShare.ReadWrite | FileShare.Delete, - bufferSize: 4096, - useAsync: true)) - { - var maxBytes = 100; - var buffer = new byte[maxBytes]; - var byteCount = _sourceStream.Value.Read(buffer, 0, maxBytes); - - Assert.True(byteCount > 0); - - await destination.WriteAsync(buffer, 0, byteCount); - - throw new CorruptionException(); - } } - public Task<string> GetPackageHashAsync(string hashAlgorithm, CancellationToken cancellationToken) + public override async Task CopyToAsync( + Stream destination, + int bufferSize, + CancellationToken cancellationToken) { - _sourceStream.Value.Seek(0, SeekOrigin.Begin); + var maxBytes = Math.Min(bufferSize, 100); + var buffer = new byte[maxBytes]; + var byteCount = _stream.Read(buffer, 0, maxBytes); - var bytes = new CryptoHashProvider(hashAlgorithm).CalculateHash(_sourceStream.Value); - var packageHash = Convert.ToBase64String(bytes); + Assert.True(byteCount > 0); - return Task.FromResult(packageHash); - } + await destination.WriteAsync(buffer, 0, byteCount); - private PackageArchiveReader GetPackageReader() - { - _sourceStream.Value.Seek(0, SeekOrigin.Begin); - - return new PackageArchiveReader(_sourceStream.Value); + throw new CorruptionException(); } + } - private FileStream GetSourceStream() - { - return new FileStream( - _packageFilePath, - FileMode.Open, - FileAccess.Read, - FileShare.Read, - bufferSize: 4096, - useAsync: true); - } + private class CorruptionException : Exception + { } } -} \ No newline at end of file +} diff --git a/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageArchiveReaderTests.cs b/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageArchiveReaderTests.cs index f70b50899ff..860ea4e28fb 100644 --- a/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageArchiveReaderTests.cs +++ b/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageArchiveReaderTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -1352,40 +1352,6 @@ public async Task GetDevelopmentDependencyAsync_ReturnsFalseIfNotDevelopmentDepe } } - [Fact] - public void NuspecReader_ReturnsNuspecReader() - { - using (var test = PackageReaderTest.Create(TestPackagesCore.GetPackageCoreReaderTestPackage())) - { - var nuspecReader = test.Reader.NuspecReader; - - Assert.NotNull(nuspecReader); - } - } - - [Fact] - public async Task GetNuspecReaderAsync_ReturnsNuspecReader() - { - using (var test = PackageReaderTest.Create(TestPackagesCore.GetPackageCoreReaderTestPackage())) - { - var nuspecReader = await test.Reader.GetNuspecReaderAsync(CancellationToken.None); - - Assert.NotNull(nuspecReader); - } - } - - [Fact] - public async Task CopyNupkgAsync_Throws() - { - using (var test = PackageReaderTest.Create(TestPackagesCore.GetPackageCoreReaderTestPackage())) - { - await Assert.ThrowsAsync<NotImplementedException>( - () => test.Reader.CopyNupkgAsync( - nupkgFilePath: "a", - cancellationToken: CancellationToken.None)); - } - } - private static string ExtractFile(string sourcePath, string targetPath, Stream sourceStream) { using (var targetStream = File.OpenWrite(targetPath)) diff --git a/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageExtractorTests.cs b/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageExtractorTests.cs index 0412d48823b..0d82dbd785c 100644 --- a/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageExtractorTests.cs +++ b/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageExtractorTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -10,8 +10,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using System.Xml.Linq; -using Moq; using NuGet.Common; using NuGet.Packaging.Core; using NuGet.Test.Utility; @@ -23,7 +21,7 @@ namespace NuGet.Packaging.Test public class PackageExtractorTests { [Fact] - public async Task InstallFromSourceAsync_StressTest() + public async Task PackageExtractor_InstallFromSourceAsync_StressTest() { // Arrange using (var root = TestDirectory.Create()) @@ -60,21 +58,15 @@ public async Task InstallFromSourceAsync_StressTest() sem.Wait(); - using (var packageDownloader = new LocalPackageArchiveDownloader( - sourcePathResolver.GetPackageFilePath(identity.Id, identity.Version), - identity, - NullLogger.Instance)) - { - var installed = await PackageExtractor.InstallFromSourceAsync( - packageDownloader, - pathContext, - CancellationToken.None); - - var exists = File.Exists(hashPath); - - installedBag.Add(installed); - hashBag.Add(exists); - } + var installed = await PackageExtractor.InstallFromSourceAsync( + packageStream.CopyToAsync, + pathContext, + CancellationToken.None); + + var exists = File.Exists(hashPath); + + installedBag.Add(installed); + hashBag.Add(exists); } }); @@ -94,7 +86,7 @@ public async Task InstallFromSourceAsync_StressTest() } [Fact] - public async Task InstallFromSourceAsync_ReturnsFalseWhenAlreadyInstalled() + public async Task PackageExtractor_InstallFromSourceAsync_ReturnsFalseWhenAlreadyInstalled() { // Arrange using (var root = TestDirectory.Create()) @@ -113,14 +105,11 @@ public async Task InstallFromSourceAsync_ReturnsFalseWhenAlreadyInstalled() var packagesPath = Path.Combine(root, "packages"); await SimpleTestPackageUtility.CreateFolderFeedV3(packagesPath, identity); - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFileInfo.FullName, - identity, - NullLogger.Instance)) + using (var packageStream = File.OpenRead(packageFileInfo.FullName)) { // Act var installed = await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + packageStream.CopyToAsync, new VersionFolderPathContext( identity, packagesPath, @@ -136,7 +125,7 @@ public async Task InstallFromSourceAsync_ReturnsFalseWhenAlreadyInstalled() } [Fact] - public async Task InstallFromSourceAsync_ReturnsTrueAfterNewInstall() + public async Task PackageExtractor_InstallFromSourceAsync_ReturnsTrueAfterNewInstall() { // Arrange using (var root = TestDirectory.Create()) @@ -154,14 +143,11 @@ public async Task InstallFromSourceAsync_ReturnsTrueAfterNewInstall() var packagesPath = Path.Combine(root, "packages"); - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFileInfo.FullName, - identity, - NullLogger.Instance)) + using (var packageStream = File.OpenRead(packageFileInfo.FullName)) { // Act var installed = await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + packageStream.CopyToAsync, new VersionFolderPathContext( identity, packagesPath, @@ -179,7 +165,7 @@ public async Task InstallFromSourceAsync_ReturnsTrueAfterNewInstall() [Theory] [InlineData(true)] [InlineData(false)] - public async Task InstallFromSourceAsync_WithLowercaseSpecified_ExtractsToSpecifiedCase(bool isLowercase) + public async Task PackageExtractor_WithLowercaseSpecified_ExtractsToSpecifiedCase(bool isLowercase) { // Arrange using (var root = TestDirectory.Create()) @@ -198,21 +184,18 @@ public async Task InstallFromSourceAsync_WithLowercaseSpecified_ExtractsToSpecif var packagesPath = Path.Combine(root, "packages"); var resolver = new VersionFolderPathResolver(packagesPath, isLowercase); - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFileInfo.FullName, - identity, - NullLogger.Instance)) + using (var packageStream = File.OpenRead(packageFileInfo.FullName)) { // Act await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + packageStream.CopyToAsync, new VersionFolderPathContext( identity, packagesPath, isLowercase, - NullLogger.Instance, - PackageSaveMode.Nupkg, - XmlDocFileSaveMode.None), + new TestLogger(), + packageSaveMode: PackageSaveMode.Nupkg, + xmlDocFileSaveMode: XmlDocFileSaveMode.None), CancellationToken.None); // Assert @@ -222,7 +205,7 @@ await PackageExtractor.InstallFromSourceAsync( } [Fact] - public async Task InstallFromSourceAsync_NuspecWithDifferentName_InstallsForV3() + public async Task PackageExtractor_NuspecWithDifferentName_InstallForV3() { // Arrange using (var root = TestDirectory.Create()) @@ -254,18 +237,13 @@ public async Task InstallFromSourceAsync_NuspecWithDifferentName_InstallsForV3() nuspecEntry.Delete(); } - var packageIdentity = new PackageIdentity("a", NuGetVersion.Parse("1.0.0")); - - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFile, - packageIdentity, - NullLogger.Instance)) + using (var packageStream = File.OpenRead(packageFile)) { // Act await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + packageStream.CopyToAsync, new VersionFolderPathContext( - packageIdentity, + new PackageIdentity("a", NuGetVersion.Parse("1.0.0")), root, NullLogger.Instance, packageSaveMode: PackageSaveMode.Defaultv3, @@ -280,7 +258,7 @@ await PackageExtractor.InstallFromSourceAsync( } [Fact] - public async Task InstallFromSourceAsync_NupkgWithDifferentName_InstallsForV3() + public async Task PackageExtractor_NupkgWithDifferentName_InstallForV3() { // Arrange using (var root = TestDirectory.Create()) @@ -297,18 +275,14 @@ public async Task InstallFromSourceAsync_NupkgWithDifferentName_InstallsForV3() SimpleTestPackageUtility.CreatePackages(root, packageA); var packageFile = Path.Combine(root, "a.1.0.0.nupkg"); - var packageIdentity = new PackageIdentity("a", NuGetVersion.Parse("1.0.0")); - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFile, - packageIdentity, - NullLogger.Instance)) + using (var packageStream = File.OpenRead(packageFile)) { // Act await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + packageStream.CopyToAsync, new VersionFolderPathContext( - packageIdentity, + new PackageIdentity("a", NuGetVersion.Parse("1.0.0")), root, NullLogger.Instance, packageSaveMode: PackageSaveMode.Defaultv3, @@ -323,7 +297,7 @@ await PackageExtractor.InstallFromSourceAsync( } [Fact] - public async Task ExtractPackageAsync_WithContentXmlFile() + public async Task PackageExtractor_WithContentXmlFile() { // Arrange using (var packageStream = TestPackagesCore.GetTestPackageWithContentXmlFile()) @@ -349,7 +323,7 @@ public async Task ExtractPackageAsync_WithContentXmlFile() } [Fact] - public async Task ExtractPackageAsync_DuplicateNupkg() + public async Task PackageExtractor_DuplicateNupkg() { using (var packageFile = TestPackagesCore.GetLegacyTestPackage()) { @@ -380,7 +354,7 @@ public async Task ExtractPackageAsync_DuplicateNupkg() } [Fact] - public async Task ExtractPackageAsync_NupkgContent() + public async Task PackageExtractor_NupkgContent() { // Arrange using (var root = TestDirectory.Create()) @@ -416,7 +390,7 @@ public async Task ExtractPackageAsync_NupkgContent() } [Fact] - public async Task ExtractPackageAsync_PackageSaveModeNupkg_FolderReader() + public async Task PackageExtractor_PackageSaveModeNupkg_FolderReader() { // Arrange using (var packageFile = TestPackagesCore.GetLegacyTestPackage()) @@ -447,7 +421,7 @@ public async Task ExtractPackageAsync_PackageSaveModeNupkg_FolderReader() } [Fact] - public async Task ExtractPackageAsync_PackageSaveModeNuspec_FolderReader() + public async Task PackageExtractor_PackageSaveModeNuspec_FolderReader() { // Arrange using (var packageFile = TestPackagesCore.GetLegacyTestPackage()) @@ -478,7 +452,7 @@ public async Task ExtractPackageAsync_PackageSaveModeNuspec_FolderReader() } [Fact] - public async Task ExtractPackageAsync_PackageSaveModeNuspecAndNupkg_PackageStream() + public async Task PackageExtractor_PackageSaveModeNuspecAndNupkg_PackageStream() { // Arrange using (var packageFile = TestPackagesCore.GetLegacyTestPackage()) @@ -509,7 +483,7 @@ public async Task ExtractPackageAsync_PackageSaveModeNuspecAndNupkg_PackageStrea } [Fact] - public async Task ExtractPackageAsync_DefaultPackageExtractionContext() + public async Task PackageExtractor_DefaultPackageExtractionContext() { // Arrange using (var root = TestDirectory.Create()) @@ -548,7 +522,7 @@ var pathToAFrDllInRunTimePackage } [Fact] - public async Task ExtractPackageAsync_ExtractsXmlFiles_IfXmlSaveModeIsSetToNone() + public async Task PackageExtractor_ExtractsXmlFiles_IfXmlSaveModeIsSetToNone() { // Arrange using (var root = TestDirectory.Create()) @@ -588,7 +562,7 @@ public async Task ExtractPackageAsync_ExtractsXmlFiles_IfXmlSaveModeIsSetToNone( } [Fact] - public async Task ExtractPackageAsync_CompressesXmlFiles_IfXmlSaveModeIsSetToCompress() + public async Task PackageExtractor_CompressesXmlFiles_IfXmlSaveModeIsSetToCompress() { // Arrange using (var root = TestDirectory.Create()) @@ -638,7 +612,7 @@ public async Task ExtractPackageAsync_CompressesXmlFiles_IfXmlSaveModeIsSetToCom } [Fact] - public async Task ExtractPackageAsync_CompressesXmlFilesForLanguageSpecificDirectories() + public async Task PackageExtractor_CompressesXmlFilesForLanguageSpecificDirectories() { // Arrange using (var root = TestDirectory.Create()) @@ -682,7 +656,7 @@ public async Task ExtractPackageAsync_CompressesXmlFilesForLanguageSpecificDirec } [Fact] - public async Task ExtractPackageAsync_SkipsXmlFiles_IfXmlSaveModeIsSetToSkip() + public async Task PackageExtractor_SkipsXmlFiles_IfXmlSaveModeIsSetToSkip() { // Arrange using (var root = TestDirectory.Create()) @@ -723,7 +697,7 @@ public async Task ExtractPackageAsync_SkipsXmlFiles_IfXmlSaveModeIsSetToSkip() } [Fact] - public async Task ExtractPackageAsync_SkipsXmlFiles_ForLanguageSpecificDirectories() + public async Task PackageExtractor_SkipsXmlFiles_ForLanguageSpecificDirectories() { // Arrange using (var root = TestDirectory.Create()) @@ -771,7 +745,7 @@ public async Task ExtractPackageAsync_SkipsXmlFiles_ForLanguageSpecificDirectori } [Fact] - public async Task ExtractPackageAsync_SkipsSatelliteXmlFiles() + public async Task PackageExtractor_SkipsSatelliteXmlFiles() { // Arrange using (var root = TestDirectory.Create()) @@ -829,7 +803,7 @@ public async Task ExtractPackageAsync_SkipsSatelliteXmlFiles() } [Fact] - public async Task ExtractPackageAsync_WithXmlModeCompress_DoesNotThrowIfPackageAlreadyContainsAXmlZipFile() + public async Task PackageExtractor_WithXmlModeCompress_DoesNotThrowIfPackageAlreadyContainsAXmlZipFile() { // Arrange using (var root = TestDirectory.Create()) @@ -870,7 +844,7 @@ public async Task ExtractPackageAsync_WithXmlModeCompress_DoesNotThrowIfPackageA } [Fact] - public async Task ExtractPackageAsync_WithXmlModeSkip_DoesNotSkipXmlZipFile() + public async Task PackageExtractor_WithXmlModeSkip_DoesNotSkipXmlZipFile() { // Arrange using (var root = TestDirectory.Create()) @@ -909,7 +883,7 @@ public async Task ExtractPackageAsync_WithXmlModeSkip_DoesNotSkipXmlZipFile() } [Fact] - public async Task ExtractPackageAsync_WithoutPackageSaveModeFile_DoesNotExtractFiles() + public async Task PackageExtractor_WithoutPackageSaveModeFile_DoesNotExtractFiles() { // Arrange using (var root = TestDirectory.Create()) @@ -949,7 +923,7 @@ public async Task ExtractPackageAsync_WithoutPackageSaveModeFile_DoesNotExtractF } [Fact] - public async Task ExtractPackageAsync_WithoutPackageSaveModeNuspec_DoesNotExtractNuspec() + public async Task PackageExtractor_WithoutPackageSaveModeNuspec_DoesNotExtractNuspec() { // Arrange using (var root = TestDirectory.Create()) @@ -989,7 +963,7 @@ public async Task ExtractPackageAsync_WithoutPackageSaveModeNuspec_DoesNotExtrac } [Fact] - public async Task ExtractPackageAsync_WithPackageSaveModeNuspec_ExtractsInnerNuspec() + public async Task PackageExtractor_WithPackageSaveModeNuspec_ExtractsInnerNuspec() { // Arrange using (var root = TestDirectory.Create()) @@ -1029,7 +1003,7 @@ public async Task ExtractPackageAsync_WithPackageSaveModeNuspec_ExtractsInnerNus } [Fact] - public async Task ExtractPackageAsync_WithoutPackageSaveModeNuspec_ExtractsInnerNuspec() + public async Task PackageExtractor_WithoutPackageSaveModeNuspec_ExtractsInnerNuspec() { // Arrange using (var root = TestDirectory.Create()) @@ -1069,7 +1043,7 @@ public async Task ExtractPackageAsync_WithoutPackageSaveModeNuspec_ExtractsInner } [Fact] - public async Task ExtractPackageAsync_WithoutPackageSaveModeNupkg_DoesNotExtractNupkg() + public async Task PackageExtractor_WithoutPackageSaveModeNupkg_DoesNotExtractNupkg() { // Arrange using (var root = TestDirectory.Create()) @@ -1108,492 +1082,6 @@ public async Task ExtractPackageAsync_WithoutPackageSaveModeNupkg_DoesNotExtract } } - [Fact] - public async Task ExtractPackageAsync_PreservesZipEntryTime() - { - // Arrange - using (var root = TestDirectory.Create()) - { - var time = DateTime.Parse("2014-09-26T01:23:00Z", - System.Globalization.CultureInfo.InvariantCulture, - System.Globalization.DateTimeStyles.AdjustToUniversal); - - var resolver = new PackagePathResolver(root); - var identity = new PackageIdentity("A", new NuGetVersion("2.0.3")); - var packageFileInfo = await TestPackagesCore.GeneratePackageAsync( - root, - identity.Id, - identity.Version.ToString(), - time.ToLocalTime(), "lib/net45/A.dll"); - - using (var packageStream = File.OpenRead(packageFileInfo.FullName)) - { - var packageExtractionContext = new PackageExtractionContext(NullLogger.Instance) - { - PackageSaveMode = PackageSaveMode.Nuspec | PackageSaveMode.Files - }; - - // Act - await PackageExtractor.ExtractPackageAsync( - packageStream, - resolver, - packageExtractionContext, - CancellationToken.None); - - var installPath = resolver.GetInstallPath(identity); - var outputDll = Path.Combine(installPath, "lib", "net45", "A.dll"); - var outputTime = File.GetLastWriteTimeUtc(outputDll); - - // Assert - Assert.True(File.Exists(outputDll)); - Assert.Equal(time, outputTime); - } - } - } - - [Fact] - public async Task ExtractPackageAsync_IgnoresFutureZipEntryTime() - { - // Arrange - using (var root = TestDirectory.Create()) - { - var testStartTime = DateTime.UtcNow; - var time = DateTime.Parse("2084-09-26T01:23:00Z", - System.Globalization.CultureInfo.InvariantCulture, - System.Globalization.DateTimeStyles.AdjustToUniversal); - - var resolver = new PackagePathResolver(root); - var identity = new PackageIdentity("A", new NuGetVersion("2.0.3")); - var packageFileInfo = await TestPackagesCore.GeneratePackageAsync( - root, - identity.Id, - identity.Version.ToString(), - time.ToLocalTime(), "lib/net45/A.dll"); - - using (var packageStream = File.OpenRead(packageFileInfo.FullName)) - { - var packageExtractionContext = new PackageExtractionContext(NullLogger.Instance) - { - PackageSaveMode = PackageSaveMode.Nuspec | PackageSaveMode.Files - }; - - // Act - await PackageExtractor.ExtractPackageAsync( - packageStream, - resolver, - packageExtractionContext, - CancellationToken.None); - - var installPath = resolver.GetInstallPath(identity); - var outputDll = Path.Combine(installPath, "lib", "net45", "A.dll"); - var outputTime = File.GetLastWriteTimeUtc(outputDll); - var testEndTime = DateTime.UtcNow; - - // Assert - Assert.True(File.Exists(outputDll)); - // Allow some slop with the time to deal with file system accuracy limits - Assert.InRange(outputTime, testStartTime.AddMinutes(-1), testEndTime.AddMinutes(1)); - } - } - } - - [Fact] - public async Task ExtractPackageAsync_SetsFilePermissions() - { - if (RuntimeEnvironmentHelper.IsWindows) - { - return; - } - // Arrange - using (var root = TestDirectory.Create()) - { - var resolver = new PackagePathResolver(root); - var identity = new PackageIdentity("A", new NuGetVersion("2.0.3")); - var packageFileInfo = await TestPackagesCore.GeneratePackageAsync( - root, - identity.Id, - identity.Version.ToString(), - DateTimeOffset.UtcNow.LocalDateTime, "lib/net45/A.dll"); - - using (var packageStream = File.OpenRead(packageFileInfo.FullName)) - { - var packageExtractionContext = new PackageExtractionContext(NullLogger.Instance) - { - PackageSaveMode = PackageSaveMode.Nuspec | PackageSaveMode.Files - }; - - // Act - await PackageExtractor.ExtractPackageAsync( - packageStream, - resolver, - packageExtractionContext, - CancellationToken.None); - - var installPath = resolver.GetInstallPath(identity); - var outputDll = Path.Combine(installPath, "lib", "net45", "A.dll"); - - // Assert - Assert.Equal("766", StatPermissions(outputDll)); - } - } - } - - [Fact] - public async Task ExtractPackageAsync_WithoutPackageStream_ThrowsForNullPackageReader() - { - using (var test = new ExtractPackageAsyncTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => PackageExtractor.ExtractPackageAsync( - packageReader: null, - packagePathResolver: test.Resolver, - packageExtractionContext: test.Context, - token: CancellationToken.None)); - - Assert.Equal("packageReader", exception.ParamName); - } - } - - [Fact] - public async Task ExtractPackageAsync_WithoutPackageStream_ThrowsForNullPackagePathResolver() - { - using (var test = new ExtractPackageAsyncTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => PackageExtractor.ExtractPackageAsync( - test.Reader, - packagePathResolver: null, - packageExtractionContext: test.Context, - token: CancellationToken.None)); - - Assert.Equal("packagePathResolver", exception.ParamName); - } - } - - [Fact] - public async Task ExtractPackageAsync_WithoutPackageStream_ThrowsForNullPackageExtractionContext() - { - using (var test = new ExtractPackageAsyncTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => PackageExtractor.ExtractPackageAsync( - test.Reader, - test.Resolver, - packageExtractionContext: null, - token: CancellationToken.None)); - - Assert.Equal("packageExtractionContext", exception.ParamName); - } - } - - [Fact] - public async Task ExtractPackageAsync_WithoutPackageStream_ThrowsIfCancelled() - { - using (var test = new ExtractPackageAsyncTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => PackageExtractor.ExtractPackageAsync( - test.Reader, - test.Resolver, - test.Context, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task ExtractPackageAsync_WithoutPackageStream_PackageSaveModeNone() - { - using (var test = new ExtractPackageAsyncTest()) - { - test.Context.PackageSaveMode = PackageSaveMode.None; - - var files = await PackageExtractor.ExtractPackageAsync( - test.Reader, - test.Resolver, - test.Context, - CancellationToken.None); - - var packageId = test.PackageIdentity.Id; - var packageVersion = test.PackageIdentity.Version.ToNormalizedString(); - var packageDirectoryPath = Path.Combine( - test.DestinationDirectory.FullName, - $"{packageId}.{packageVersion}"); - var nupkgFilePath = Path.Combine( - packageDirectoryPath, - $"{packageId}.{packageVersion}{PackagingCoreConstants.NupkgExtension}"); - var nuspecFilePath = Path.Combine(packageDirectoryPath, $"{packageId}{PackagingCoreConstants.NuspecExtension}"); - var libFilePath = Path.Combine(packageDirectoryPath, "lib", "net45", $"{packageId}.dll"); - - var comparer = PathUtility.GetStringComparerBasedOnOS(); - - Assert.DoesNotContain(nupkgFilePath, files, comparer); - Assert.DoesNotContain(nuspecFilePath, files, comparer); - Assert.DoesNotContain(libFilePath, files, comparer); - Assert.False(File.Exists(nupkgFilePath)); - Assert.False(File.Exists(nuspecFilePath)); - Assert.False(File.Exists(libFilePath)); - } - } - - [Fact] - public async Task ExtractPackageAsync_WithoutPackageStream_PackageSaveModeFiles() - { - using (var test = new ExtractPackageAsyncTest()) - { - test.Context.PackageSaveMode = PackageSaveMode.Files; - - var files = await PackageExtractor.ExtractPackageAsync( - test.Reader, - test.Resolver, - test.Context, - CancellationToken.None); - - var packageId = test.PackageIdentity.Id; - var packageVersion = test.PackageIdentity.Version.ToNormalizedString(); - var packageDirectoryPath = Path.Combine( - test.DestinationDirectory.FullName, - $"{packageId}.{packageVersion}"); - var nupkgFilePath = Path.Combine( - packageDirectoryPath, - $"{packageId}.{packageVersion}{PackagingCoreConstants.NupkgExtension}"); - var nuspecFilePath = Path.Combine(packageDirectoryPath, $"{packageId}{PackagingCoreConstants.NuspecExtension}"); - var libFilePath = Path.Combine(packageDirectoryPath, "lib", "net45", $"{packageId}.dll"); - - var comparer = PathUtility.GetStringComparerBasedOnOS(); - - Assert.DoesNotContain(nupkgFilePath, files, comparer); - Assert.DoesNotContain(nuspecFilePath, files, comparer); - Assert.Contains(libFilePath, files, comparer); - Assert.False(File.Exists(nupkgFilePath)); - Assert.False(File.Exists(nuspecFilePath)); - Assert.True(File.Exists(libFilePath)); - } - } - - [Fact] - public async Task ExtractPackageAsync_WithoutPackageStream_PackageSaveModeNuspec() - { - using (var test = new ExtractPackageAsyncTest()) - { - test.Context.PackageSaveMode = PackageSaveMode.Nuspec; - - var files = await PackageExtractor.ExtractPackageAsync( - test.Reader, - test.Resolver, - test.Context, - CancellationToken.None); - - var packageId = test.PackageIdentity.Id; - var packageVersion = test.PackageIdentity.Version.ToNormalizedString(); - var packageDirectoryPath = Path.Combine( - test.DestinationDirectory.FullName, - $"{packageId}.{packageVersion}"); - var nupkgFilePath = Path.Combine( - packageDirectoryPath, - $"{packageId}.{packageVersion}{PackagingCoreConstants.NupkgExtension}"); - var nuspecFilePath = Path.Combine(packageDirectoryPath, $"{packageId}{PackagingCoreConstants.NuspecExtension}"); - var libFilePath = Path.Combine(packageDirectoryPath, "lib", "net45", $"{packageId}.dll"); - - var comparer = PathUtility.GetStringComparerBasedOnOS(); - - Assert.DoesNotContain(nupkgFilePath, files, comparer); - Assert.Contains(nuspecFilePath, files, comparer); - Assert.DoesNotContain(libFilePath, files, comparer); - Assert.False(File.Exists(nupkgFilePath)); - Assert.True(File.Exists(nuspecFilePath)); - Assert.False(File.Exists(libFilePath)); - } - } - - [Fact] - public async Task ExtractPackageAsync_WithoutPackageStream_PackageSaveModeNupkg() - { - using (var test = new ExtractPackageAsyncTest()) - { - test.Context.PackageSaveMode = PackageSaveMode.Nupkg; - - var files = await PackageExtractor.ExtractPackageAsync( - test.Reader, - test.Resolver, - test.Context, - CancellationToken.None); - - var packageId = test.PackageIdentity.Id; - var packageVersion = test.PackageIdentity.Version.ToNormalizedString(); - var packageDirectoryPath = Path.Combine( - test.DestinationDirectory.FullName, - $"{packageId}.{packageVersion}"); - var nupkgFilePath = Path.Combine( - packageDirectoryPath, - $"{packageId}.{packageVersion}{PackagingCoreConstants.NupkgExtension}"); - var nuspecFilePath = Path.Combine(packageDirectoryPath, $"{packageId}{PackagingCoreConstants.NuspecExtension}"); - var libFilePath = Path.Combine(packageDirectoryPath, "lib", "net45", $"{packageId}.dll"); - - var comparer = PathUtility.GetStringComparerBasedOnOS(); - - Assert.Contains(nupkgFilePath, files, comparer); - Assert.DoesNotContain(nuspecFilePath, files, comparer); - Assert.DoesNotContain(libFilePath, files, comparer); - Assert.True(File.Exists(nupkgFilePath)); - Assert.False(File.Exists(nuspecFilePath)); - Assert.False(File.Exists(libFilePath)); - } - } - - [Fact] - public async Task ExtractPackageAsync_WithoutPackageStream_PackageSaveModeDefaultV2() - { - using (var test = new ExtractPackageAsyncTest()) - { - test.Context.PackageSaveMode = PackageSaveMode.Defaultv2; - - var files = await PackageExtractor.ExtractPackageAsync( - test.Reader, - test.Resolver, - test.Context, - CancellationToken.None); - - var packageId = test.PackageIdentity.Id; - var packageVersion = test.PackageIdentity.Version.ToNormalizedString(); - var packageDirectoryPath = Path.Combine( - test.DestinationDirectory.FullName, - $"{packageId}.{packageVersion}"); - var nupkgFilePath = Path.Combine( - packageDirectoryPath, - $"{packageId}.{packageVersion}{PackagingCoreConstants.NupkgExtension}"); - var nuspecFilePath = Path.Combine(packageDirectoryPath, $"{packageId}{PackagingCoreConstants.NuspecExtension}"); - var libFilePath = Path.Combine(packageDirectoryPath, "lib", "net45", $"{packageId}.dll"); - - var comparer = PathUtility.GetStringComparerBasedOnOS(); - - Assert.Contains(nupkgFilePath, files, comparer); - Assert.DoesNotContain(nuspecFilePath, files, comparer); - Assert.Contains(libFilePath, files, comparer); - Assert.True(File.Exists(nupkgFilePath)); - Assert.False(File.Exists(nuspecFilePath)); - Assert.True(File.Exists(libFilePath)); - } - } - - [Fact] - public async Task ExtractPackageAsync_WithoutPackageStream_PackageSaveModeDefaultV3() - { - using (var test = new ExtractPackageAsyncTest()) - { - test.Context.PackageSaveMode = PackageSaveMode.Defaultv3; - - var files = await PackageExtractor.ExtractPackageAsync( - test.Reader, - test.Resolver, - test.Context, - CancellationToken.None); - - var packageId = test.PackageIdentity.Id; - var packageVersion = test.PackageIdentity.Version.ToNormalizedString(); - var packageDirectoryPath = Path.Combine( - test.DestinationDirectory.FullName, - $"{packageId}.{packageVersion}"); - var nupkgFilePath = Path.Combine( - packageDirectoryPath, - $"{packageId}.{packageVersion}{PackagingCoreConstants.NupkgExtension}"); - var nuspecFilePath = Path.Combine(packageDirectoryPath, $"{packageId}{PackagingCoreConstants.NuspecExtension}"); - var libFilePath = Path.Combine(packageDirectoryPath, "lib", "net45", $"{packageId}.dll"); - - var comparer = PathUtility.GetStringComparerBasedOnOS(); - - Assert.Contains(nupkgFilePath, files, comparer); - Assert.Contains(nuspecFilePath, files, comparer); - Assert.Contains(libFilePath, files, comparer); - Assert.True(File.Exists(nupkgFilePath)); - Assert.True(File.Exists(nuspecFilePath)); - Assert.True(File.Exists(libFilePath)); - } - } - - [Fact] - public async Task ExtractPackageAsync_WithoutPackageStream_XmlDocFileSaveModeNone() - { - using (var test = new ExtractPackageAsyncTest()) - { - test.Context.PackageSaveMode = PackageSaveMode.Files; - test.Context.XmlDocFileSaveMode = XmlDocFileSaveMode.None; - - var files = await PackageExtractor.ExtractPackageAsync( - test.Reader, - test.Resolver, - test.Context, - CancellationToken.None); - - var packageId = test.PackageIdentity.Id; - var packageVersion = test.PackageIdentity.Version.ToNormalizedString(); - var packageDirectoryPath = Path.Combine( - test.DestinationDirectory.FullName, - $"{packageId}.{packageVersion}"); - var xmlFilePath = Path.Combine(packageDirectoryPath, "lib", "net45", $"{packageId}.xml"); - - var comparer = PathUtility.GetStringComparerBasedOnOS(); - - Assert.Contains(xmlFilePath, files, comparer); - Assert.True(File.Exists(xmlFilePath)); - } - } - - [Fact] - public async Task ExtractPackageAsync_WithoutPackageStream_XmlDocFileSaveModeSkip() - { - using (var test = new ExtractPackageAsyncTest()) - { - test.Context.PackageSaveMode = PackageSaveMode.Files; - test.Context.XmlDocFileSaveMode = XmlDocFileSaveMode.Skip; - - var files = await PackageExtractor.ExtractPackageAsync( - test.Reader, - test.Resolver, - test.Context, - CancellationToken.None); - - var packageId = test.PackageIdentity.Id; - var packageVersion = test.PackageIdentity.Version.ToNormalizedString(); - var packageDirectoryPath = Path.Combine( - test.DestinationDirectory.FullName, - $"{packageId}.{packageVersion}"); - var xmlFilePath = Path.Combine(packageDirectoryPath, "lib", "net45", $"{packageId}.xml"); - - var comparer = PathUtility.GetStringComparerBasedOnOS(); - - Assert.DoesNotContain(xmlFilePath, files, comparer); - Assert.False(File.Exists(xmlFilePath)); - } - } - - [Fact] - public async Task ExtractPackageAsync_WithoutPackageStream_XmlDocFileSaveModeCompress() - { - using (var test = new ExtractPackageAsyncTest()) - { - test.Context.PackageSaveMode = PackageSaveMode.Files; - test.Context.XmlDocFileSaveMode = XmlDocFileSaveMode.Compress; - - var files = await PackageExtractor.ExtractPackageAsync( - test.Reader, - test.Resolver, - test.Context, - CancellationToken.None); - - var packageId = test.PackageIdentity.Id; - var packageVersion = test.PackageIdentity.Version.ToNormalizedString(); - var packageDirectoryPath = Path.Combine( - test.DestinationDirectory.FullName, - $"{packageId}.{packageVersion}"); - var xmlZipFilePath = Path.Combine(packageDirectoryPath, "lib", "net45", $"{packageId}.xml.zip"); - - var comparer = PathUtility.GetStringComparerBasedOnOS(); - - Assert.Contains(xmlZipFilePath, files, comparer); - Assert.True(File.Exists(xmlZipFilePath)); - } - } - [Fact] public async Task InstallFromSourceAsync_WithoutPackageSaveModeNuspec_DoesNotExtractNuspec() { @@ -1609,14 +1097,11 @@ public async Task InstallFromSourceAsync_WithoutPackageSaveModeNuspec_DoesNotExt DateTimeOffset.UtcNow.LocalDateTime, "lib/net45/A.dll"); - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFileInfo.FullName, - identity, - NullLogger.Instance)) + using (var packageStream = File.OpenRead(packageFileInfo.FullName)) { // Act await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + packageStream.CopyToAsync, new VersionFolderPathContext( identity, root, @@ -1648,14 +1133,11 @@ public async Task InstallFromSourceAsync_WithoutPackageSaveModeNupkg_DoesNotExtr DateTimeOffset.UtcNow.LocalDateTime, "lib/net45/A.dll"); - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFileInfo.FullName, - identity, - NullLogger.Instance)) + using (var packageStream = File.OpenRead(packageFileInfo.FullName)) { // Act await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + packageStream.CopyToAsync, new VersionFolderPathContext( identity, root, @@ -1688,14 +1170,11 @@ public async Task InstallFromSourceAsync_WithoutPackageSaveModeFiles_DoesNotExtr DateTimeOffset.UtcNow.LocalDateTime, "lib/net45/A.dll"); - using (var packageDownloader = new LocalPackageArchiveDownloader( - packageFileInfo.FullName, - identity, - NullLogger.Instance)) + using (var packageStream = File.OpenRead(packageFileInfo.FullName)) { // Act await PackageExtractor.InstallFromSourceAsync( - packageDownloader, + packageStream.CopyToAsync, new VersionFolderPathContext( identity, root, @@ -1713,135 +1192,133 @@ await PackageExtractor.InstallFromSourceAsync( } [Fact] - public async Task InstallFromSourceAsync_DoesNotMoveNuspecFileIfFileNameIsSameAsExpected() + public async Task PackageExtractor_PreservesZipEntryTime() { - var nuspecFileName = "a.nuspec"; - var packageDownloader = new Mock<IPackageDownloader>(MockBehavior.Strict); - var coreReader = new Mock<IAsyncPackageCoreReader>(MockBehavior.Strict); - - packageDownloader.Setup(x => x.CopyNupkgFileToAsync(It.IsNotNull<string>(), It.IsAny<CancellationToken>())) - .ReturnsAsync(false); - packageDownloader.Setup(x => x.GetPackageHashAsync(It.IsNotNull<string>(), It.IsAny<CancellationToken>())) - .ReturnsAsync("hash"); - packageDownloader.SetupGet(x => x.CoreReader) - .Returns(coreReader.Object); - packageDownloader.Setup(x => x.Dispose()); - - coreReader.Setup(x => x.GetNuspecFileAsync(It.IsAny<CancellationToken>())) - .ReturnsAsync(nuspecFileName); - - IEnumerable<string> copiedFilePaths = null; - - coreReader.Setup(x => x.CopyFilesAsync( - It.IsNotNull<string>(), - It.IsNotNull<IEnumerable<string>>(), - It.IsNotNull<ExtractPackageFileDelegate>(), - It.IsNotNull<ILogger>(), - It.IsAny<CancellationToken>())) - .Callback<string, IEnumerable<string>, ExtractPackageFileDelegate, ILogger, CancellationToken>( - (destination, packageFiles, extractFileDelegate, logger, cancellationToken) => - { - var copiedFilePath = Path.Combine(destination, nuspecFileName); + // Arrange + using (var root = TestDirectory.Create()) + { + var time = DateTime.Parse("2014-09-26T01:23:00Z", + System.Globalization.CultureInfo.InvariantCulture, + System.Globalization.DateTimeStyles.AdjustToUniversal); - File.WriteAllText(copiedFilePath, string.Empty); + var resolver = new PackagePathResolver(root); + var identity = new PackageIdentity("A", new NuGetVersion("2.0.3")); + var packageFileInfo = await TestPackagesCore.GeneratePackageAsync( + root, + identity.Id, + identity.Version.ToString(), + time.ToLocalTime(), "lib/net45/A.dll"); - copiedFilePaths = new[] { copiedFilePath }; - }) - .ReturnsAsync(() => copiedFilePaths); + using (var packageStream = File.OpenRead(packageFileInfo.FullName)) + { + var packageExtractionContext = new PackageExtractionContext(NullLogger.Instance) + { + PackageSaveMode = PackageSaveMode.Nuspec | PackageSaveMode.Files + }; - var packageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); + // Act + await PackageExtractor.ExtractPackageAsync( + packageStream, + resolver, + packageExtractionContext, + CancellationToken.None); - using (var testDirectory = TestDirectory.Create()) - { - var versionFolderPathContext = new VersionFolderPathContext( - packageIdentity, - testDirectory.Path, - NullLogger.Instance, - PackageSaveMode.Nuspec, - XmlDocFileSaveMode.None); - var versionFolderPathResolver = new VersionFolderPathResolver(testDirectory.Path); - var installDirectoryPath = versionFolderPathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version); - var expectedNuspecFilePath = Path.Combine(installDirectoryPath, nuspecFileName); - - var wasInstalled = await PackageExtractor.InstallFromSourceAsync( - packageDownloader.Object, - versionFolderPathContext, - CancellationToken.None); + var installPath = resolver.GetInstallPath(identity); + var outputDll = Path.Combine(installPath, "lib", "net45", "A.dll"); + var outputTime = File.GetLastWriteTimeUtc(outputDll); - Assert.True(wasInstalled); - Assert.True(File.Exists(expectedNuspecFilePath)); - Assert.True(FileExistsCaseSensitively(expectedNuspecFilePath)); + // Assert + Assert.True(File.Exists(outputDll)); + Assert.Equal(time, outputTime); + } } - - coreReader.Verify(); - packageDownloader.Verify(); } [Fact] - public async Task InstallFromSourceAsync_MovesNuspecFileIfFileNameIsDifferentThanExpected() + public async Task PackageExtractor_IgnoresFutureZipEntryTime() { - var intendedNuspecFileName = "a.nuspec"; - var actualNuspecFileName = intendedNuspecFileName.ToUpperInvariant(); - var packageDownloader = new Mock<IPackageDownloader>(MockBehavior.Strict); - var coreReader = new Mock<IAsyncPackageCoreReader>(MockBehavior.Strict); - - packageDownloader.Setup(x => x.CopyNupkgFileToAsync(It.IsNotNull<string>(), It.IsAny<CancellationToken>())) - .ReturnsAsync(false); - packageDownloader.Setup(x => x.GetPackageHashAsync(It.IsNotNull<string>(), It.IsAny<CancellationToken>())) - .ReturnsAsync("hash"); - packageDownloader.SetupGet(x => x.CoreReader) - .Returns(coreReader.Object); - packageDownloader.Setup(x => x.Dispose()); - - coreReader.Setup(x => x.GetNuspecFileAsync(It.IsAny<CancellationToken>())) - .ReturnsAsync(actualNuspecFileName); - - IEnumerable<string> copiedFilePaths = null; - - coreReader.Setup(x => x.CopyFilesAsync( - It.IsNotNull<string>(), - It.IsNotNull<IEnumerable<string>>(), - It.IsNotNull<ExtractPackageFileDelegate>(), - It.IsNotNull<ILogger>(), - It.IsAny<CancellationToken>())) - .Callback<string, IEnumerable<string>, ExtractPackageFileDelegate, ILogger, CancellationToken>( - (destination, packageFiles, extractFileDelegate, logger, cancellationToken) => + // Arrange + using (var root = TestDirectory.Create()) + { + var testStartTime = DateTime.UtcNow; + var time = DateTime.Parse("2084-09-26T01:23:00Z", + System.Globalization.CultureInfo.InvariantCulture, + System.Globalization.DateTimeStyles.AdjustToUniversal); + + var resolver = new PackagePathResolver(root); + var identity = new PackageIdentity("A", new NuGetVersion("2.0.3")); + var packageFileInfo = await TestPackagesCore.GeneratePackageAsync( + root, + identity.Id, + identity.Version.ToString(), + time.ToLocalTime(), "lib/net45/A.dll"); + + using (var packageStream = File.OpenRead(packageFileInfo.FullName)) + { + var packageExtractionContext = new PackageExtractionContext(NullLogger.Instance) { - var copiedFilePath = Path.Combine(destination, actualNuspecFileName); + PackageSaveMode = PackageSaveMode.Nuspec | PackageSaveMode.Files + }; - File.WriteAllText(copiedFilePath, string.Empty); + // Act + await PackageExtractor.ExtractPackageAsync( + packageStream, + resolver, + packageExtractionContext, + CancellationToken.None); - copiedFilePaths = new[] { copiedFilePath }; - }) - .ReturnsAsync(() => copiedFilePaths); + var installPath = resolver.GetInstallPath(identity); + var outputDll = Path.Combine(installPath, "lib", "net45", "A.dll"); + var outputTime = File.GetLastWriteTimeUtc(outputDll); + var testEndTime = DateTime.UtcNow; - var packageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); + // Assert + Assert.True(File.Exists(outputDll)); + // Allow some slop with the time to deal with file system accuracy limits + Assert.InRange(outputTime, testStartTime.AddMinutes(-1), testEndTime.AddMinutes(1)); + } + } + } - using (var testDirectory = TestDirectory.Create()) + [Fact] + public async Task PackageExtractor_SetsFilePermissions() + { + if (RuntimeEnvironmentHelper.IsWindows) { - var versionFolderPathContext = new VersionFolderPathContext( - packageIdentity, - testDirectory.Path, - NullLogger.Instance, - PackageSaveMode.Nuspec, - XmlDocFileSaveMode.None); + return; + } + // Arrange + using (var root = TestDirectory.Create()) + { + var resolver = new PackagePathResolver(root); + var identity = new PackageIdentity("A", new NuGetVersion("2.0.3")); + var packageFileInfo = await TestPackagesCore.GeneratePackageAsync( + root, + identity.Id, + identity.Version.ToString(), + DateTimeOffset.UtcNow.LocalDateTime, "lib/net45/A.dll"); - var versionFolderPathResolver = new VersionFolderPathResolver(testDirectory.Path); - var installDirectoryPath = versionFolderPathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version); - var intendedNuspecFilePath = Path.Combine(installDirectoryPath, intendedNuspecFileName); + using (var packageStream = File.OpenRead(packageFileInfo.FullName)) + { + var packageExtractionContext = new PackageExtractionContext(NullLogger.Instance) + { + PackageSaveMode = PackageSaveMode.Nuspec | PackageSaveMode.Files + }; - var wasInstalled = await PackageExtractor.InstallFromSourceAsync( - packageDownloader.Object, - versionFolderPathContext, - CancellationToken.None); + // Act + await PackageExtractor.ExtractPackageAsync( + packageStream, + resolver, + packageExtractionContext, + CancellationToken.None); - Assert.True(wasInstalled); - Assert.True(File.Exists(intendedNuspecFilePath)); - Assert.True(FileExistsCaseSensitively(intendedNuspecFilePath)); - } + var installPath = resolver.GetInstallPath(identity); + var outputDll = Path.Combine(installPath, "lib", "net45", "A.dll"); - coreReader.Verify(); - packageDownloader.Verify(); + // Assert + Assert.Equal("766", StatPermissions(outputDll)); + } + } } private string StatPermissions(string path) @@ -1981,111 +1458,5 @@ public async Task CopySatelliteFilesAsync_ReturnsDestinationFilePath() Assert.Equal(Path.Combine(testDirectory.Path, "lib", "net45", "fr", "A.resources.dll"), files[0]); } } - - private static bool FileExistsRecursively(string directoryPath, string fileNamePattern) - { - return Directory.GetFiles(directoryPath, fileNamePattern, SearchOption.AllDirectories) - .Any(); - } - - private static bool FileExistsCaseSensitively(string expectedFilePath) - { - var directoryPath = Path.GetDirectoryName(expectedFilePath); - - return Directory.GetFiles(directoryPath, "*", SearchOption.TopDirectoryOnly) - .Where(filePath => string.Equals(filePath, expectedFilePath, StringComparison.Ordinal)) - .Any(); - } - - private sealed class ExtractPackageAsyncTest : IDisposable - { - private readonly TestDirectory _testDirectory; - - internal PackageExtractionContext Context { get; } - internal DirectoryInfo DestinationDirectory { get; } - internal FileInfo Package { get; } - internal PackageIdentity PackageIdentity { get; } - internal PackageReader Reader { get; } - internal PackagePathResolver Resolver { get; } - - internal ExtractPackageAsyncTest() - { - Context = new PackageExtractionContext(NullLogger.Instance); - PackageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); - _testDirectory = TestDirectory.Create(); - - var sourceDirectory = Path.Combine(_testDirectory.Path, "source"); - - Directory.CreateDirectory(sourceDirectory); - - DestinationDirectory = Directory.CreateDirectory(Path.Combine(_testDirectory.Path, "destination")); - - Package = CreatePackage(PackageIdentity, sourceDirectory); - Reader = new PackageReader(File.OpenRead(Package.FullName)); - Resolver = new PackagePathResolver(DestinationDirectory.FullName); - } - - public void Dispose() - { - Reader.Dispose(); - _testDirectory.Dispose(); - - GC.SuppressFinalize(this); - } - - private static FileInfo CreatePackage(PackageIdentity packageIdentity, string directoryPath) - { - var packageContext = new SimpleTestPackageContext() - { - Id = packageIdentity.Id, - Version = packageIdentity.Version.ToNormalizedString(), - Nuspec = XDocument.Parse($@"<?xml version=""1.0"" encoding=""utf-8""?> - <package> - <metadata> - <id>{packageIdentity.Id}</id> - <version>{packageIdentity.Version.ToNormalizedString()}</version> - <title /> - <language>en-US</language> - <contentFiles> - <files include=""lib/net45/{packageIdentity.Id}.dll"" copyToOutput=""true"" flatten=""false"" /> - </contentFiles> - </metadata> - </package>") - }; - - packageContext.AddFile($"lib/net45/{packageIdentity.Id}.dll"); - packageContext.AddFile($"lib/net45/{packageIdentity.Id}.xml"); - - SimpleTestPackageUtility.CreatePackages(directoryPath, packageContext); - - return new FileInfo( - Path.Combine( - directoryPath, - $"{packageIdentity.Id}.{packageIdentity.Version.ToNormalizedString()}.nupkg")); - } - } - - private sealed class PackageReader : PackageArchiveReader - { - private readonly Stream _stream; - - public PackageReader(Stream stream) - : base(stream) - { - _stream = stream; - } - - public override async Task<string> CopyNupkgAsync(string nupkgFilePath, CancellationToken cancellationToken) - { - _stream.Seek(offset: 0, origin: SeekOrigin.Begin); - - using (var destination = File.OpenWrite(nupkgFilePath)) - { - await _stream.CopyToAsync(destination); - } - - return nupkgFilePath; - } - } } } \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageFolderReaderTests.cs b/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageFolderReaderTests.cs index c62b434d3b6..b2769c38a64 100644 --- a/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageFolderReaderTests.cs +++ b/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageFolderReaderTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -1047,40 +1047,6 @@ public async Task GetDevelopmentDependencyAsync_ReturnsFalseIfNotDevelopmentDepe } } - [Fact] - public void NuspecReader_ReturnsNuspecReader() - { - using (var test = PackageReaderTest.Create(TestPackagesCore.GetPackageCoreReaderTestPackage())) - { - var nuspecReader = test.Reader.NuspecReader; - - Assert.NotNull(nuspecReader); - } - } - - [Fact] - public async Task GetNuspecReaderAsync_ReturnsNuspecReader() - { - using (var test = PackageReaderTest.Create(TestPackagesCore.GetPackageCoreReaderTestPackage())) - { - var nuspecReader = await test.Reader.GetNuspecReaderAsync(CancellationToken.None); - - Assert.NotNull(nuspecReader); - } - } - - [Fact] - public async Task CopyNupkgAsync_Throws() - { - using (var test = PackageReaderTest.Create(TestPackagesCore.GetPackageCoreReaderTestPackage())) - { - await Assert.ThrowsAsync<NotImplementedException>( - () => test.Reader.CopyNupkgAsync( - nupkgFilePath: "a", - cancellationToken: CancellationToken.None)); - } - } - private static string ExtractFile(string sourcePath, string targetPath, Stream sourceStream) { using (var targetStream = File.OpenWrite(targetPath)) diff --git a/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackagePathResolverTests.cs b/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackagePathResolverTests.cs index 0c7ca84dfa5..9c3dfd58a9f 100644 --- a/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackagePathResolverTests.cs +++ b/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackagePathResolverTests.cs @@ -1,10 +1,9 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using NuGet.Packaging.Core; -using NuGet.Test.Utility; using NuGet.Versioning; using Xunit; @@ -16,7 +15,7 @@ public class PackagePathResolverTests private static readonly PackageIdentity PackageIdentity = new PackageIdentity("PackageA", new NuGetVersion("1.0.0.0-BETA")); [Fact] - public void Constructor_ThrowsForNullRootDirectory() + public void PackagePathResolver_RejectsNullRootDirectory() { // Arrange & Act & Assert var exception = Assert.Throws<ArgumentException>(() => new PackagePathResolver( @@ -26,7 +25,7 @@ public void Constructor_ThrowsForNullRootDirectory() } [Fact] - public void Constructor_ThrowsForEmptyRootDirectory() + public void PackagePathResolver_RejectsEmptyRootDirectory() { // Arrange & Act & Assert var exception = Assert.Throws<ArgumentException>(() => new PackagePathResolver( @@ -38,7 +37,7 @@ public void Constructor_ThrowsForEmptyRootDirectory() [Theory] [InlineData(true, "PackageA.1.0.0.0-BETA")] [InlineData(false, "PackageA")] - public void GetPackageDirectoryName_ReturnsPackageDirectoryName(bool useSideBySidePaths, string expected) + public void PackagePathResolver_GetPackageDirectoryName(bool useSideBySidePaths, string expected) { // Arrange var target = new PackagePathResolver( @@ -55,7 +54,7 @@ public void GetPackageDirectoryName_ReturnsPackageDirectoryName(bool useSideBySi [Theory] [InlineData(true, "PackageA.1.0.0.0-BETA.nupkg")] [InlineData(false, "PackageA.nupkg")] - public void GetPackageFileName_ReturnsPackageFileName(bool useSideBySidePaths, string expected) + public void PackagePathResolver_GetPackageFileName(bool useSideBySidePaths, string expected) { // Arrange var target = new PackagePathResolver( @@ -69,24 +68,10 @@ public void GetPackageFileName_ReturnsPackageFileName(bool useSideBySidePaths, s Assert.Equal(expected, actual); } - [Theory] - [InlineData(true, "PackageA.packagedownload.marker")] - [InlineData(false, "PackageA.packagedownload.marker")] - public void GetPackageDownloadMarkerFileName_ReturnsPackageDownloadMarkerFileName( - bool useSideBySidePaths, - string expected) - { - var target = new PackagePathResolver(InMemoryRootDirectory, useSideBySidePaths); - - var actual = target.GetPackageDownloadMarkerFileName(PackageIdentity); - - Assert.Equal(expected, actual); - } - [Theory] [InlineData(true, "PackageA.nuspec")] [InlineData(false, "PackageA.nuspec")] - public void GetManifestFileName_ReturnsManifestFileName(bool useSideBySidePaths, string expected) + public void PackagePathResolver_GetManifestFileName(bool useSideBySidePaths, string expected) { // Arrange var target = new PackagePathResolver( @@ -103,7 +88,7 @@ public void GetManifestFileName_ReturnsManifestFileName(bool useSideBySidePaths, [Theory] [InlineData(true, "PackageA.1.0.0.0-BETA")] [InlineData(false, "PackageA")] - public void GetInstallPath_ReturnsInstallPath(bool useSideBySidePaths, string expected) + public void PackagePathResolver_GetInstallPath(bool useSideBySidePaths, string expected) { // Arrange var target = new PackagePathResolver( @@ -117,73 +102,5 @@ public void GetInstallPath_ReturnsInstallPath(bool useSideBySidePaths, string ex // Assert Assert.Equal(expected, actual); } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void GetInstalledPath_ReturnsNullIfFileDoesNotExist(bool useSideBySidePaths) - { - using (var testDirectory = TestDirectory.Create()) - { - var target = new PackagePathResolver(testDirectory.Path, useSideBySidePaths); - - var filePath = target.GetInstalledPath(PackageIdentity); - - Assert.Null(filePath); - } - } - - [Theory] - [InlineData(true, "PackageA.1.0.0.0-BETA.nupkg")] - [InlineData(false, "PackageA.nupkg")] - public void GetInstalledPath_ReturnsInstalledPath(bool useSideBySidePaths, string expectedFileName) - { - using (var testDirectory = TestDirectory.Create()) - { - var expectedFilePath = Path.Combine(testDirectory.Path, expectedFileName); - - File.WriteAllText(expectedFilePath, string.Empty); - - var target = new PackagePathResolver(testDirectory.Path, useSideBySidePaths); - - var actualFilePath = target.GetInstalledPath(PackageIdentity); - - Assert.Equal(testDirectory.Path, actualFilePath); - } - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void GetInstalledPackageFilePath_ReturnsNullIfFileDoesNotExist(bool useSideBySidePaths) - { - using (var testDirectory = TestDirectory.Create()) - { - var target = new PackagePathResolver(testDirectory.Path, useSideBySidePaths); - - var filePath = target.GetInstalledPackageFilePath(PackageIdentity); - - Assert.Null(filePath); - } - } - - [Theory] - [InlineData(true, "PackageA.1.0.0.0-BETA.nupkg")] - [InlineData(false, "PackageA.nupkg")] - public void GetInstalledPackageFilePath_ReturnsInstalledPackageFilePath(bool useSideBySidePaths, string expectedFileName) - { - using (var testDirectory = TestDirectory.Create()) - { - var expectedFilePath = Path.Combine(testDirectory.Path, expectedFileName); - - File.WriteAllText(expectedFilePath, string.Empty); - - var target = new PackagePathResolver(testDirectory.Path, useSideBySidePaths); - - var actualFilePath = target.GetInstalledPackageFilePath(PackageIdentity); - - Assert.Equal(expectedFilePath, actualFilePath); - } - } } -} \ No newline at end of file +} diff --git a/test/NuGet.Core.Tests/NuGet.Packaging.Test/VersionFolderPathResolverTests.cs b/test/NuGet.Core.Tests/NuGet.Packaging.Test/VersionFolderPathResolverTests.cs index 84e02a70dca..98df3eb0f20 100644 --- a/test/NuGet.Core.Tests/NuGet.Packaging.Test/VersionFolderPathResolverTests.cs +++ b/test/NuGet.Core.Tests/NuGet.Packaging.Test/VersionFolderPathResolverTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.IO; @@ -10,7 +10,7 @@ namespace NuGet.Packaging.Test public class VersionFolderPathResolverTests { [Fact] - public void RootPath_ReturnsRootPath() + public void VersionFolderPathResolver_GetRoot() { // Arrange && Act var resolver = new VersionFolderPathResolver("/tmp/test", isLowercase: false); @@ -23,7 +23,7 @@ public void RootPath_ReturnsRootPath() [Theory] [InlineData("nuget.packaging", "3.4.3-beta", true)] [InlineData("NuGet.Packaging", "3.4.3-Beta", false)] - public void GetInstallPath_ReturnsInstallPath(string id, string version, bool isLowercase) + public void VersionFolderPathResolver_GetInstallPath(string id, string version, bool isLowercase) { // Arrange var tc = new TestContext { IsLowercase = isLowercase }; @@ -38,7 +38,7 @@ public void GetInstallPath_ReturnsInstallPath(string id, string version, bool is [Theory] [InlineData("nuget.packaging", "3.4.3-beta", "nuget.packaging.3.4.3-beta.nupkg", true)] [InlineData("NuGet.Packaging", "3.4.3-Beta", "NuGet.Packaging.3.4.3-Beta.nupkg", false)] - public void GetPackageFilePath_ReturnsPackageFilePath(string id, string version, string file, bool isLowercase) + public void VersionFolderPathResolver_GetPackageFilePath(string id, string version, string file, bool isLowercase) { // Arrange var tc = new TestContext { IsLowercase = isLowercase }; @@ -55,7 +55,7 @@ public void GetPackageFilePath_ReturnsPackageFilePath(string id, string version, [Theory] [InlineData("nuget.packaging", "3.4.3-beta", "nuget.packaging.nuspec", true)] [InlineData("NuGet.Packaging", "3.4.3-Beta", "NuGet.Packaging.nuspec", false)] - public void GetManifestFilePath_ReturnsManifestFilePath(string id, string version, string file, bool isLowercase) + public void VersionFolderPathResolver_GetManifestFilePath(string id, string version, string file, bool isLowercase) { // Arrange var tc = new TestContext { IsLowercase = isLowercase }; @@ -72,7 +72,7 @@ public void GetManifestFilePath_ReturnsManifestFilePath(string id, string versio [Theory] [InlineData("nuget.packaging", "3.4.3-beta", "nuget.packaging.3.4.3-beta.nupkg.sha512", true)] [InlineData("NuGet.Packaging", "3.4.3-Beta", "NuGet.Packaging.3.4.3-Beta.nupkg.sha512", false)] - public void GetHashPath_ReturnsHashPath(string id, string version, string file, bool isLowercase) + public void VersionFolderPathResolver_GetHashPath(string id, string version, string file, bool isLowercase) { // Arrange var tc = new TestContext { IsLowercase = isLowercase }; @@ -89,7 +89,7 @@ public void GetHashPath_ReturnsHashPath(string id, string version, string file, [Theory] [InlineData("nuget.packaging.3.4.3-beta.nupkg.sha512", true)] [InlineData("NuGet.Packaging.3.4.3-Beta.nupkg.sha512", false)] - public void GetHashFileName_ReturnsHashFileName(string file, bool isLowercase) + public void VersionFolderPathResolver_GetHashFileName(string file, bool isLowercase) { // Arrange var tc = new TestContext { IsLowercase = isLowercase }; @@ -104,7 +104,7 @@ public void GetHashFileName_ReturnsHashFileName(string file, bool isLowercase) [Theory] [InlineData("nuget.packaging", "3.4.3-beta", true)] [InlineData("NuGet.Packaging", "3.4.3-Beta", false)] - public void GetPackageDirectory_ReturnsPackageDirectory(string id, string version, bool isLowercase) + public void VersionFolderPathResolver_GetPackageDirectory(string id, string version, bool isLowercase) { // Arrange var tc = new TestContext { IsLowercase = isLowercase }; @@ -119,7 +119,7 @@ public void GetPackageDirectory_ReturnsPackageDirectory(string id, string versio [Theory] [InlineData("nuget.packaging.3.4.3-beta.nupkg", true)] [InlineData("NuGet.Packaging.3.4.3-Beta.nupkg", false)] - public void GetPackageFileName_ReturnsPackageFileName(string file, bool isLowercase) + public void VersionFolderPathResolver_GetPackageFileName(string file, bool isLowercase) { // Arrange var tc = new TestContext { IsLowercase = isLowercase }; @@ -134,7 +134,7 @@ public void GetPackageFileName_ReturnsPackageFileName(string file, bool isLowerc [Theory] [InlineData("nuget.packaging.nuspec", true)] [InlineData("NuGet.Packaging.nuspec", false)] - public void GetManifestFileName_ReturnsManifestFileName(string file, bool isLowercase) + public void VersionFolderPathResolver_GetManifestFileName(string file, bool isLowercase) { // Arrange var tc = new TestContext { IsLowercase = isLowercase }; @@ -149,7 +149,7 @@ public void GetManifestFileName_ReturnsManifestFileName(string file, bool isLowe [Theory] [InlineData("nuget.packaging", true)] [InlineData("NuGet.Packaging", false)] - public void GetVersionListPath_ReturnsVersionListPath(string directory, bool isLowercase) + public void VersionFolderPathResolver_GetVersionListPath(string directory, bool isLowercase) { // Arrange var tc = new TestContext { IsLowercase = isLowercase }; @@ -166,7 +166,7 @@ public void GetVersionListPath_ReturnsVersionListPath(string directory, bool isL [Theory] [InlineData("nuget.packaging", true)] [InlineData("NuGet.Packaging", false)] - public void GetVersionListDirectory_ReturnsVersionListDirectory(string directory, bool isLowercase) + public void VersionFolderPathResolver_GetVersionListDirectory(string directory, bool isLowercase) { // Arrange var tc = new TestContext { IsLowercase = isLowercase }; @@ -178,20 +178,6 @@ public void GetVersionListDirectory_ReturnsVersionListDirectory(string directory Assert.Equal(directory, actual); } - [Theory] - [InlineData("nuget.packaging.packagedownload.marker", true)] - [InlineData("NuGet.Packaging.packagedownload.marker", false)] - public void GetPackageDownloadMarkerFileName_ReturnsPackageDownloadMarkerFileName( - string expectedFileName, - bool isLowercase) - { - var context = new TestContext { IsLowercase = isLowercase }; - - var actualFileName = context.Target.GetPackageDownloadMarkerFileName(context.Id); - - Assert.Equal(expectedFileName, actualFileName); - } - private class TestContext { public TestContext() @@ -213,4 +199,4 @@ public VersionFolderPathResolver Target } } } -} \ No newline at end of file +} diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Converters/SemanticVersionConverterTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Converters/SemanticVersionConverterTests.cs deleted file mode 100644 index 328c9364624..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Converters/SemanticVersionConverterTests.cs +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using Newtonsoft.Json; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class SemanticVersionConverterTests - { - private static readonly SemanticVersionConverter _converter = new SemanticVersionConverter(); - private static readonly SemanticVersion _version = new SemanticVersion(major: 1, minor: 2, patch: 3, releaseLabel: "a", metadata: "b"); - - [Fact] - public void CanConvert_ReturnsTrueForSemanticVersionType() - { - var canConvert = _converter.CanConvert(typeof(SemanticVersion)); - - Assert.True(canConvert); - } - - [Fact] - public void CanConvert_ReturnsFalseForNonSemanticVersionType() - { - var canConvert = _converter.CanConvert(typeof(DateTime)); - - Assert.False(canConvert); - } - - [Fact] - public void ReadJson_ThrowsForInvalidVersion() - { - using (var stringReader = new StringReader("1.2")) - using (var jsonReader = new JsonTextReader(stringReader)) - { - var exception = Assert.Throws<ArgumentException>(() => _converter.ReadJson( - jsonReader, - typeof(SemanticVersion), - existingValue: null, - serializer: JsonSerializationUtilities.Serializer)); - - Assert.Equal("value", exception.ParamName); - } - } - - [Fact] - public void ReadJson_ReadsSemanticVersion() - { - using (var stringReader = new StringReader($"\"{_version.ToString()}\"")) - using (var jsonReader = new JsonTextReader(stringReader)) - { - var actualVersion = _converter.ReadJson( - jsonReader, - typeof(SemanticVersion), - existingValue: null, - serializer: JsonSerializationUtilities.Serializer); - - Assert.Equal(_version, actualVersion); - } - } - - [Fact] - public void WriteJson_ThrowsForInvalidVersion() - { - using (var stringWriter = new StringWriter()) - using (var jsonWriter = new JsonTextWriter(stringWriter)) - { - Assert.Throws<InvalidCastException>( - () => _converter.WriteJson(jsonWriter, "1.2", JsonSerializationUtilities.Serializer)); - } - } - - [Fact] - public void WriteJson_WritesSemanticVersionToString() - { - using (var stringWriter = new StringWriter()) - using (var jsonWriter = new JsonTextWriter(stringWriter)) - { - _converter.WriteJson(jsonWriter, _version, JsonSerializationUtilities.Serializer); - - Assert.Equal($"\"{_version.ToString()}\"", stringWriter.ToString()); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/DownloadResourceResultTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/DownloadResourceResultTests.cs deleted file mode 100644 index e11c9633d7a..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/DownloadResourceResultTests.cs +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using NuGet.Common; -using NuGet.Frameworks; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; -using Xunit; - -namespace NuGet.Protocol.Tests -{ - public class DownloadResourceResultTests - { - [Theory] - [InlineData(DownloadResourceResultStatus.Available)] - [InlineData(DownloadResourceResultStatus.AvailableWithoutStream)] - public void Constructor_Status_ThrowsForInvalidStatus(DownloadResourceResultStatus status) - { - var exception = Assert.Throws<ArgumentException>(() => new DownloadResourceResult(status)); - - var expectedMessage = $"A stream should be provided when the result is available.{Environment.NewLine}" - + "Parameter name: status"; - - Assert.Equal("status", exception.ParamName); - Assert.Equal(expectedMessage, exception.Message); - } - - [Theory] - [InlineData(DownloadResourceResultStatus.Cancelled)] - [InlineData(DownloadResourceResultStatus.NotFound)] - public void Constructor_Status_InitializesProperties(DownloadResourceResultStatus status) - { - using (var result = new DownloadResourceResult(status)) - { - Assert.Null(result.PackageReader); - Assert.Null(result.PackageSource); - Assert.Null(result.PackageStream); - Assert.Equal(status, result.Status); - } - } - - [Fact] - public void Constructor_PackageReaderSource_ThrowsForNullPackageReader() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new DownloadResourceResult(packageReader: null, source: "a")); - - Assert.Equal("packageReader", exception.ParamName); - } - - [Fact] - public void Constructor_PackageReaderSource_AllowsNullSource() - { - using (var packageReader = new TestPackageReader()) - using (var result = new DownloadResourceResult(packageReader, source: null)) - { - Assert.Null(result.PackageSource); - } - } - - [Fact] - public void Constructor_PackageReaderSource_InitializesProperties() - { - using (var packageReader = new TestPackageReader()) - using (var result = new DownloadResourceResult(packageReader, source: "a")) - { - Assert.Same(packageReader, result.PackageReader); - Assert.Equal("a", result.PackageSource); - Assert.Null(result.PackageStream); - Assert.Equal(DownloadResourceResultStatus.AvailableWithoutStream, result.Status); - } - } - - [Fact] - public void Constructor_Stream_ThrowsForNullStream() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new DownloadResourceResult(stream: null)); - - Assert.Equal("stream", exception.ParamName); - } - - [Fact] - public void Constructor_Stream_InitializesProperties() - { - using (var result = new DownloadResourceResult(Stream.Null)) - { - Assert.Null(result.PackageReader); - Assert.Null(result.PackageSource); - Assert.Same(Stream.Null, result.PackageStream); - Assert.Equal(DownloadResourceResultStatus.Available, result.Status); - } - } - - [Fact] - public void Constructor_StreamSource_ThrowsForNullStream() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new DownloadResourceResult(stream: null, source: "a")); - - Assert.Equal("stream", exception.ParamName); - } - - [Fact] - public void Constructor_StreamSource_AllowsNullSource() - { - using (var result = new DownloadResourceResult(Stream.Null, source: null)) - { - Assert.Null(result.PackageSource); - } - } - - [Fact] - public void Constructor_StreamSource_InitializesProperties() - { - using (var result = new DownloadResourceResult(Stream.Null, source: "a")) - { - Assert.Null(result.PackageReader); - Assert.Equal("a", result.PackageSource); - Assert.Same(Stream.Null, result.PackageStream); - Assert.Equal(DownloadResourceResultStatus.Available, result.Status); - } - } - - [Fact] - public void Constructor_StreamPackageReaderBase_ThrowsForNullStream() - { - using (var packageReader = new TestPackageReader()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => new DownloadResourceResult(stream: null, packageReader: packageReader)); - - Assert.Equal("stream", exception.ParamName); - } - } - - [Fact] - public void Constructor_StreamPackageReaderBase_AllowsNullPackageReader() - { - using (var result = new DownloadResourceResult(Stream.Null, packageReader: null)) - { - Assert.Null(result.PackageReader); - } - } - - [Fact] - public void Constructor_StreamPackageReaderBase_InitializesProperties() - { - using (var packageReader = new TestPackageReader()) - using (var result = new DownloadResourceResult(Stream.Null, packageReader)) - { - Assert.Same(packageReader, result.PackageReader); - Assert.Null(result.PackageSource); - Assert.Same(Stream.Null, result.PackageStream); - Assert.Equal(DownloadResourceResultStatus.Available, result.Status); - } - } - - [Fact] - public void Constructor_StreamPackageReaderBaseSource_ThrowsForNullStream() - { - using (var packageReader = new TestPackageReader()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => new DownloadResourceResult(stream: null, packageReader: packageReader, source: "a")); - - Assert.Equal("stream", exception.ParamName); - } - } - - [Fact] - public void Constructor_StreamPackageReaderBaseSource_AllowsNullPackageReaderAndSource() - { - using (var result = new DownloadResourceResult(Stream.Null, packageReader: null, source: null)) - { - Assert.Null(result.PackageReader); - Assert.Null(result.PackageSource); - } - } - - [Fact] - public void Constructor_StreamPackageReaderBaseSource_InitializesProperties() - { - using (var packageReader = new TestPackageReader()) - using (var result = new DownloadResourceResult(Stream.Null, packageReader, source: "a")) - { - Assert.Same(packageReader, result.PackageReader); - Assert.Equal("a", result.PackageSource); - Assert.Same(Stream.Null, result.PackageStream); - Assert.Equal(DownloadResourceResultStatus.Available, result.Status); - } - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var stream = new TestStream()) - using (var result = new DownloadResourceResult(stream)) - { - result.Dispose(); - result.Dispose(); - - Assert.Equal(1, stream.DisposeCallCount); - } - } - - private sealed class TestPackageReader : PackageReaderBase - { - public TestPackageReader() - : base(DefaultFrameworkNameProvider.Instance, DefaultCompatibilityProvider.Instance) - { - } - - public override IEnumerable<string> CopyFiles( - string destination, - IEnumerable<string> packageFiles, - ExtractPackageFileDelegate extractFile, - ILogger logger, - CancellationToken token) - { - throw new NotImplementedException(); - } - - public override IEnumerable<string> GetFiles() - { - throw new NotImplementedException(); - } - - public override IEnumerable<string> GetFiles(string folder) - { - throw new NotImplementedException(); - } - - public override Stream GetStream(string path) - { - throw new NotImplementedException(); - } - - protected override void Dispose(bool disposing) - { - } - } - - private sealed class TestStream : MemoryStream - { - internal int DisposeCallCount { get; private set; } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - - ++DisposeCallCount; - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/HttpFileSystemBasedFindPackageByIdResourceTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/HttpFileSystemBasedFindPackageByIdResourceTests.cs new file mode 100644 index 00000000000..b80d85f2ab6 --- /dev/null +++ b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/HttpFileSystemBasedFindPackageByIdResourceTests.cs @@ -0,0 +1,79 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using NuGet.Protocol.Core.Types; +using NuGet.Test.Utility; +using NuGet.Versioning; +using Test.Utility; +using Xunit; + +namespace NuGet.Protocol.Tests +{ + public class HttpFileSystemBasedFindPackageByIdResourceTests + { + [Fact] + public async Task HttpFileSystemBasedFindPackageById_GetOriginalIdentity() + { + // Arrange + using (var workingDir = TestDirectory.Create()) + { + var source = "http://testsource.com/v3-with-flat-container/index.json"; + var package = SimpleTestPackageUtility.CreateFullPackage(workingDir, "DeepEqual", "1.4.0.1-rc"); + var packageBytes = File.ReadAllBytes(package.FullName); + + var responses = new Dictionary<string, Func<HttpRequestMessage, Task<HttpResponseMessage>>> + { + { + source, + _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new TestContent(JsonData.IndexWithFlatContainer) + }) + }, + { + "https://api.nuget.org/v3-flatcontainer/deepequal/index.json", + _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new TestContent(JsonData.DeepEqualFlatContainerIndex) + }) + }, + { + "https://api.nuget.org/v3-flatcontainer/deepequal/1.4.0.1-rc/deepequal.1.4.0.1-rc.nupkg", + _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new ByteArrayContent(packageBytes) + }) + } + }; + + var repo = StaticHttpHandler.CreateSource(source, Repository.Provider.GetCoreV3(), responses); + var logger = new TestLogger(); + + using (var cacheContext = new SourceCacheContext()) + { + var resource = await repo.GetResourceAsync<FindPackageByIdResource>(); + + // Act + var info = await resource.GetDependencyInfoAsync( + "DEEPEQUAL", + new NuGetVersion("1.4.0.1-RC"), + cacheContext, + logger, + CancellationToken.None); + + // Assert + Assert.IsType<HttpFileSystemBasedFindPackageByIdResource>(resource); + Assert.Equal("DeepEqual", info.PackageIdentity.Id); + Assert.Equal("1.4.0.1-rc", info.PackageIdentity.Version.ToNormalizedString()); + } + } + } + } +} diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/LocalRepositories/LocalV2FindPackageByIdResourceTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/LocalRepositories/LocalV2FindPackageByIdResourceTests.cs deleted file mode 100644 index 983ca3437c9..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/LocalRepositories/LocalV2FindPackageByIdResourceTests.cs +++ /dev/null @@ -1,531 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; -using NuGet.Test.Utility; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Tests -{ - public class LocalV2FindPackageByIdResourceTests - { - [Fact] - public void Constructor_ThrowsForNullPackageSource() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new LocalV2FindPackageByIdResource(packageSource: null)); - - Assert.Equal("packageSource", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetAllVersionsAsync_ThrowsForNullOrEmptyId(string id) - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.GetAllVersionsAsync( - id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowsForNullSourceCacheContext() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowsForNullLogger() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowIfCancelled() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ReturnsEmptyEnumerableIfPackageIdNotFound() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var versions = await test.Resource.GetAllVersionsAsync( - id: "b", - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.Empty(versions); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ReturnsAllVersions() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var versions = await test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Equal(new[] { NuGetVersion.Parse("1.0.0") }, versions); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetDependencyInfoAsync_ThrowsForNullOrEmptyId(string id) - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.GetDependencyInfoAsync( - id, - NuGetVersion.Parse("1.0.0"), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullVersion() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id, - version: null, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("version", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullSourceCacheContext() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullLogger() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowIfCancelled() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ReturnsNullIfPackageNotFound() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var dependencyInfo = await test.Resource.GetDependencyInfoAsync( - id: "b", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.Null(dependencyInfo); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_GetsOriginalIdentity() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var info = await test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id.ToUpper(), - test.PackageIdentity.Version, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Equal(test.PackageIdentity.Id.ToLower(), info.PackageIdentity.Id); - Assert.Equal(test.PackageIdentity.Version, info.PackageIdentity.Version); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task CopyNupkgToStreamAsync_ThrowsForNullId(string id) - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.CopyNupkgToStreamAsync( - id, - NuGetVersion.Parse("1.0.0"), - Stream.Null, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullVersion() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - version: null, - destination: Stream.Null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("version", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullDestination() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - destination: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("destination", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullSourceCacheContext() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - Stream.Null, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullLogger() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - Stream.Null, - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsIfCancelled() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - Stream.Null, - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ReturnsFalseIfNotCopied() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - using (var stream = new MemoryStream()) - { - var wasCopied = await test.Resource.CopyNupkgToStreamAsync( - id: "b", - version: NuGetVersion.Parse("1.0.0"), - destination: stream, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.False(wasCopied); - Assert.Equal(0, stream.Length); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ReturnsTrueIfCopied() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - using (var stream = new MemoryStream()) - { - var wasCopied = await test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - stream, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.True(wasCopied); - Assert.Equal(test.Package.Length, stream.Length); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullPackageIdentity() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - packageIdentity: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullSourceCacheContext() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullLogger() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsIfCancelled() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsNullIfPackageNotFound() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var downloader = await test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "b", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Null(downloader); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsPackageDownloaderIfPackageFound() - { - using (var test = LocalV2FindPackageByIdResourceTest.Create()) - { - var downloader = await test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.IsType<LocalPackageArchiveDownloader>(downloader); - } - } - - private sealed class LocalV2FindPackageByIdResourceTest : IDisposable - { - private readonly TestDirectory _testDirectory; - - internal FileInfo Package { get; } - internal PackageIdentity PackageIdentity { get; } - internal LocalV2FindPackageByIdResource Resource { get; } - internal SourceCacheContext SourceCacheContext { get; } - - private LocalV2FindPackageByIdResourceTest( - LocalV2FindPackageByIdResource resource, - FileInfo package, - PackageIdentity packageIdentity, - TestDirectory testDirectory) - { - Resource = resource; - Package = package; - PackageIdentity = packageIdentity; - _testDirectory = testDirectory; - SourceCacheContext = new SourceCacheContext(); - } - - public void Dispose() - { - SourceCacheContext.Dispose(); - _testDirectory.Dispose(); - - GC.SuppressFinalize(this); - } - - internal static LocalV2FindPackageByIdResourceTest Create() - { - var packageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); - var testDirectory = TestDirectory.Create(); - var packagesDirectory = Directory.CreateDirectory(Path.Combine(testDirectory.Path, "packages")); - var packageSource = new PackageSource(testDirectory.Path); - var package = SimpleTestPackageUtility.CreateFullPackage( - packagesDirectory.FullName, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); - var packageBytes = File.ReadAllBytes(package.FullName); - var resource = new LocalV2FindPackageByIdResource(packageSource); - - return new LocalV2FindPackageByIdResourceTest( - resource, - package, - packageIdentity, - testDirectory); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/LocalRepositories/LocalV3FindPackageByIdResourceTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/LocalRepositories/LocalV3FindPackageByIdResourceTests.cs deleted file mode 100644 index 72e9b5040e4..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/LocalRepositories/LocalV3FindPackageByIdResourceTests.cs +++ /dev/null @@ -1,562 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; -using NuGet.Test.Utility; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Tests -{ - public class LocalV3FindPackageByIdResourceTests - { - [Fact] - public void Constructor_ThrowsForNullPackageSource() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new LocalV3FindPackageByIdResource(packageSource: null)); - - Assert.Equal("packageSource", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetAllVersionsAsync_ThrowsForNullOrEmptyId(string id) - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.GetAllVersionsAsync( - id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowsForNullSourceCacheContext() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowsForNullLogger() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowIfCancelled() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ReturnsEmptyEnumerableIfPackageIdNotFound() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create(createFiles: true)) - { - var versions = await test.Resource.GetAllVersionsAsync( - id: "b", - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.Empty(versions); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ReturnsAllVersions() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create(createFiles: true)) - { - var versions = await test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Equal(new[] { test.PackageIdentity.Version }, versions); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetDependencyInfoAsync_ThrowsForNullOrEmptyId(string id) - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.GetDependencyInfoAsync( - id, - NuGetVersion.Parse("1.0.0"), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullVersion() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id, - version: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("version", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullSourceCacheContext() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullLogger() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowIfCancelled() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ReturnsNullIfPackageNotFound() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var dependencyInfo = await test.Resource.GetDependencyInfoAsync( - id: "b", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.Null(dependencyInfo); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_GetsOriginalIdentity() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create(createFiles: true)) - { - var info = await test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id.ToUpper(), - test.PackageIdentity.Version, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Equal(test.PackageIdentity.Id.ToLower(), info.PackageIdentity.Id); - Assert.Equal(test.PackageIdentity.Version, info.PackageIdentity.Version); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task CopyNupkgToStreamAsync_ThrowsForNullId(string id) - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.CopyNupkgToStreamAsync( - id, - NuGetVersion.Parse("1.0.0"), - Stream.Null, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullVersion() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - version: null, - destination: Stream.Null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("version", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullDestination() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - destination: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("destination", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullSourceCacheContext() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - Stream.Null, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullLogger() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - Stream.Null, - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsIfCancelled() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - Stream.Null, - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ReturnsFalseIfNotCopied() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create(createFiles: true)) - using (var stream = new MemoryStream()) - { - var wasCopied = await test.Resource.CopyNupkgToStreamAsync( - id: "b", - version: NuGetVersion.Parse("1.0.0"), - destination: stream, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.False(wasCopied); - Assert.Equal(0, stream.Length); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ReturnsTrueIfCopied() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create(createFiles: true)) - using (var stream = new MemoryStream()) - { - var wasCopied = await test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - stream, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.True(wasCopied); - Assert.Equal(test.Package.Length, stream.Length); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullPackageIdentity() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - packageIdentity: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullSourceCacheContext() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullLogger() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsIfCancelled() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsNullIfPackageNotFound() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create(createFiles: true)) - { - var downloader = await test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "b", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Null(downloader); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsPackageDownloaderIfPackageFound() - { - using (var test = LocalV3FindPackageByIdResourceTest.Create(createFiles: true)) - { - var downloader = await test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.IsType<LocalPackageArchiveDownloader>(downloader); - } - } - - private sealed class LocalV3FindPackageByIdResourceTest : IDisposable - { - private readonly TestDirectory _testDirectory; - - internal FileInfo Package { get; } - internal PackageIdentity PackageIdentity { get; } - internal LocalV3FindPackageByIdResource Resource { get; } - internal SourceCacheContext SourceCacheContext { get; } - - private LocalV3FindPackageByIdResourceTest( - LocalV3FindPackageByIdResource resource, - FileInfo package, - PackageIdentity packageIdentity, - TestDirectory testDirectory) - { - Resource = resource; - Package = package; - PackageIdentity = packageIdentity; - _testDirectory = testDirectory; - SourceCacheContext = new SourceCacheContext(); - } - - public void Dispose() - { - SourceCacheContext.Dispose(); - _testDirectory.Dispose(); - - GC.SuppressFinalize(this); - } - - internal static LocalV3FindPackageByIdResourceTest Create(bool createFiles = false) - { - var packageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); - var testDirectory = TestDirectory.Create(); - var packageDirectory = Directory.CreateDirectory( - Path.Combine( - testDirectory.Path, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString())); - var packageSource = new PackageSource(testDirectory.Path); - FileInfo package = null; - - // Only a few tests have outcomes that rely on the presence of these files, - // so only create them if necessary. - if (createFiles) - { - package = SimpleTestPackageUtility.CreateFullPackage( - packageDirectory.FullName, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); - - File.WriteAllText( - Path.Combine(packageDirectory.FullName, $"{packageIdentity.Id}.nuspec"), - $@"<?xml version=""1.0"" encoding=""utf-8""?> - <package> - <metadata> - <id>{packageIdentity.Id}</id> - <version>{packageIdentity.Version.ToNormalizedString()}</version> - <title /> - <frameworkAssemblies> - <frameworkAssembly assemblyName=""System.Runtime"" /> - </frameworkAssemblies> - </metadata> - </package>"); - - File.WriteAllText( - Path.Combine( - packageDirectory.FullName, - $"{packageIdentity.Id}.{packageIdentity.Version.ToNormalizedString()}.nupkg.sha512"), - string.Empty); - } - - var resource = new LocalV3FindPackageByIdResource(packageSource); - - return new LocalV3FindPackageByIdResourceTest( - resource, - package, - packageIdentity, - testDirectory); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/OffineFeedUtilityTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/OffineFeedUtilityTests.cs new file mode 100644 index 00000000000..dc970dfe7c6 --- /dev/null +++ b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/OffineFeedUtilityTests.cs @@ -0,0 +1,69 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using Xunit; +using NuGet.Protocol.Core.Types; + +namespace NuGet.Protocol.Tests +{ +//Negative tests here won't run well on *nix because bad test data used will trigger new exceptions +//TODO: we can revisit to catch them if there is value. + +#if !IS_CORECLR + public class OffineFeedUtilityTests + { + [Theory] + [InlineData("c:\\foo|<>|bar")] + [InlineData("c:\\foo|<>|bar.nupkg")] + public void OfflineFeedUtility_ThrowIfInvalid_Throws_PathInvalid(string path) + { + // Act & Assert + var expectedMessage = string.Format("'{0}' is not a valid path.", path); + + var exception + = Assert.Throws<ArgumentException>(() => OfflineFeedUtility.ThrowIfInvalid(path)); + + Assert.Equal(expectedMessage, exception.Message); + } + + [Theory] + [InlineData("http://foonugetbar.org")] + [InlineData("http://foonugetbar.org/A.nupkg")] + public void OfflineFeedUtility_ThrowIfInvalid_Throws_Path_Invalid_NotFileNotUnc(string path) + { + // Act & Assert + var expectedMessage = string.Format("'{0}' should be a local path or a UNC share path.", path); + + var exception + = Assert.Throws<ArgumentException>(() => OfflineFeedUtility.ThrowIfInvalid(path)); + + Assert.Equal(expectedMessage, exception.Message); + } + + [Theory] + [InlineData("foo\\bar")] + [InlineData("c:\\foo\\bar")] + [InlineData("\\foouncshare\\bar")] + public void OfflineFeedUtility_ThrowIfInvalid_DoesNotThrow(string path) + { + // Act & Assert that the following call does not throw + OfflineFeedUtility.ThrowIfInvalid(path); + } + + [Theory] + [InlineData("c:\\foobardoesnotexist", true)] + [InlineData("foobardoesnotexist\\A.nupkg", false)] + public void OfflineFeedUtility_ThrowIfInvalidOrNotFound_Throws(string path, bool isDirectory) + { + // Act & Assert + var exception + = Assert.Throws<ArgumentException>(() + => OfflineFeedUtility.ThrowIfInvalidOrNotFound( + path, + isDirectory, + "some exception message")); + } + } +#endif +} diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/AutomaticProgressReporterTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/AutomaticProgressReporterTests.cs deleted file mode 100644 index c5052921e4f..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/AutomaticProgressReporterTests.cs +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class AutomaticProgressReporterTests - { - [Fact] - public void Create_ThrowsForNullConnection() - { - using (var test = new AutomaticProgressReporterTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => AutomaticProgressReporter.Create( - connection: null, - request: test.Request, - interval: test.Interval, - cancellationToken: CancellationToken.None)); - - Assert.Equal("connection", exception.ParamName); - } - } - - [Fact] - public void Create_ThrowsForNullRequest() - { - using (var test = new AutomaticProgressReporterTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => AutomaticProgressReporter.Create( - test.Connection.Object, - request: null, - interval: test.Interval, - cancellationToken: CancellationToken.None)); - - Assert.Equal("request", exception.ParamName); - } - } - - [Fact] - public void Create_ThrowsForTimeSpanZero() - { - VerifyInvalidInterval(TimeSpan.Zero); - } - - [Fact] - public void Create_ThrowsForNegativeTimeSpan() - { - VerifyInvalidInterval(TimeSpan.FromSeconds(-1)); - } - - [Fact] - public void Create_ThrowsForTooLargeTimeSpan() - { - var milliseconds = int.MaxValue + 1L; - - VerifyInvalidInterval(TimeSpan.FromMilliseconds(milliseconds)); - } - - [Fact] - public void Create_ThrowsIfCancelled() - { - using (var test = new AutomaticProgressReporterTest()) - { - Assert.Throws<OperationCanceledException>( - () => AutomaticProgressReporter.Create( - test.Connection.Object, - test.Request, - test.Interval, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public void Dispose_DisposesDisposables() - { - using (var test = new AutomaticProgressReporterTest()) - { - } - } - - [Fact] - public void Dispose_DoesNotDisposeConnection() - { - var connection = new Mock<IConnection>(MockBehavior.Strict); - var request = MessageUtilities.Create( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.GetServiceIndex, - payload: new GetServiceIndexRequest(packageSourceRepository: "https://unit.test")); - - using (var reporter = AutomaticProgressReporter.Create( - connection.Object, - request, - TimeSpan.FromHours(1), - CancellationToken.None)) - { - } - - connection.Verify(); - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var test = new AutomaticProgressReporterTest()) - { - test.Reporter.Dispose(); - test.Reporter.Dispose(); - } - } - - [Fact] - public void Progress_FiredOnInterval() - { - using (var test = new AutomaticProgressReporterTest( - TimeSpan.FromMilliseconds(50), - expectedSentCount: 3)) - { - test.SentEvent.Wait(); - } - } - - private static void VerifyInvalidInterval(TimeSpan interval) - { - using (var test = new AutomaticProgressReporterTest()) - { - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => AutomaticProgressReporter.Create( - test.Connection.Object, - test.Request, - interval, - CancellationToken.None)); - - Assert.Equal("interval", exception.ParamName); - } - } - - private sealed class AutomaticProgressReporterTest : IDisposable - { - private int _actualSentCount; - private readonly int _expectedSentCount; - private bool _isDisposed; - - internal CancellationTokenSource CancellationTokenSource { get; } - internal Mock<IConnection> Connection { get; } - internal TimeSpan Interval { get; } - internal AutomaticProgressReporter Reporter { get; } - internal Message Request { get; } - internal ManualResetEventSlim SentEvent { get; } - - internal AutomaticProgressReporterTest(TimeSpan? interval = null, int expectedSentCount = 0) - { - _expectedSentCount = expectedSentCount; - - var payload = new HandshakeRequest( - ProtocolConstants.CurrentVersion, - ProtocolConstants.CurrentVersion); - - CancellationTokenSource = new CancellationTokenSource(); - Interval = interval.HasValue ? interval.Value : ProtocolConstants.MaxTimeout; - SentEvent = new ManualResetEventSlim(initialState: false); - - Connection = new Mock<IConnection>(MockBehavior.Strict); - - Connection.Setup(x => x.SendAsync( - It.IsNotNull<Message>(), - It.IsAny<CancellationToken>())) - .Callback<Message, CancellationToken>( - (message, cancellationToken) => - { - ++_actualSentCount; - - if (_actualSentCount >= expectedSentCount) - { - SentEvent.Set(); - } - }) - .Returns(Task.FromResult(0)); - - Request = MessageUtilities.Create( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Handshake, - payload: payload); - Reporter = AutomaticProgressReporter.Create( - Connection.Object, - Request, - Interval, - CancellationTokenSource.Token); - } - - public void Dispose() - { - if (!_isDisposed) - { - try - { - using (CancellationTokenSource) - { - CancellationTokenSource.Cancel(); - } - } - catch (Exception) - { - } - - Reporter.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - - var connectionTimes = _expectedSentCount == 0 ? Times.Never() : Times.AtLeast(_expectedSentCount); - - Connection.Verify(x => x.SendAsync( - It.IsNotNull<Message>(), - It.IsAny<CancellationToken>()), connectionTimes); - } - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/ConnectionOptionsTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/ConnectionOptionsTests.cs deleted file mode 100644 index e1d52f4ef64..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/ConnectionOptionsTests.cs +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class ConnectionOptionsTests - { - private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(10); - private static readonly SemanticVersion _version1_0_0 = new SemanticVersion(major: 1, minor: 0, patch: 0); - private static readonly SemanticVersion _version2_0_0 = new SemanticVersion(major: 2, minor: 0, patch: 0); - - [Fact] - public void Constructor_ThrowsForNullProtocolVersion() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new ConnectionOptions( - protocolVersion: null, - minimumProtocolVersion: _version2_0_0, - handshakeTimeout: _timeout, - requestTimeout: _timeout)); - - Assert.Equal("protocolVersion", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullMinimumProtocolVersion() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new ConnectionOptions( - _version1_0_0, - minimumProtocolVersion: null, - handshakeTimeout: _timeout, - requestTimeout: _timeout)); - - Assert.Equal("minimumProtocolVersion", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForInvalidVersionRange() - { - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new ConnectionOptions(_version1_0_0, _version2_0_0, _timeout, _timeout)); - - Assert.Equal("protocolVersion", exception.ParamName); - Assert.Equal(_version1_0_0, exception.ActualValue); - } - - [Fact] - public void Constructor_ThrowsForZeroHandshakeTimeout() - { - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new ConnectionOptions(_version2_0_0, _version1_0_0, TimeSpan.Zero, _timeout)); - - Assert.Equal("handshakeTimeout", exception.ParamName); - Assert.Equal(TimeSpan.Zero, exception.ActualValue); - } - - [Fact] - public void Constructor_ThrowsForNegativeHandshakeTimeout() - { - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new ConnectionOptions(_version2_0_0, _version1_0_0, TimeSpan.FromSeconds(-1), _timeout)); - - Assert.Equal("handshakeTimeout", exception.ParamName); - Assert.Equal(TimeSpan.FromSeconds(-1), exception.ActualValue); - } - - [Fact] - public void Constructor_ThrowsForTooLargeHandshakeTimeout() - { - var milliseconds = int.MaxValue + 1L; - - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new ConnectionOptions( - _version2_0_0, - _version1_0_0, - TimeSpan.FromMilliseconds(milliseconds), - _timeout)); - - Assert.Equal("handshakeTimeout", exception.ParamName); - Assert.Equal(TimeSpan.FromMilliseconds(milliseconds), exception.ActualValue); - } - - [Fact] - public void Constructor_ThrowsForZeroRequestTimeout() - { - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new ConnectionOptions(_version2_0_0, _version1_0_0, _timeout, TimeSpan.Zero)); - - Assert.Equal("requestTimeout", exception.ParamName); - Assert.Equal(TimeSpan.Zero, exception.ActualValue); - } - - [Fact] - public void Constructor_ThrowsForNegativeRequestTimeout() - { - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new ConnectionOptions(_version2_0_0, _version1_0_0, _timeout, TimeSpan.FromSeconds(-1))); - - Assert.Equal("requestTimeout", exception.ParamName); - Assert.Equal(TimeSpan.FromSeconds(-1), exception.ActualValue); - } - - [Fact] - public void Constructor_ThrowsForTooLargeRequestTimeout() - { - var milliseconds = int.MaxValue + 1L; - - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new ConnectionOptions( - _version2_0_0, - _version1_0_0, - _timeout, - TimeSpan.FromMilliseconds(milliseconds))); - - Assert.Equal("requestTimeout", exception.ParamName); - Assert.Equal(TimeSpan.FromMilliseconds(milliseconds), exception.ActualValue); - } - - [Fact] - public void Constructor_AcceptsEqualVersions() - { - var options = new ConnectionOptions(_version1_0_0, _version1_0_0, _timeout, _timeout); - - Assert.Equal(options.ProtocolVersion, options.MinimumProtocolVersion); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var options = new ConnectionOptions( - _version2_0_0, - _version1_0_0, - TimeSpan.FromSeconds(1), - TimeSpan.FromSeconds(2)); - - Assert.Equal(_version2_0_0, options.ProtocolVersion); - Assert.Equal(_version1_0_0, options.MinimumProtocolVersion); - Assert.Equal(TimeSpan.FromSeconds(1), options.HandshakeTimeout); - Assert.Equal(TimeSpan.FromSeconds(2), options.RequestTimeout); - } - - [Fact] - public void CreateDefault_HasCorrectProtocolVersion() - { - var options = ConnectionOptions.CreateDefault(); - - Assert.Equal(ProtocolConstants.CurrentVersion, options.ProtocolVersion); - } - - [Fact] - public void CreateDefault_HasCorrectMinimumProtocolVersion() - { - var options = ConnectionOptions.CreateDefault(); - - Assert.Equal(ProtocolConstants.CurrentVersion, options.MinimumProtocolVersion); - } - - [Fact] - public void CreateDefault_HasCorrectHandshakeTimeout() - { - var options = ConnectionOptions.CreateDefault(); - - Assert.Equal(ProtocolConstants.HandshakeTimeout, options.HandshakeTimeout); - } - - [Fact] - public void CreateDefault_HasCorrectRequestTimeoutDefault() - { - var options = ConnectionOptions.CreateDefault(); - - Assert.Equal(ProtocolConstants.RequestTimeout, options.RequestTimeout); - } - - [Fact] - public void SetRequestTimeout_ThrowsForZeroTimeout() - { - var options = ConnectionOptions.CreateDefault(); - - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => options.SetRequestTimeout(TimeSpan.Zero)); - - Assert.Equal("requestTimeout", exception.ParamName); - Assert.Equal(TimeSpan.Zero, exception.ActualValue); - } - - [Fact] - public void SetRequestTimeout_ThrowsForNegativeTimeout() - { - var options = ConnectionOptions.CreateDefault(); - - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => options.SetRequestTimeout(TimeSpan.FromSeconds(-1))); - - Assert.Equal("requestTimeout", exception.ParamName); - Assert.Equal(TimeSpan.FromSeconds(-1), exception.ActualValue); - } - - [Fact] - public void SetRequestTimeout_ThrowsForTooLargeTimeout() - { - var options = ConnectionOptions.CreateDefault(); - var milliseconds = int.MaxValue + 1L; - - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => options.SetRequestTimeout(TimeSpan.FromMilliseconds(milliseconds))); - - Assert.Equal("requestTimeout", exception.ParamName); - Assert.Equal(TimeSpan.FromMilliseconds(milliseconds), exception.ActualValue); - } - - [Fact] - public void SetRequestTimeout_UpdatesRequestTimeout() - { - var options = ConnectionOptions.CreateDefault(); - - options.SetRequestTimeout(ProtocolConstants.MaxTimeout); - - Assert.Equal(ProtocolConstants.MaxTimeout, options.RequestTimeout); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/ConnectionTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/ConnectionTests.cs deleted file mode 100644 index 813c9e219db..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/ConnectionTests.cs +++ /dev/null @@ -1,639 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Common; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class ConnectionTests - { - [Fact] - public void Constructor_ThrowsForNullDispatcher() - { - using (var cancellationTokenSource = new CancellationTokenSource()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => new Connection( - dispatcher: null, - sender: new Sender(TextWriter.Null), - receiver: new StandardInputReceiver(TextReader.Null), - options: ConnectionOptions.CreateDefault())); - - Assert.Equal("dispatcher", exception.ParamName); - } - } - - [Fact] - public void Constructor_ThrowsForNullSender() - { - using (var cancellationTokenSource = new CancellationTokenSource()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => new Connection( - new MessageDispatcher(new RequestHandlers(), new RequestIdGenerator()), - sender: null, - receiver: new StandardInputReceiver(TextReader.Null), - options: ConnectionOptions.CreateDefault())); - - Assert.Equal("sender", exception.ParamName); - } - } - - [Fact] - public void Constructor_ThrowsForNullReceiver() - { - var exception = Assert.Throws<ArgumentNullException>(() => new Connection( - new MessageDispatcher(new RequestHandlers(), new RequestIdGenerator()), - new Sender(TextWriter.Null), - receiver: null, - options: ConnectionOptions.CreateDefault())); - - Assert.Equal("receiver", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullOptions() - { - using (var cancellationTokenSource = new CancellationTokenSource()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => new Connection( - new MessageDispatcher(new RequestHandlers(), new RequestIdGenerator()), - new Sender(TextWriter.Null), - new StandardInputReceiver(TextReader.Null), - options: null)); - - Assert.Equal("options", exception.ParamName); - } - } - - [Fact] - public void Constructor_InitializesProperties() - { - var dispatcher = Mock.Of<IMessageDispatcher>(); - var sender = Mock.Of<ISender>(); - var receiver = Mock.Of<IReceiver>(); - var options = ConnectionOptions.CreateDefault(); - - using (var connection = new Connection(dispatcher, sender, receiver, options)) - { - Assert.Same(dispatcher, connection.MessageDispatcher); - Assert.Same(options, connection.Options); - Assert.Null(connection.ProtocolVersion); - Assert.Equal(ConnectionState.ReadyToConnect, connection.State); - } - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var test = new ConnectionTest()) - { - test.Connection.Dispose(); - test.Connection.Dispose(); - } - } - - [Fact] - public void Dispose_ClosesConnection() - { - using (var test = new ConnectionTest()) - { - Assert.Equal(ConnectionState.ReadyToConnect, test.Connection.State); - - test.Connection.Dispose(); - - Assert.Equal(ConnectionState.Closed, test.Connection.State); - } - } - - [Fact] - public void Dispose_DisposesDisposables() - { - using (var test = new MockConnectionTest()) - { - } - } - - [Fact] - public async Task ConnectAsync_ThrowsIfCancelled() - { - using (var cancellationTokenSource = new CancellationTokenSource()) - using (var sender = new Sender(TextWriter.Null)) - using (var receiver = new StandardInputReceiver(TextReader.Null)) - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), new RequestIdGenerator())) - using (var connection = new Connection(dispatcher, sender, receiver, ConnectionOptions.CreateDefault())) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => connection.ConnectAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task ConnectAsync_HandshakeNegotiatesProtocolVersionForIdenticalVersionRanges() - { - using (var test = new ConnectAsyncTest(ConnectionOptions.CreateDefault(), ConnectionOptions.CreateDefault())) - { - await Task.WhenAll( - test.RemoteToLocalConnection.ConnectAsync(test.CancellationToken), - test.LocalToRemoteConnection.ConnectAsync(test.CancellationToken)); - - Assert.NotNull(test.RemoteToLocalConnection.ProtocolVersion); - Assert.NotNull(test.LocalToRemoteConnection.ProtocolVersion); - Assert.Equal(test.RemoteToLocalConnection.ProtocolVersion, test.LocalToRemoteConnection.ProtocolVersion); - } - } - - [Fact] - public async Task ConnectAsync_HandshakeNegotiatesHighestCompatibleProtocolVersion() - { - var localToRemoteOptions = new ConnectionOptions( - new SemanticVersion(2, 0, 0), - new SemanticVersion(1, 0, 0), - TimeSpan.FromSeconds(10), - TimeSpan.FromSeconds(10)); - var remoteToLocalOptions = new ConnectionOptions( - new SemanticVersion(3, 0, 0), - new SemanticVersion(1, 0, 0), - TimeSpan.FromSeconds(10), - TimeSpan.FromSeconds(10)); - - using (var test = new ConnectAsyncTest(localToRemoteOptions, remoteToLocalOptions)) - { - await Task.WhenAll( - test.RemoteToLocalConnection.ConnectAsync(test.CancellationToken), - test.LocalToRemoteConnection.ConnectAsync(test.CancellationToken)); - - Assert.NotNull(test.RemoteToLocalConnection.ProtocolVersion); - Assert.NotNull(test.LocalToRemoteConnection.ProtocolVersion); - Assert.Equal(test.RemoteToLocalConnection.ProtocolVersion, test.LocalToRemoteConnection.ProtocolVersion); - Assert.Equal(test.RemoteToLocalConnection.ProtocolVersion, localToRemoteOptions.ProtocolVersion); - } - } - - [Fact] - public async Task ConnectAsync_HandshakeFailsToNegotiateProtocolVersionIfVersionRangesDoNotOverlap() - { - var localToRemoteOptions = new ConnectionOptions( - new SemanticVersion(2, 0, 0), - new SemanticVersion(2, 0, 0), - TimeSpan.FromSeconds(10), - TimeSpan.FromSeconds(10)); - var remoteToLocalOptions = new ConnectionOptions( - new SemanticVersion(1, 0, 0), - new SemanticVersion(1, 0, 0), - TimeSpan.FromSeconds(10), - TimeSpan.FromSeconds(10)); - - using (var test = new ConnectAsyncTest(localToRemoteOptions, remoteToLocalOptions)) - { - var tasks = new[] - { - test.RemoteToLocalConnection.ConnectAsync(test.CancellationToken), - test.LocalToRemoteConnection.ConnectAsync(test.CancellationToken) - }; - - await Assert.ThrowsAsync<ProtocolException>(() => Task.WhenAll(tasks)); - - Assert.NotNull(tasks[0].Exception); - Assert.NotNull(tasks[1].Exception); - - Assert.Null(test.RemoteToLocalConnection.ProtocolVersion); - Assert.Equal(ConnectionState.FailedToHandshake, test.RemoteToLocalConnection.State); - Assert.Null(test.LocalToRemoteConnection.ProtocolVersion); - Assert.Equal(ConnectionState.FailedToHandshake, test.LocalToRemoteConnection.State); - } - } - - [Fact] - public async Task ConnectAsync_HandshakeFailsToNegotiateProtocolVersionIfOnePartyFailsToRespondWithinTimeoutPeriod() - { - var protocolVersion = new SemanticVersion(1, 0, 0); - var localToRemoteOptions = new ConnectionOptions( - protocolVersion, - protocolVersion, - TimeSpan.FromSeconds(1), - TimeSpan.FromSeconds(10)); - var remoteToLocalOptions = new ConnectionOptions( - protocolVersion, - protocolVersion, - TimeSpan.FromSeconds(10), - TimeSpan.FromSeconds(10)); - - using (var test = new ConnectAsyncTest(localToRemoteOptions, remoteToLocalOptions)) - { - await Assert.ThrowsAsync<TaskCanceledException>( - () => test.LocalToRemoteConnection.ConnectAsync(test.CancellationToken)); - - Assert.Null(test.LocalToRemoteConnection.ProtocolVersion); - Assert.Equal(ConnectionState.FailedToHandshake, test.LocalToRemoteConnection.State); - } - } - - [Fact] - public void Close_ClosesCloseables() - { - var dispatcher = new Mock<IMessageDispatcher>(MockBehavior.Strict); - var sender = new Mock<ISender>(MockBehavior.Strict); - var receiver = new Mock<IReceiver>(MockBehavior.Strict); - - dispatcher.Setup(x => x.SetConnection(It.IsNotNull<IConnection>())); - dispatcher.Setup(x => x.Close()); - sender.Setup(x => x.Close()); - receiver.Setup(x => x.Close()); - - using (var connection = new Connection( - dispatcher.Object, - sender.Object, - receiver.Object, - ConnectionOptions.CreateDefault())) - { - connection.Close(); - - sender.Verify(); - receiver.Verify(); - dispatcher.Verify(); - - dispatcher.Setup(x => x.Dispose()); - sender.Setup(x => x.Dispose()); - receiver.Setup(x => x.Dispose()); - } - } - - [Fact] - public async Task Close_SetsStateToClosed() - { - using (var test = new ConnectAsyncTest(ConnectionOptions.CreateDefault(), ConnectionOptions.CreateDefault())) - { - await Task.WhenAll( - test.RemoteToLocalConnection.ConnectAsync(test.CancellationToken), - test.LocalToRemoteConnection.ConnectAsync(test.CancellationToken)); - - Assert.Equal(ConnectionState.Connected, test.LocalToRemoteConnection.State); - - test.LocalToRemoteConnection.Close(); - - Assert.Equal(ConnectionState.Closed, test.LocalToRemoteConnection.State); - } - } - - [Fact] - public async Task Faulted_RaisedForProtocolError() - { - using (var test = new ConnectAsyncTest(ConnectionOptions.CreateDefault(), ConnectionOptions.CreateDefault())) - { - await Task.WhenAll( - test.RemoteToLocalConnection.ConnectAsync(test.CancellationToken), - test.LocalToRemoteConnection.ConnectAsync(test.CancellationToken)); - - using (var faultedEvent = new ManualResetEventSlim(initialState: false)) - { - ProtocolErrorEventArgs args = null; - - test.LocalToRemoteConnection.Faulted += (object sender, ProtocolErrorEventArgs e) => - { - args = e; - - faultedEvent.Set(); - }; - - test.LocalToRemoteConnection.MessageDispatcher.RequestHandlers.TryAdd( - MessageMethod.Initialize, - new RequestHandler<InitializeResponse>(new InitializeResponse(MessageResponseCode.Success))); - - var message = new Message( - requestId: "a", - type: MessageType.Response, - method: MessageMethod.Initialize); - - await test.RemoteToLocalConnection.SendAsync(message, test.CancellationToken); - - faultedEvent.Wait(); - - Assert.NotNull(args); - Assert.IsType<ProtocolException>(args.Exception); - Assert.NotNull(args.Message); - Assert.Equal(message.RequestId, args.Message.RequestId); - Assert.Equal(message.Type, args.Message.Type); - Assert.Equal(message.Method, args.Message.Method); - } - } - } - - [Fact] - public async Task MessageReceived_RaisedForInboundMessage() - { - using (var test = new ConnectAsyncTest(ConnectionOptions.CreateDefault(), ConnectionOptions.CreateDefault())) - { - await Task.WhenAll( - test.RemoteToLocalConnection.ConnectAsync(test.CancellationToken), - test.LocalToRemoteConnection.ConnectAsync(test.CancellationToken)); - - using (var messageReceivedEvent = new ManualResetEventSlim(initialState: false)) - { - MessageEventArgs args = null; - - test.LocalToRemoteConnection.MessageReceived += (object sender, MessageEventArgs e) => - { - args = e; - - messageReceivedEvent.Set(); - }; - - test.LocalToRemoteConnection.MessageDispatcher.RequestHandlers.TryAdd( - MessageMethod.Initialize, - new RequestHandler<InitializeResponse>(new InitializeResponse(MessageResponseCode.Success))); - - var message = new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Initialize); - - await test.RemoteToLocalConnection.SendAsync(message, test.CancellationToken); - - messageReceivedEvent.Wait(); - - Assert.NotNull(args); - Assert.NotNull(args.Message); - Assert.Equal(message.RequestId, args.Message.RequestId); - Assert.Equal(message.Type, args.Message.Type); - Assert.Equal(message.Method, args.Message.Method); - } - } - } - - [Fact] - public async Task SendAsync_ThrowsForNullMessage() - { - using (var test = new ConnectionTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Connection.SendAsync(message: null, cancellationToken: CancellationToken.None)); - - Assert.Equal("message", exception.ParamName); - } - } - - [Fact] - public async Task SendAsync_ThrowsIfCancelled() - { - var message = new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Initialize); - - using (var test = new ConnectionTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Connection.SendAsync(message, new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task SendAsync_ThrowsIfNotConnected() - { - var message = new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Initialize); - - using (var test = new ConnectionTest()) - { - await Assert.ThrowsAsync<InvalidOperationException>( - () => test.Connection.SendAsync(message, CancellationToken.None)); - } - } - - [Fact] - public async Task SendAsync_NoOpsIfClosed() - { - using (var test = new MockConnectionTest()) - { - var message = new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Initialize); - - test.Connection.Close(); - - await test.Connection.SendAsync(message, CancellationToken.None); - } - } - - [Fact] - public async Task SendRequestAndReceiveResponseAsync_ThrowsIfNotConnected() - { - using (var test = new ConnectionTest()) - { - await Assert.ThrowsAsync<InvalidOperationException>( - () => test.Connection.SendRequestAndReceiveResponseAsync<HandshakeRequest, HandshakeResponse>( - MessageMethod.Handshake, - new HandshakeRequest(ProtocolConstants.CurrentVersion, ProtocolConstants.CurrentVersion), - CancellationToken.None)); - } - } - - [Fact] - public async Task SendRequestAndReceiveResponseAsync_ThrowsIfCancelled() - { - using (var test = new ConnectAsyncTest(ConnectionOptions.CreateDefault(), ConnectionOptions.CreateDefault())) - { - await Task.WhenAll( - test.RemoteToLocalConnection.ConnectAsync(test.CancellationToken), - test.LocalToRemoteConnection.ConnectAsync(test.CancellationToken)); - - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.LocalToRemoteConnection.SendRequestAndReceiveResponseAsync<LogRequest, LogResponse>( - MessageMethod.Log, - new LogRequest(LogLevel.Debug, "a"), - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task SendRequestAndReceiveResponseAsync_NoOpsIfClosed() - { - using (var test = new MockConnectionTest()) - { - var message = new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Initialize); - - test.Connection.Close(); - - var response = await test.Connection.SendRequestAndReceiveResponseAsync<HandshakeRequest, HandshakeResponse>( - MessageMethod.Handshake, - new HandshakeRequest(ProtocolConstants.CurrentVersion, ProtocolConstants.CurrentVersion), - CancellationToken.None); - - Assert.Null(response); - } - } - - private sealed class ConnectAsyncTest : IDisposable - { - private readonly CancellationTokenSource _combinedCancellationTokenSource; - private readonly SimulatedIpc _simulatedIpc; - private readonly Sender _remoteSender; - private readonly Receiver _remoteReceiver; - private readonly MessageDispatcher _remoteDispatcher; - private readonly Sender _localSender; - private readonly Receiver _localReceiver; - private readonly MessageDispatcher _localDispatcher; - private bool _isDisposed; - - internal Connection RemoteToLocalConnection { get; } - internal Connection LocalToRemoteConnection { get; } - internal CancellationToken CancellationToken { get; } - - internal ConnectAsyncTest(ConnectionOptions localToRemoteOptions, ConnectionOptions remoteToLocalOptions) - { - _combinedCancellationTokenSource = new CancellationTokenSource(); - _simulatedIpc = SimulatedIpc.Create(_combinedCancellationTokenSource.Token); - _remoteSender = new Sender(_simulatedIpc.RemoteStandardOutputForRemote); - _remoteReceiver = new StandardInputReceiver(_simulatedIpc.RemoteStandardInputForRemote); - _remoteDispatcher = new MessageDispatcher(new RequestHandlers(), new RequestIdGenerator()); - LocalToRemoteConnection = new Connection(_remoteDispatcher, _remoteSender, _remoteReceiver, localToRemoteOptions); - _localSender = new Sender(_simulatedIpc.RemoteStandardInputForLocal); - _localReceiver = new StandardInputReceiver(_simulatedIpc.RemoteStandardOutputForLocal); - _localDispatcher = new MessageDispatcher(new RequestHandlers(), new RequestIdGenerator()); - RemoteToLocalConnection = new Connection(_localDispatcher, _localSender, _localReceiver, remoteToLocalOptions); - CancellationToken = _combinedCancellationTokenSource.Token; - } - - public void Dispose() - { - if (_isDisposed) - { - return; - } - - using (_combinedCancellationTokenSource) - { - _combinedCancellationTokenSource.Cancel(); - - LocalToRemoteConnection.Dispose(); - RemoteToLocalConnection.Dispose(); - _simulatedIpc.Dispose(); - - // Other IDisposable fields should be disposed by the connections. - } - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - private sealed class ConnectionTest : IDisposable - { - private readonly SimulatedIpc _simulatedIpc; - private bool _isDisposed; - - internal Connection Connection { get; } - - internal ConnectionTest() - { - var cancellationTokenSource = new CancellationTokenSource(); - _simulatedIpc = SimulatedIpc.Create(cancellationTokenSource.Token); - var sender = new Sender(_simulatedIpc.RemoteStandardOutputForRemote); - var receiver = new StandardInputReceiver(_simulatedIpc.RemoteStandardInputForRemote); - var dispatcher = new MessageDispatcher(new RequestHandlers(), new RequestIdGenerator()); - var options = ConnectionOptions.CreateDefault(); - Connection = new Connection(dispatcher, sender, receiver, options); - } - - public void Dispose() - { - if (_isDisposed) - { - return; - } - - _simulatedIpc.Dispose(); - Connection.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - private sealed class MockConnectionTest : IDisposable - { - internal Connection Connection { get; } - internal Mock<IMessageDispatcher> Dispatcher { get; } - internal Mock<ISender> Sender { get; } - internal Mock<IReceiver> Receiver { get; } - - internal MockConnectionTest() - { - Dispatcher = new Mock<IMessageDispatcher>(MockBehavior.Strict); - Sender = new Mock<ISender>(MockBehavior.Strict); - Receiver = new Mock<IReceiver>(MockBehavior.Strict); - - Dispatcher.Setup(x => x.SetConnection(It.IsNotNull<IConnection>())); - Dispatcher.Setup(x => x.Close()); - Dispatcher.Setup(x => x.Dispose()); - Sender.Setup(x => x.Close()); - Sender.Setup(x => x.Dispose()); - Receiver.Setup(x => x.Close()); - Receiver.Setup(x => x.Dispose()); - - Connection = new Connection( - Dispatcher.Object, - Sender.Object, - Receiver.Object, - ConnectionOptions.CreateDefault()); - } - - public void Dispose() - { - Connection.Dispose(); - - Dispatcher.Verify(); - Sender.Verify(); - Receiver.Verify(); - } - } - - private sealed class RequestHandler<TPayload> : IRequestHandler - where TPayload : class - { - private readonly TPayload _payload; - - public CancellationToken CancellationToken => CancellationToken.None; - - internal RequestHandler(TPayload payload) - { - _payload = payload; - } - - public Task HandleCancelAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - throw new NotImplementedException(); - } - - public Task HandleResponseAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - return responseHandler.SendResponseAsync(request, _payload, cancellationToken); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/DownloadResourcePluginProviderTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/DownloadResourcePluginProviderTests.cs deleted file mode 100644 index cbe5d307a3d..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/DownloadResourcePluginProviderTests.cs +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using Newtonsoft.Json.Linq; -using NuGet.Configuration; -using NuGet.Protocol.Core.Types; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class DownloadResourcePluginProviderTests - { - private readonly DownloadResourcePluginProvider _provider; - - private static readonly PluginResource _pluginResource = new PluginResource( - Enumerable.Empty<PluginCreationResult>(), - new PackageSource("https://unit.test"), - Mock.Of<ICredentialService>()); - - public DownloadResourcePluginProviderTests() - { - _provider = new DownloadResourcePluginProvider(); - - HttpHandlerResourceV3.CredentialService = Mock.Of<ICredentialService>(); - } - - [Fact] - public void Before_IsBeforeDownloadResourceV3Provider() - { - Assert.Equal(new[] { nameof(DownloadResourceV3Provider) }, _provider.Before); - } - - [Fact] - public void After_IsEmpty() - { - Assert.Empty(_provider.After); - } - - [Fact] - public void Name_IsDownloadResourceV3PluginProvider() - { - Assert.Equal(nameof(DownloadResourcePluginProvider), _provider.Name); - } - - [Fact] - public void ResourceType_IsDownloadResource() - { - Assert.Equal(typeof(DownloadResource), _provider.ResourceType); - } - - [Fact] - public async Task TryCreate_ThrowsForNullSource() - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => _provider.TryCreate(source: null, cancellationToken: CancellationToken.None)); - - Assert.Equal("source", exception.ParamName); - } - - [Fact] - public async Task TryCreate_ThrowsIfCancelled() - { - var sourceRepository = CreateSourceRepository( - createPluginResource: true, - createServiceIndexResourceV3: true, - createHttpHandlerResource: true); - - await Assert.ThrowsAsync<OperationCanceledException>( - () => _provider.TryCreate(sourceRepository, new CancellationToken(canceled: true))); - } - - [Fact] - public async Task TryCreate_ReturnsFalseIfNoPluginResource() - { - var sourceRepository = CreateSourceRepository( - createPluginResource: false, - createServiceIndexResourceV3: true, - createHttpHandlerResource: true); - - var result = await _provider.TryCreate(sourceRepository, CancellationToken.None); - - Assert.False(result.Item1); - Assert.Null(result.Item2); - } - - [Fact] - public async Task TryCreate_ReturnsFalseIfNoServiceIndexResourceV3() - { - var sourceRepository = CreateSourceRepository( - createPluginResource: true, - createServiceIndexResourceV3: false, - createHttpHandlerResource: true); - - var result = await _provider.TryCreate(sourceRepository, CancellationToken.None); - - Assert.False(result.Item1); - Assert.Null(result.Item2); - } - - [Fact] - public async Task TryCreate_ReturnsFalseIfNoHttpHandlerResource() - { - var sourceRepository = CreateSourceRepository( - createPluginResource: true, - createServiceIndexResourceV3: true, - createHttpHandlerResource: false); - - var result = await _provider.TryCreate(sourceRepository, CancellationToken.None); - - Assert.False(result.Item1); - Assert.Null(result.Item2); - } - - [Fact] - public async Task TryCreate_ReturnsDownloadResourcePlugin() - { - var sourceRepository = CreateSourceRepository( - createPluginResource: true, - createServiceIndexResourceV3: true, - createHttpHandlerResource: true); - - var result = await _provider.TryCreate(sourceRepository, CancellationToken.None); - - Assert.True(result.Item1); - Assert.IsType<DownloadResourcePlugin>(result.Item2); - } - - private static SourceRepository CreateSourceRepository( - bool createPluginResource, - bool createServiceIndexResourceV3, - bool createHttpHandlerResource) - { - var packageSource = new PackageSource(source: "https://unit.test"); - var providers = new INuGetResourceProvider[] - { - CreatePluginResourceProvider(createPluginResource), - CreateServiceIndexResourceV3Provider(createServiceIndexResourceV3), - CreateMockHttpHandlerResource(createHttpHandlerResource) - }; - - return new SourceRepository(packageSource, providers); - } - - private static HttpHandlerResourceV3Provider CreateMockHttpHandlerResource(bool createResource) - { - var provider = new Mock<HttpHandlerResourceV3Provider>(); - - provider.Setup(x => x.Name) - .Returns(nameof(HttpHandlerResourceV3Provider)); - provider.Setup(x => x.ResourceType) - .Returns(typeof(HttpHandlerResource)); - - HttpHandlerResource resource = null; - - if (createResource) - { - resource = Mock.Of<HttpHandlerResource>(); - } - - var tryCreateResult = new Tuple<bool, INuGetResource>(resource != null, resource); - - provider.Setup(x => x.TryCreate(It.IsAny<SourceRepository>(), It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(tryCreateResult)); - - return provider.Object; - } - - private static PluginResourceProvider CreatePluginResourceProvider(bool createResource) - { - var provider = new Mock<PluginResourceProvider>(); - - provider.Setup(x => x.Name) - .Returns(nameof(PluginResourceProvider)); - provider.Setup(x => x.ResourceType) - .Returns(typeof(PluginResource)); - - PluginResource pluginResource = null; - - if (createResource) - { - var plugin = new Mock<IPlugin>(); - var utilities = new Mock<IPluginMulticlientUtilities>(); - var connection = new Mock<IConnection>(); - var dispatcher = new Mock<IMessageDispatcher>(); - - dispatcher.SetupGet(x => x.RequestHandlers) - .Returns(new RequestHandlers()); - - connection.SetupGet(x => x.MessageDispatcher) - .Returns(dispatcher.Object); - - plugin.Setup(x => x.Connection) - .Returns(connection.Object); - - var creationResult = new PluginCreationResult( - plugin.Object, - utilities.Object, - new List<OperationClaim>() { OperationClaim.DownloadPackage }); - var packageSource = new PackageSource(source: "https://unit.test"); - - pluginResource = new PluginResource( - new[] { creationResult }, - packageSource, - Mock.Of<ICredentialService>()); - } - - var tryCreateResult = new Tuple<bool, INuGetResource>(pluginResource != null, pluginResource); - - provider.Setup(x => x.TryCreate(It.IsAny<SourceRepository>(), It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(tryCreateResult)); - - return provider.Object; - } - - private static ServiceIndexResourceV3Provider CreateServiceIndexResourceV3Provider(bool createResource) - { - var provider = new Mock<ServiceIndexResourceV3Provider>(); - - provider.Setup(x => x.Name) - .Returns(nameof(ServiceIndexResourceV3Provider)); - provider.Setup(x => x.ResourceType) - .Returns(typeof(ServiceIndexResourceV3)); - - var serviceIndexResource = createResource - ? new ServiceIndexResourceV3(JObject.Parse("{}"), DateTime.UtcNow) : null; - var tryCreateResult = new Tuple<bool, INuGetResource>(serviceIndexResource != null, serviceIndexResource); - - provider.Setup(x => x.TryCreate(It.IsAny<SourceRepository>(), It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(tryCreateResult)); - - return provider.Object; - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/DownloadResourcePluginTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/DownloadResourcePluginTests.cs deleted file mode 100644 index 23e665db672..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/DownloadResourcePluginTests.cs +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class DownloadResourcePluginTests - { - private readonly Mock<IConnection> _connection; - private readonly Mock<ICredentialService> _credentialService; - private readonly Mock<IMessageDispatcher> _dispatcher; - private readonly PackageSource _packageSource; - private readonly Mock<IPlugin> _plugin; - private readonly Mock<IWebProxy> _proxy; - private readonly DownloadResourcePlugin _resource; - private readonly Mock<IPluginMulticlientUtilities> _utilities; - - public DownloadResourcePluginTests() - { - _packageSource = new PackageSource("https://unit.test"); - _proxy = new Mock<IWebProxy>(); - _credentialService = new Mock<ICredentialService>(); - _dispatcher = new Mock<IMessageDispatcher>(); - _connection = new Mock<IConnection>(); - _plugin = new Mock<IPlugin>(); - _utilities = new Mock<IPluginMulticlientUtilities>(); - - _dispatcher.SetupGet(x => x.RequestHandlers) - .Returns(new RequestHandlers()); - - _connection.SetupGet(x => x.MessageDispatcher) - .Returns(_dispatcher.Object); - - _plugin.SetupGet(x => x.Connection) - .Returns(_connection.Object); - - _resource = new DownloadResourcePlugin( - _plugin.Object, - _utilities.Object, - _packageSource); - } - - [Fact] - public void Constructor_ThrowsForNullPlugin() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new DownloadResourcePlugin( - plugin: null, - utilities: _utilities.Object, - packageSource: _packageSource)); - - Assert.Equal("plugin", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullPluginMulticlientUtilities() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new DownloadResourcePlugin( - _plugin.Object, - utilities: null, - packageSource: _packageSource)); - - Assert.Equal("utilities", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullPackageSource() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new DownloadResourcePlugin( - _plugin.Object, - _utilities.Object, - packageSource: null)); - - Assert.Equal("packageSource", exception.ParamName); - } - - [Fact] - public async Task GetDownloadResourceResultAsync_ThrowsForNullIdentity() - { - using (var sourceCacheContext = new SourceCacheContext()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => _resource.GetDownloadResourceResultAsync( - identity: null, - downloadContext: new PackageDownloadContext(sourceCacheContext), - globalPackagesFolder: "", - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("identity", exception.ParamName); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_ThrowsForNullDownloadContext() - { - var resource = new DownloadResourcePlugin( - _plugin.Object, - _utilities.Object, - _packageSource); - - using (var sourceCacheContext = new SourceCacheContext()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => resource.GetDownloadResourceResultAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - downloadContext: null, - globalPackagesFolder: "", - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("downloadContext", exception.ParamName); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_ThrowsForNullLogger() - { - using (var sourceCacheContext = new SourceCacheContext()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => _resource.GetDownloadResourceResultAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - new PackageDownloadContext(sourceCacheContext), - globalPackagesFolder: "", - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_ThrowsIfCancelled() - { - using (var sourceCacheContext = new SourceCacheContext()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => _resource.GetDownloadResourceResultAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - new PackageDownloadContext(sourceCacheContext), - globalPackagesFolder: "", - logger: NullLogger.Instance, - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_ThrowsForErrorPrefetchPackageResponse() - { - _connection.Setup(x => x.SendRequestAndReceiveResponseAsync<PrefetchPackageRequest, PrefetchPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.PrefetchPackage), - It.IsNotNull<PrefetchPackageRequest>(), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new PrefetchPackageResponse(MessageResponseCode.Error)); - - using (var sourceCacheContext = new SourceCacheContext()) - { - await Assert.ThrowsAsync<PluginException>( - () => _resource.GetDownloadResourceResultAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - new PackageDownloadContext(sourceCacheContext), - globalPackagesFolder: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_ReturnsDownloadResourceResultForSuccessfulPrefetchPackageResponse() - { - _connection.Setup(x => x.SendRequestAndReceiveResponseAsync<PrefetchPackageRequest, PrefetchPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.PrefetchPackage), - It.IsNotNull<PrefetchPackageRequest>(), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new PrefetchPackageResponse(MessageResponseCode.Success)); - - using (var sourceCacheContext = new SourceCacheContext()) - using (var result = await _resource.GetDownloadResourceResultAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - new PackageDownloadContext(sourceCacheContext), - globalPackagesFolder: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)) - { - Assert.NotNull(result); - Assert.Equal(DownloadResourceResultStatus.AvailableWithoutStream, result.Status); - Assert.IsType<PluginPackageReader>(result.PackageReader); - Assert.Null(result.PackageStream); - Assert.Equal(_packageSource.Source, result.PackageSource); - } - } - - [Fact] - public async Task GetDownloadResourceResultAsync_ReturnsDownloadResourceResultForNotFoundPrefetchPackageResponse() - { - _connection.Setup(x => x.SendRequestAndReceiveResponseAsync<PrefetchPackageRequest, PrefetchPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.PrefetchPackage), - It.IsNotNull<PrefetchPackageRequest>(), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new PrefetchPackageResponse(MessageResponseCode.NotFound)); - - using (var sourceCacheContext = new SourceCacheContext()) - using (var result = await _resource.GetDownloadResourceResultAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - new PackageDownloadContext(sourceCacheContext), - globalPackagesFolder: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)) - { - Assert.NotNull(result); - Assert.Equal(DownloadResourceResultStatus.NotFound, result.Status); - Assert.Null(result.PackageReader); - Assert.Null(result.PackageStream); - Assert.Null(result.PackageSource); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/EmbeddedSignatureVerifierTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/EmbeddedSignatureVerifierTests.cs deleted file mode 100644 index 1ee597488bd..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/EmbeddedSignatureVerifierTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using NuGet.Test.Utility; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class EmbeddedSignatureVerifierTests - { - [PlatformFact(Platform.Windows)] - public void Create_ReturnsWindowsEmbeddedSignatureVerifierOnWindows() - { - var verifier = EmbeddedSignatureVerifier.Create(); - - Assert.IsType<WindowsEmbeddedSignatureVerifier>(verifier); - } - - [PlatformFact(Platform.Darwin)] - public void Create_ReturnsFallbackEmbeddedSignatureVerifierOnMacOS() - { - var verifier = EmbeddedSignatureVerifier.Create(); - - Assert.IsType<FallbackEmbeddedSignatureVerifier>(verifier); - } - - [PlatformFact(Platform.Linux)] - public void Create_ReturnsFallbackEmbeddedSignatureVerifierOnLinux() - { - var verifier = EmbeddedSignatureVerifier.Create(); - - Assert.IsType<FallbackEmbeddedSignatureVerifier>(verifier); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/FallbackEmbeddedSignatureVerifierTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/FallbackEmbeddedSignatureVerifierTests.cs deleted file mode 100644 index 07011532361..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/FallbackEmbeddedSignatureVerifierTests.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class FallbackEmbeddedSignatureVerifierTests - { - [Fact] - public void IsValid_Throws() - { - var verifier = new FallbackEmbeddedSignatureVerifier(); - - Assert.Throws<PlatformNotSupportedException>(() => verifier.IsValid(filePath: "a")); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedIpc.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedIpc.cs deleted file mode 100644 index cd9b3d99aab..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedIpc.cs +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; - -namespace NuGet.Protocol.Plugins.Tests -{ - internal sealed class SimulatedIpc : IDisposable - { - private readonly CancellationTokenSource _cancellationTokenSource; - private bool _isDisposed; - - internal SimulatedStreamWriter RemoteStandardInputForLocal { get; } - internal SimulatedStreamReader RemoteStandardInputForRemote { get; } - internal SimulatedStreamWriter RemoteStandardOutputForRemote { get; } - internal SimulatedStreamReader RemoteStandardOutputForLocal { get; } - - private SimulatedIpc( - SimulatedStreamWriter remoteStandardInputForLocal, - SimulatedStreamReader remoteStandardInputForRemote, - SimulatedStreamWriter remoteStandardOutputForRemote, - SimulatedStreamReader remoteStandardOutputForLocal, - CancellationTokenSource cancellationTokenSource) - { - RemoteStandardInputForLocal = remoteStandardInputForLocal; - RemoteStandardInputForRemote = remoteStandardInputForRemote; - RemoteStandardOutputForRemote = remoteStandardOutputForRemote; - RemoteStandardOutputForLocal = remoteStandardOutputForLocal; - _cancellationTokenSource = cancellationTokenSource; - } - - internal static SimulatedIpc Create(CancellationToken cancellationToken) - { - SimulatedStreamWriter remoteStandardInputForLocal; - SimulatedStreamReader remoteStandardInputForRemote; - SimulatedStreamWriter remoteStandardOutputForRemote; - SimulatedStreamReader remoteStandardOutputForLocal; - - var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - - CreateSimulatedIpcChannel(cancellationTokenSource.Token, out remoteStandardInputForLocal, out remoteStandardInputForRemote); - CreateSimulatedIpcChannel(cancellationTokenSource.Token, out remoteStandardOutputForRemote, out remoteStandardOutputForLocal); - - return new SimulatedIpc( - remoteStandardInputForLocal, - remoteStandardInputForRemote, - remoteStandardOutputForRemote, - remoteStandardOutputForLocal, - cancellationTokenSource); - } - - private static void CreateSimulatedIpcChannel(CancellationToken cancellationToken, out SimulatedStreamWriter streamWriter, out SimulatedStreamReader streamReader) - { - var memoryStream = new MemoryStream(); - var readWriteSemaphore = new SemaphoreSlim(initialCount: 1, maxCount: 1); - var dataWrittenEvent = new ManualResetEventSlim(initialState: false); - - var inboundStream = new SimulatedReadOnlyFileStream(memoryStream, readWriteSemaphore, dataWrittenEvent, cancellationToken); - var outboundStream = new SimulatedWriteOnlyFileStream(memoryStream, readWriteSemaphore, dataWrittenEvent, cancellationToken); - - streamWriter = new SimulatedStreamWriter(outboundStream); - streamReader = new SimulatedStreamReader(inboundStream); - } - - public void Dispose() - { - if (_isDisposed) - { - return; - } - - using (_cancellationTokenSource) - { - _cancellationTokenSource.Cancel(); - } - - RemoteStandardInputForLocal.Dispose(); - RemoteStandardInputForRemote.Dispose(); - RemoteStandardOutputForRemote.Dispose(); - RemoteStandardOutputForLocal.Dispose(); - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedReadOnlyFileStream.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedReadOnlyFileStream.cs deleted file mode 100644 index 3eec371ce35..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedReadOnlyFileStream.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; - -namespace NuGet.Protocol.Plugins.Tests -{ - internal sealed class SimulatedReadOnlyFileStream : Stream - { - private readonly CancellationToken _cancellationToken; - private readonly ManualResetEventSlim _dataWrittenEvent; - private readonly MemoryStream _stream; - private readonly SemaphoreSlim _readWriteSemaphore; - - public override bool CanRead => true; - public override bool CanSeek => false; - public override bool CanTimeout => false; - public override bool CanWrite => false; - public override long Length => throw new NotSupportedException(); - public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } - public override int ReadTimeout { get => throw new InvalidOperationException(); set => throw new InvalidOperationException(); } - public override int WriteTimeout { get => throw new InvalidOperationException(); set => throw new InvalidOperationException(); } - - internal SimulatedReadOnlyFileStream( - MemoryStream stream, - SemaphoreSlim readWriteSemaphore, - ManualResetEventSlim dataWrittenEvent, - CancellationToken cancellationToken) - { - _stream = stream; - _readWriteSemaphore = readWriteSemaphore; - _dataWrittenEvent = dataWrittenEvent; - _cancellationToken = cancellationToken; - } - - public override void Flush() - { - } - - public override int Read(byte[] buffer, int offset, int count) - { - _dataWrittenEvent.Wait(_cancellationToken); - - try - { - _readWriteSemaphore.Wait(_cancellationToken); - - return _stream.Read(buffer, offset, count); - } - finally - { - if (_stream.Position == _stream.Length) - { - _dataWrittenEvent.Reset(); - } - - _readWriteSemaphore.Release(); - } - } - - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotSupportedException(); - } - - public override void SetLength(long value) - { - throw new NotSupportedException(); - } - - public override void Write(byte[] buffer, int offset, int count) - { - throw new NotSupportedException(); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedStreamReader.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedStreamReader.cs deleted file mode 100644 index b20b4478dad..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedStreamReader.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.IO; -using System.Text; - -namespace NuGet.Protocol.Plugins.Tests -{ - internal sealed class SimulatedStreamReader : StreamReader - { - internal SimulatedStreamReader(Stream stream) - : base(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 4096, leaveOpen: true) - { - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedStreamWriter.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedStreamWriter.cs deleted file mode 100644 index 88ccb8d8267..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedStreamWriter.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.IO; -using System.Text; - -namespace NuGet.Protocol.Plugins.Tests -{ - internal sealed class SimulatedStreamWriter : StreamWriter - { - internal SimulatedStreamWriter(Stream stream) - : base(stream, Encoding.UTF8, bufferSize: 4096, leaveOpen: true) - { - AutoFlush = true; - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedWriteOnlyFileStream.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedWriteOnlyFileStream.cs deleted file mode 100644 index dc8b4bfc4a9..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/SimulatedWriteOnlyFileStream.cs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; - -namespace NuGet.Protocol.Plugins.Tests -{ - internal sealed class SimulatedWriteOnlyFileStream : Stream - { - private readonly CancellationToken _cancellationToken; - private readonly ManualResetEventSlim _dataWrittenEvent; - private readonly MemoryStream _stream; - private readonly SemaphoreSlim _readWriteSemaphore; - private long _writePosition; - - public override bool CanRead => false; - public override bool CanSeek => false; - public override bool CanTimeout => false; - public override bool CanWrite => true; - public override long Length => throw new NotSupportedException(); - public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } - public override int ReadTimeout { get => throw new InvalidOperationException(); set => throw new InvalidOperationException(); } - public override int WriteTimeout { get => throw new InvalidOperationException(); set => throw new InvalidOperationException(); } - - internal SimulatedWriteOnlyFileStream( - MemoryStream stream, - SemaphoreSlim readWriteSemaphore, - ManualResetEventSlim dataWrittenEvent, - CancellationToken cancellationToken) - { - _stream = stream; - _readWriteSemaphore = readWriteSemaphore; - _dataWrittenEvent = dataWrittenEvent; - _cancellationToken = cancellationToken; - } - - public override void Flush() - { - } - - public override int Read(byte[] buffer, int offset, int count) - { - throw new NotSupportedException(); - } - - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotSupportedException(); - } - - public override void SetLength(long value) - { - throw new NotSupportedException(); - } - - public override void Write(byte[] buffer, int offset, int count) - { - try - { - _readWriteSemaphore.Wait(_cancellationToken); - - //System.Diagnostics.Debug.WriteLine($"Position: {_stream.Position}. Length: {_stream.Length}. Writing..."); - - if (_stream.Position == _writePosition) - { - // Read has caught up with write. - // Reset the stream so it doesn't grow indefinitely. - _stream.Position = 0; - _stream.SetLength(0); - _writePosition = 0; - - //System.Diagnostics.Debug.WriteLine($"Position: {_stream.Position}. Length: {_stream.Length}. Reset stream."); - } - - var readPosition = _stream.Position; - - _stream.Position = _writePosition; - - _stream.Write(buffer, offset, count); - - _writePosition = _stream.Position; - - _stream.Position = readPosition; - - //System.Diagnostics.Debug.WriteLine($"Position: {_stream.Position}. Length: {_stream.Length}. Wrote {count} bytes."); - - _dataWrittenEvent.Set(); - } - finally - { - _readWriteSemaphore.Release(); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/TestUtilities.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/TestUtilities.cs deleted file mode 100644 index b434fddbd25..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Helpers/TestUtilities.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.IO; -using Newtonsoft.Json; - -namespace NuGet.Protocol.Plugins.Tests -{ - internal static class TestUtilities - { - internal static string Serialize(object value) - { - using (var stringWriter = new StringWriter()) - using (var jsonWriter = new JsonTextWriter(stringWriter)) - { - JsonSerializationUtilities.Serialize(jsonWriter, value); - - return stringWriter.ToString(); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/InboundRequestContextTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/InboundRequestContextTests.cs deleted file mode 100644 index 75ac4e5b10e..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/InboundRequestContextTests.cs +++ /dev/null @@ -1,481 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class InboundRequestContextTests - { - [Fact] - public void Constructor_ThrowsForNullConnection() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new InboundRequestContext( - connection: null, - requestId: "a", - cancellationToken: CancellationToken.None)); - - Assert.Equal("connection", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyRequestId(string requestId) - { - var exception = Assert.Throws<ArgumentException>( - () => new InboundRequestContext( - Mock.Of<IConnection>(), - requestId, - CancellationToken.None)); - - Assert.Equal("requestId", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesRequestIdProperty() - { - using (var test = new InboundRequestContextTest()) - { - Assert.Equal(test.RequestId, test.Context.RequestId); - } - } - - [Fact] - public void Dispose_DoesNotDisposeConnection() - { - using (var test = new InboundRequestContextTest()) - { - test.Context.Dispose(); - test.Connection.Verify(); - } - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var test = new InboundRequestContextTest()) - { - test.Context.Dispose(); - test.Context.Dispose(); - } - } - - [Fact] - public void BeginCancelAsync_ThrowsForNullRequest() - { - using (var test = new InboundRequestContextTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => test.Context.BeginCancelAsync( - request: null, - requestHandler: Mock.Of<IRequestHandler>(), - responseHandler: Mock.Of<IResponseHandler>())); - - Assert.Equal("request", exception.ParamName); - } - } - - [Fact] - public void BeginCancelAsync_ThrowsForNullRequestHandler() - { - using (var test = new InboundRequestContextTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => test.Context.BeginCancelAsync( - new Message( - test.RequestId, - MessageType.Request, - MessageMethod.GetOperationClaims, - payload: null), - requestHandler: null, - responseHandler: Mock.Of<IResponseHandler>())); - - Assert.Equal("requestHandler", exception.ParamName); - } - } - - [Fact] - public void BeginCancelAsync_ThrowsForNullResponseHandler() - { - using (var test = new InboundRequestContextTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => test.Context.BeginCancelAsync( - new Message( - test.RequestId, - type: MessageType.Request, - method: MessageMethod.GetOperationClaims, - payload: null), - requestHandler: Mock.Of<IRequestHandler>(), - responseHandler: null)); - - Assert.Equal("responseHandler", exception.ParamName); - } - } - - [Fact] - public void BeginCancelAsync_CallsRequestHandler() - { - using (var test = new InboundRequestContextTest()) - using (var handledEvent = new ManualResetEventSlim(initialState: false)) - { - var requestHandler = new Mock<IRequestHandler>(MockBehavior.Strict); - - requestHandler.Setup(x => x.HandleCancelAsync( - It.IsNotNull<IConnection>(), - It.IsNotNull<Message>(), - It.IsNotNull<IResponseHandler>(), - It.IsAny<CancellationToken>())) - .Callback<IConnection, Message, IResponseHandler, CancellationToken>( - (connection, message, responseHandler, cancellationToken) => - { - handledEvent.Set(); - }) - .Returns(Task.FromResult(0)); - - test.Context.BeginCancelAsync( - new Message( - test.RequestId, - MessageType.Request, - MessageMethod.GetOperationClaims, - payload: null), - requestHandler.Object, - Mock.Of<IResponseHandler>()); - - handledEvent.Wait(); - - requestHandler.Verify(x => x.HandleCancelAsync( - It.IsNotNull<IConnection>(), - It.IsNotNull<Message>(), - It.IsNotNull<IResponseHandler>(), - It.IsAny<CancellationToken>()), Times.Once); - } - } - - [Fact] - public void BeginCancelAsync_TranslatesRequestHandlerExceptionIntoFaultResponse() - { - using (var test = new InboundRequestContextTest()) - using (var sentEvent = new ManualResetEventSlim(initialState: false)) - { - var requestHandler = new Mock<IRequestHandler>(MockBehavior.Strict); - - requestHandler.Setup(x => x.HandleCancelAsync( - It.IsNotNull<IConnection>(), - It.IsNotNull<Message>(), - It.IsNotNull<IResponseHandler>(), - It.IsAny<CancellationToken>())) - .Throws(new Exception("test")); - - Message response = null; - - test.Connection.Setup(x => x.SendAsync(It.IsNotNull<Message>(), It.IsAny<CancellationToken>())) - .Callback<Message, CancellationToken>( - (message, cancellationToken) => - { - response = message; - - sentEvent.Set(); - }) - .Returns(Task.FromResult(0)); - - test.Context.BeginCancelAsync( - new Message( - test.RequestId, - MessageType.Request, - MessageMethod.GetOperationClaims, - payload: null), - requestHandler.Object, - Mock.Of<IResponseHandler>()); - - sentEvent.Wait(); - - requestHandler.Verify(x => x.HandleCancelAsync( - It.IsNotNull<IConnection>(), - It.IsNotNull<Message>(), - It.IsNotNull<IResponseHandler>(), - It.IsAny<CancellationToken>()), Times.Once); - - test.Connection.Verify( - x => x.SendAsync(It.IsNotNull<Message>(), It.IsAny<CancellationToken>()), - Times.Once); - - Assert.NotNull(response); - Assert.Equal(test.RequestId, response.RequestId); - Assert.Equal(MessageType.Fault, response.Type); - Assert.Equal(MessageMethod.GetOperationClaims, response.Method); - - var responsePayload = MessageUtilities.DeserializePayload<Fault>(response); - - Assert.Equal("test", responsePayload.Message); - } - } - - [Fact] - public void BeginFaultAsync_ThrowsForNullRequest() - { - using (var test = new InboundRequestContextTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => test.Context.BeginFaultAsync(request: null, exception: new Exception())); - - Assert.Equal("request", exception.ParamName); - } - } - - [Fact] - public void BeginFaultAsync_ThrowsForNullException() - { - using (var test = new InboundRequestContextTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => test.Context.BeginFaultAsync( - new Message( - test.RequestId, - MessageType.Request, - MessageMethod.GetOperationClaims, - payload: null), - exception: null)); - - Assert.Equal("exception", exception.ParamName); - } - } - - [Fact] - public void BeginFaultAsync_SendsReponse() - { - using (var test = new InboundRequestContextTest()) - using (var sentEvent = new ManualResetEventSlim(initialState: false)) - { - Message response = null; - - test.Connection.Setup(x => x.SendAsync(It.IsNotNull<Message>(), It.IsAny<CancellationToken>())) - .Callback<Message, CancellationToken>( - (message, cancellationToken) => - { - response = message; - - sentEvent.Set(); - }) - .Returns(Task.FromResult(0)); - - test.Context.BeginFaultAsync( - new Message( - test.RequestId, - MessageType.Request, - MessageMethod.GetOperationClaims, - payload: null), - new Exception("test")); - - sentEvent.Wait(); - - test.Connection.Verify( - x => x.SendAsync(It.IsNotNull<Message>(), It.IsAny<CancellationToken>()), - Times.Once); - - Assert.NotNull(response); - Assert.Equal(test.RequestId, response.RequestId); - Assert.Equal(MessageType.Fault, response.Type); - Assert.Equal(MessageMethod.GetOperationClaims, response.Method); - - var responsePayload = MessageUtilities.DeserializePayload<Fault>(response); - - Assert.Equal("test", responsePayload.Message); - } - } - - [Fact] - public void BeginResponseAsync_ThrowsForNullRequest() - { - using (var test = new InboundRequestContextTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => test.Context.BeginResponseAsync( - request: null, - requestHandler: Mock.Of<IRequestHandler>(), - responseHandler: Mock.Of<IResponseHandler>())); - - Assert.Equal("request", exception.ParamName); - } - } - - [Fact] - public void BeginResponseAsync_ThrowsForNullRequestHandler() - { - using (var test = new InboundRequestContextTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => test.Context.BeginResponseAsync( - new Message( - test.RequestId, - MessageType.Progress, - MessageMethod.GetOperationClaims, - payload: null), - requestHandler: null, - responseHandler: Mock.Of<IResponseHandler>())); - - Assert.Equal("requestHandler", exception.ParamName); - } - } - - [Fact] - public void BeginResponseAsync_ThrowsForNullResponseHandler() - { - using (var test = new InboundRequestContextTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => test.Context.BeginResponseAsync( - new Message( - test.RequestId, - type: MessageType.Progress, - method: MessageMethod.GetOperationClaims, - payload: null), - requestHandler: Mock.Of<IRequestHandler>(), - responseHandler: null)); - - Assert.Equal("responseHandler", exception.ParamName); - } - } - - [Fact] - public void BeginResponseAsync_CallsRequestHandler() - { - using (var test = new InboundRequestContextTest()) - using (var handledEvent = new ManualResetEventSlim(initialState: false)) - { - var requestHandler = new Mock<IRequestHandler>(MockBehavior.Strict); - - requestHandler.Setup(x => x.HandleResponseAsync( - It.IsNotNull<IConnection>(), - It.IsNotNull<Message>(), - It.IsNotNull<IResponseHandler>(), - It.IsAny<CancellationToken>())) - .Callback<IConnection, Message, IResponseHandler, CancellationToken>( - (connection, message, responseHandler, cancellationToken) => - { - handledEvent.Set(); - }) - .Returns(Task.FromResult(0)); - - test.Context.BeginResponseAsync( - new Message( - test.RequestId, - MessageType.Request, - MessageMethod.GetOperationClaims, - payload: null), - requestHandler.Object, - Mock.Of<IResponseHandler>()); - - handledEvent.Wait(); - - requestHandler.Verify(x => x.HandleResponseAsync( - It.IsNotNull<IConnection>(), - It.IsNotNull<Message>(), - It.IsNotNull<IResponseHandler>(), - It.IsAny<CancellationToken>()), Times.Once); - } - } - - [Fact] - public void BeginResponseAsync_TranslatesRequestHandlerExceptionIntoFaultResponse() - { - using (var test = new InboundRequestContextTest()) - using (var sentEvent = new ManualResetEventSlim(initialState: false)) - { - var requestHandler = new Mock<IRequestHandler>(MockBehavior.Strict); - - requestHandler.Setup(x => x.HandleResponseAsync( - It.IsNotNull<IConnection>(), - It.IsNotNull<Message>(), - It.IsNotNull<IResponseHandler>(), - It.IsAny<CancellationToken>())) - .Throws(new Exception("test")); - - Message response = null; - - test.Connection.Setup(x => x.SendAsync(It.IsNotNull<Message>(), It.IsAny<CancellationToken>())) - .Callback<Message, CancellationToken>( - (message, cancellationToken) => - { - response = message; - - sentEvent.Set(); - }) - .Returns(Task.FromResult(0)); - - test.Context.BeginResponseAsync( - new Message( - test.RequestId, - MessageType.Request, - MessageMethod.GetOperationClaims, - payload: null), - requestHandler.Object, - Mock.Of<IResponseHandler>()); - - sentEvent.Wait(); - - requestHandler.Verify(x => x.HandleResponseAsync( - It.IsNotNull<IConnection>(), - It.IsNotNull<Message>(), - It.IsNotNull<IResponseHandler>(), - It.IsAny<CancellationToken>()), Times.Once); - - test.Connection.Verify( - x => x.SendAsync(It.IsNotNull<Message>(), It.IsAny<CancellationToken>()), - Times.Once); - - Assert.NotNull(response); - Assert.Equal(test.RequestId, response.RequestId); - Assert.Equal(MessageType.Fault, response.Type); - Assert.Equal(MessageMethod.GetOperationClaims, response.Method); - - var responsePayload = MessageUtilities.DeserializePayload<Fault>(response); - - Assert.Equal("test", responsePayload.Message); - } - } - - private sealed class InboundRequestContextTest : IDisposable - { - internal CancellationTokenSource CancellationTokenSource { get; } - internal Mock<IConnection> Connection { get; } - internal InboundRequestContext Context { get; } - internal string RequestId { get; } - - internal InboundRequestContextTest() - { - CancellationTokenSource = new CancellationTokenSource(); - Connection = new Mock<IConnection>(MockBehavior.Strict); - RequestId = "a"; - Context = new InboundRequestContext( - Connection.Object, - RequestId, - CancellationTokenSource.Token); - } - - public void Dispose() - { - try - { - using (CancellationTokenSource) - { - CancellationTokenSource.Cancel(); - } - } - catch (Exception) - { - } - - Context.Dispose(); - - GC.SuppressFinalize(this); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/JsonSerializationUtilitiesTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/JsonSerializationUtilitiesTests.cs deleted file mode 100644 index d94163b7f79..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/JsonSerializationUtilitiesTests.cs +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class JsonSerializationUtilitiesTests - { - private readonly static A _expectedObject = new A() { B = 3 }; - private readonly static string _expectedJson = "{\"B\":3}"; - - [Fact] - public void Serializer_Converters() - { - var converters = JsonSerializationUtilities.Serializer.Converters; - - Assert.Contains(converters, converter => converter is SemanticVersionConverter); - Assert.Contains(converters, converter => converter is StringEnumConverter); - } - - [Fact] - public void Serializer_Formatting() - { - Assert.Equal(Formatting.None, JsonSerializationUtilities.Serializer.Formatting); - } - - [Fact] - public void Serializer_NullValueHandling() - { - Assert.Equal(NullValueHandling.Ignore, JsonSerializationUtilities.Serializer.NullValueHandling); - } - - [Fact] - public void Deserialize_ThrowsForNullJson() - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<A>(json: null)); - - Assert.Equal("json", exception.ParamName); - } - - [Fact] - public void Deserialize_ThrowsForEmptyJson() - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<A>(json: "")); - - Assert.Equal("json", exception.ParamName); - } - - [Fact] - public void Deserialize_ReturnsCorrectObject() - { - var a = JsonSerializationUtilities.Deserialize<A>(_expectedJson); - - Assert.Equal(3, a.B); - } - - [Fact] - public void FromObject_ThrowsForNullValue() - { - var exception = Assert.Throws<ArgumentNullException>( - () => JsonSerializationUtilities.FromObject(value: null)); - - Assert.Equal("value", exception.ParamName); - } - - [Fact] - public void FromObject_ReturnsCorrectJObject() - { - var jObject = JsonSerializationUtilities.FromObject(_expectedObject); - - Assert.Equal(_expectedJson, jObject.ToString(Formatting.None)); - } - - [Fact] - public void Serialize_ThrowsForNullWriter() - { - var exception = Assert.Throws<ArgumentNullException>( - () => JsonSerializationUtilities.Serialize(writer: null, value: _expectedObject)); - - Assert.Equal("writer", exception.ParamName); - } - - [Fact] - public void Serialize_ReturnsCorrectJson() - { - using (var stringWriter = new StringWriter()) - using (var jsonWriter = new JsonTextWriter(stringWriter)) - { - JsonSerializationUtilities.Serialize(jsonWriter, _expectedObject); - - var json = stringWriter.ToString(); - - Assert.Equal(_expectedJson, json); - } - } - - [Fact] - public void ToObject_ThrowsForNullValue() - { - var exception = Assert.Throws<ArgumentNullException>( - () => JsonSerializationUtilities.ToObject<A>(jObject: null)); - - Assert.Equal("jObject", exception.ParamName); - } - - [Fact] - public void ToObject_ReturnsCorrectObject() - { - var jObject = JObject.FromObject(_expectedObject); - var a = JsonSerializationUtilities.ToObject<A>(jObject); - - Assert.Equal(3, a.B); - } - - private sealed class A - { - public int B { get; set; } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/LineReadEventArgsTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/LineReadEventArgsTests.cs deleted file mode 100644 index 085599fb0db..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/LineReadEventArgsTests.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class LineReadEventArgsTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("a")] - public void Constructor_InitializesLineProperty(string line) - { - var args = new LineReadEventArgs(line); - - Assert.Equal(line, args.Line); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/MessageDispatcherTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/MessageDispatcherTests.cs deleted file mode 100644 index 4a5c04e3760..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/MessageDispatcherTests.cs +++ /dev/null @@ -1,925 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class MessageDispatcherTests - { - private readonly Mock<IConnection> _connection = new Mock<IConnection>(MockBehavior.Strict); - private readonly ConstantIdGenerator _idGenerator = new ConstantIdGenerator(); - private readonly MessageMethod _method = MessageMethod.None; - private readonly TimeSpan _timeout = TimeSpan.FromHours(1); - - [Fact] - public void Constructor_ThrowsForNullRequestHandlers() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new MessageDispatcher(requestHandlers: null, idGenerator: _idGenerator)); - - Assert.Equal("requestHandlers", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullIdGenerator() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new MessageDispatcher(new RequestHandlers(), idGenerator: null)); - - Assert.Equal("idGenerator", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - Assert.NotNull(dispatcher.RequestHandlers); - } - } - - [Fact] - public async Task Close_DisposesAllActiveOutboundRequests() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - using (var sentEvent = new ManualResetEventSlim(initialState: false)) - { - var connection = new Mock<IConnection>(MockBehavior.Strict); - - connection.SetupGet(x => x.Options) - .Returns(ConnectionOptions.CreateDefault()); - - connection.Setup(x => x.SendAsync(It.IsNotNull<Message>(), It.IsAny<CancellationToken>())) - .Callback<Message, CancellationToken>( - (message, cancellationToken) => - { - sentEvent.Set(); - }) - .Returns(Task.FromResult(0)); - - dispatcher.SetConnection(connection.Object); - - var outboundRequestTask = Task.Run(() => dispatcher.DispatchRequestAsync<HandshakeRequest, HandshakeResponse>( - MessageMethod.Handshake, - new HandshakeRequest(ProtocolConstants.CurrentVersion, ProtocolConstants.CurrentVersion), - CancellationToken.None)); - - sentEvent.Wait(); - - dispatcher.Close(); - - await Assert.ThrowsAsync<TaskCanceledException>(() => outboundRequestTask); - - connection.Verify(x => x.SendAsync(It.IsNotNull<Message>(), It.IsAny<CancellationToken>()), Times.Once); - } - } - - [Fact] - public void Close_DisposesAllActiveInboundRequests() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - using (var handlingEvent = new ManualResetEventSlim(initialState: false)) - using (var blockingEvent = new ManualResetEventSlim(initialState: false)) - { - var requestHandler = new RequestHandler(); - - Assert.True(dispatcher.RequestHandlers.TryAdd(MessageMethod.Handshake, requestHandler)); - - var connection = new Mock<IConnection>(MockBehavior.Strict); - var payload = new HandshakeRequest(ProtocolConstants.CurrentVersion, ProtocolConstants.CurrentVersion); - var request = dispatcher.CreateMessage(MessageType.Request, MessageMethod.Handshake, payload); - - dispatcher.SetConnection(connection.Object); - - CancellationToken actualCancellationToken; - - requestHandler.HandleResponseAsyncFunc = (conn, message, responseHandler, cancellationToken) => - { - handlingEvent.Set(); - - actualCancellationToken = cancellationToken; - - blockingEvent.Set(); - - return Task.FromResult(0); - }; - - connection.Raise(x => x.MessageReceived += null, new MessageEventArgs(request)); - - handlingEvent.Wait(); - - dispatcher.Close(); - - blockingEvent.Wait(); - - Assert.True(actualCancellationToken.IsCancellationRequested); - } - } - - [Fact] - public void Close_IsIdempotent() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - dispatcher.Close(); - dispatcher.Close(); - } - } - - [Fact] - public void CreateMessage_TypeMethod_ReturnsMessage() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var message = dispatcher.CreateMessage(MessageType.Request, MessageMethod.Handshake); - - Assert.Equal(_idGenerator.Id, message.RequestId); - Assert.Equal(MessageType.Request, message.Type); - Assert.Equal(MessageMethod.Handshake, message.Method); - Assert.Null(message.Payload); - } - } - - [Fact] - public void CreateMessage_TypeMethodPayload_ThrowsForNullPayload() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var exception = Assert.Throws<ArgumentNullException>( - () => dispatcher.CreateMessage<HandshakeRequest>( - MessageType.Request, - MessageMethod.Handshake, - payload: null)); - - Assert.Equal("payload", exception.ParamName); - } - } - - [Fact] - public void CreateMessage_TypeMethodPayload_ReturnsMessage() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var payload = new HandshakeRequest(ProtocolConstants.CurrentVersion, ProtocolConstants.CurrentVersion); - var message = dispatcher.CreateMessage( - MessageType.Request, - MessageMethod.Handshake, - payload); - - Assert.Equal(_idGenerator.Id, message.RequestId); - Assert.Equal(MessageType.Request, message.Type); - Assert.Equal(MessageMethod.Handshake, message.Method); - Assert.Equal("{\"ProtocolVersion\":\"1.0.0\",\"MinimumProtocolVersion\":\"1.0.0\"}", - message.Payload.ToString(Formatting.None)); - } - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - dispatcher.Dispose(); - dispatcher.Dispose(); - } - } - - [Fact] - public void SetConnection_SubscribesToMessageReceived() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var spy = new ConnectionEventRegistrationSpy(); - - Assert.Equal(0, spy.MessageReceivedAddCount); - - dispatcher.SetConnection(spy); - - Assert.Equal(1, spy.MessageReceivedAddCount); - } - } - - [Fact] - public void SetConnection_UnsubscribesFromMessageReceivedWithNullConnection() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var spy = new ConnectionEventRegistrationSpy(); - - dispatcher.SetConnection(spy); - dispatcher.SetConnection(connection: null); - - Assert.Equal(1, spy.MessageReceivedRemoveCount); - } - } - - [Fact] - public void SetConnection_UnsubscribesFromMessageReceivedWithNewConnection() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var firstSpy = new ConnectionEventRegistrationSpy(); - - dispatcher.SetConnection(firstSpy); - - var secondSpy = new ConnectionEventRegistrationSpy(); - - dispatcher.SetConnection(secondSpy); - - Assert.Equal(1, firstSpy.MessageReceivedRemoveCount); - Assert.Equal(1, secondSpy.MessageReceivedAddCount); - } - } - - [Fact] - public void SetConnection_IsIdempotent() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var spy = new ConnectionEventRegistrationSpy(); - - dispatcher.SetConnection(spy); - dispatcher.SetConnection(spy); - dispatcher.SetConnection(spy); - - Assert.Equal(1, spy.MessageReceivedAddCount); - Assert.Equal(0, spy.MessageReceivedRemoveCount); - } - } - - [Fact] - public async Task DispatchCancelAsync_NoOpsIfNoConnection() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var request = new Message(_idGenerator.Id, MessageType.Request, _method); - - await dispatcher.DispatchCancelAsync(request, CancellationToken.None); - } - } - - [Fact] - public async Task DispatchCancelAsync_ThrowsForNullRequest() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => dispatcher.DispatchCancelAsync(request: null, cancellationToken: CancellationToken.None)); - - Assert.Equal("request", exception.ParamName); - } - } - - [Fact] - public async Task DispatchCancelAsync_ThrowsIfCancelled() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => dispatcher.DispatchCancelAsync( - new Message(_idGenerator.Id, MessageType.Request, _method), - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task DispatchCancelAsync_ThrowsWithoutAssociatedRequestId() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - using (var connection = new ConnectionMock()) - { - dispatcher.SetConnection(connection); - - var request = new Message(_idGenerator.Id, MessageType.Request, _method); - - await Assert.ThrowsAsync<ProtocolException>( - () => dispatcher.DispatchCancelAsync(request, CancellationToken.None)); - } - } - - [Fact] - public async Task DispatchCancelAsync_SendsProgressWithAssociatedRequestId() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - using (var connection = new ConnectionMock()) - using (var messageSentEvent = new ManualResetEventSlim(initialState: false)) - { - dispatcher.SetConnection(connection); - - var request = new Message(_idGenerator.Id, MessageType.Request, MessageMethod.GetOperationClaims); - - var requestTask = dispatcher.DispatchRequestAsync<Request, Response>( - request.Method, - new Request(), - cancellationToken: CancellationToken.None); - - Message message = null; - - connection.MessageSent += (object sender, MessageEventArgs e) => - { - message = e.Message; - - messageSentEvent.Set(); - }; - - await dispatcher.DispatchCancelAsync(request, CancellationToken.None); - - Assert.NotNull(message); - Assert.Equal(_idGenerator.Id, message.RequestId); - Assert.Equal(MessageType.Cancel, message.Type); - Assert.Equal(request.Method, message.Method); - Assert.Null(message.Payload); - } - } - - [Fact] - public async Task DispatchFaultAsync_NoOpsIfNoConnection() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - await dispatcher.DispatchFaultAsync( - request: null, - fault: new Fault(message: "a"), - cancellationToken: CancellationToken.None); - } - } - - [Fact] - public async Task DispatchFaultAsync_ThrowsForNullFault() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => dispatcher.DispatchFaultAsync( - new Message(_idGenerator.Id, MessageType.Request, _method), - fault: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("fault", exception.ParamName); - } - } - - [Fact] - public async Task DispatchFaultAsync_ThrowsIfCancelled() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => dispatcher.DispatchFaultAsync( - new Message(_idGenerator.Id, MessageType.Request, _method), - new Fault("test"), - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task DispatchFaultAsync_SendsFaultWithoutAssociatedRequestId() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - using (var connection = new ConnectionMock()) - using (var messageSentEvent = new ManualResetEventSlim(initialState: false)) - { - dispatcher.SetConnection(connection); - - var fault = new Fault(message: "a"); - - Message message = null; - - connection.MessageSent += (object sender, MessageEventArgs e) => - { - message = e.Message; - - messageSentEvent.Set(); - }; - - await dispatcher.DispatchFaultAsync( - request: null, - fault: fault, - cancellationToken: CancellationToken.None); - - Assert.NotNull(message); - Assert.Equal(_idGenerator.Id, message.RequestId); - Assert.Equal(MessageType.Fault, message.Type); - Assert.Equal(MessageMethod.None, message.Method); - Assert.Equal("{\"Message\":\"a\"}", message.Payload.ToString(Formatting.None)); - } - } - - [Fact] - public async Task DispatchFaultAsync_SendsFaultWithAssociatedRequestId() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - using (var connection = new ConnectionMock()) - using (var messageSentEvent = new ManualResetEventSlim(initialState: false)) - { - dispatcher.SetConnection(connection); - - var request = new Message( - _idGenerator.Id, - MessageType.Request, - MessageMethod.Handshake, - JObject.FromObject(new Request())); - - var requestTask = dispatcher.DispatchRequestAsync<Request, Response>( - request.Method, - new Request(), - cancellationToken: CancellationToken.None); - - var fault = new Fault(message: "a"); - - Message message = null; - - connection.MessageSent += (object sender, MessageEventArgs e) => - { - message = e.Message; - - messageSentEvent.Set(); - }; - - await dispatcher.DispatchFaultAsync(request, fault, CancellationToken.None); - - Assert.NotNull(message); - Assert.Equal(_idGenerator.Id, message.RequestId); - Assert.Equal(MessageType.Fault, message.Type); - Assert.Equal(request.Method, message.Method); - Assert.Equal("{\"Message\":\"a\"}", message.Payload.ToString(Formatting.None)); - } - } - - [Fact] - public async Task DispatchProgressAsync_NoOpsIfNoConnection() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var payload = JObject.FromObject(new Request()); - var request = new Message(_idGenerator.Id, MessageType.Request, _method, payload); - - await dispatcher.DispatchProgressAsync( - request, - new Progress(percentage: 0.5), - CancellationToken.None); - } - } - - [Fact] - public async Task DispatchProgressAsync_ThrowsForNullRequest() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => dispatcher.DispatchProgressAsync( - request: null, - progress: new Progress(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("request", exception.ParamName); - } - } - - [Fact] - public async Task DispatchProgressAsync_ThrowsForNullProgress() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => dispatcher.DispatchProgressAsync( - new Message(_idGenerator.Id, MessageType.Request, _method), - progress: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("progress", exception.ParamName); - } - } - - [Fact] - public async Task DispatchProgressAsync_ThrowsIfCancelled() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => dispatcher.DispatchProgressAsync( - new Message(_idGenerator.Id, MessageType.Request, _method), - new Progress(), - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task DispatchProgressAsync_ThrowsWithoutAssociatedRequestId() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - using (var connection = new ConnectionMock()) - { - dispatcher.SetConnection(connection); - - var payload = JObject.FromObject(new Request()); - var request = new Message(_idGenerator.Id, MessageType.Request, _method, payload); - var progress = new Progress(percentage: 0.5); - - await Assert.ThrowsAsync<ProtocolException>( - () => dispatcher.DispatchProgressAsync(request, progress, CancellationToken.None)); - } - } - - [Fact] - public async Task DispatchProgressAsync_SendsProgressWithAssociatedRequestId() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - using (var connection = new ConnectionMock()) - using (var messageSentEvent = new ManualResetEventSlim(initialState: false)) - { - dispatcher.SetConnection(connection); - - var payload = JObject.FromObject(new Request()); - var request = new Message( - _idGenerator.Id, - MessageType.Request, - MessageMethod.GetOperationClaims, - payload); - var progress = new Progress(percentage: 0.5); - - var requestTask = dispatcher.DispatchRequestAsync<Request, Response>( - request.Method, - new Request(), - cancellationToken: CancellationToken.None); - - Message message = null; - - connection.MessageSent += (object sender, MessageEventArgs e) => - { - message = e.Message; - - messageSentEvent.Set(); - }; - - await dispatcher.DispatchProgressAsync(request, progress, CancellationToken.None); - - Assert.NotNull(message); - Assert.Equal(_idGenerator.Id, message.RequestId); - Assert.Equal(MessageType.Progress, message.Type); - Assert.Equal(request.Method, message.Method); - Assert.Equal("{\"Percentage\":0.5}", message.Payload.ToString(Formatting.None)); - } - } - - [Fact] - public async Task DispatchRequestAsync_NoOpsIfNoConnection() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var version = new SemanticVersion(major: 1, minor: 0, patch: 0); - var result = await dispatcher.DispatchRequestAsync<HandshakeRequest, HandshakeResponse>( - MessageMethod.Handshake, - new HandshakeRequest(version, version), - cancellationToken: CancellationToken.None); - - Assert.Null(result); - } - } - - [Fact] - public async Task DispatchRequestAsync_ThrowsIfCancelled() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var version = new SemanticVersion(major: 1, minor: 0, patch: 0); - - await Assert.ThrowsAsync<OperationCanceledException>( - () => dispatcher.DispatchRequestAsync<HandshakeRequest, HandshakeResponse>( - MessageMethod.Handshake, - new HandshakeRequest(version, version), - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task DispatchRequestAsync_ReturnsResponse() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - using (var connection = new ConnectionMock()) - { - var response = new Message( - _idGenerator.Id, - MessageType.Response, - _method, - JObject.FromObject(new Response())); - - dispatcher.SetConnection(connection); - - var requestTask = dispatcher.DispatchRequestAsync<Request, Response>( - _method, - new Request(), - cancellationToken: CancellationToken.None); - - connection.SimulateResponse(response); - - await requestTask; - - Assert.IsType<Response>(requestTask.Result); - } - } - - [Fact] - public async Task DispatchResponseAsync_NoOpsIfNoConnection() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var version = new SemanticVersion(major: 1, minor: 0, patch: 0); - var payload = JObject.FromObject(new HandshakeRequest(version, version)); - var request = new Message(_idGenerator.Id, MessageType.Request, _method, payload); - - await dispatcher.DispatchResponseAsync( - request, - new HandshakeResponse(MessageResponseCode.Error, protocolVersion: null), - CancellationToken.None); - } - } - - [Fact] - public async Task DispatchResponseAsync_ThrowsForNullRequest() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => dispatcher.DispatchResponseAsync( - request: null, - responsePayload: new HandshakeResponse( - MessageResponseCode.Success, - ProtocolConstants.CurrentVersion), - cancellationToken: CancellationToken.None)); - - Assert.Equal("request", exception.ParamName); - } - } - - [Fact] - public async Task DispatchResponseAsync_ThrowsForNullResponsePayload() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => dispatcher.DispatchResponseAsync<HandshakeResponse>( - new Message(_idGenerator.Id, MessageType.Request, MessageMethod.Handshake), - responsePayload: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("responsePayload", exception.ParamName); - } - } - - [Fact] - public async Task DispatchResponseAsync_ThrowsIfCancelled() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => dispatcher.DispatchResponseAsync( - new Message(_idGenerator.Id, MessageType.Request, MessageMethod.Handshake), - new HandshakeResponse( - MessageResponseCode.Success, - ProtocolConstants.CurrentVersion), - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task DispatchResponseAsync_ReturnsResponse() - { - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - using (var connection = new ConnectionMock()) - { - dispatcher.SetConnection(connection); - - var requestTask = dispatcher.DispatchRequestAsync<Request, Response>( - _method, - new Request(), - CancellationToken.None); - - var response = new Message( - _idGenerator.Id, - MessageType.Response, - _method, - JObject.FromObject(new Response())); - - connection.SimulateResponse(response); - - await requestTask; - - Assert.IsType<Response>(requestTask.Result); - } - } - - [Fact] - public void OnMessageReceived_ThrowsForInboundFault() - { - var connection = new Mock<IConnection>(); - - using (var dispatcher = new MessageDispatcher(new RequestHandlers(), _idGenerator)) - { - dispatcher.SetConnection(connection.Object); - - var fault = MessageUtilities.Create( - _idGenerator.Id, - MessageType.Fault, - MessageMethod.GetOperationClaims, - new Fault("test")); - - Assert.Throws<ProtocolException>( - () => connection.Raise(x => x.MessageReceived += null, new MessageEventArgs(fault))); - } - } - - private sealed class ConstantIdGenerator : IIdGenerator - { - internal string Id { get; } - - internal ConstantIdGenerator() - { - Id = "0"; - } - - public string GenerateUniqueId() - { - return Id; - } - } - - private sealed class ConnectionMock : IConnection, IDisposable - { - private readonly ManualResetEventSlim _event; - private bool _isDisposed; - - public IMessageDispatcher MessageDispatcher => throw new NotImplementedException(); - public ConnectionOptions Options { get; } - public SemanticVersion ProtocolVersion => throw new NotImplementedException(); - -#pragma warning disable 67 - public event EventHandler<ProtocolErrorEventArgs> Faulted; -#pragma warning restore 67 - public event EventHandler<MessageEventArgs> MessageReceived; - public event EventHandler<MessageEventArgs> MessageSent; - - public ConnectionMock() - { - _event = new ManualResetEventSlim(initialState: false); - - Options = ConnectionOptions.CreateDefault(); - } - - public void Dispose() - { - if (!_isDisposed) - { - _event.Dispose(); - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - public void Close() - { - } - - public Task SendAsync(Message message, CancellationToken cancellationToken) - { - switch (message.Type) - { - case MessageType.Fault: - MessageSent?.Invoke(this, new MessageEventArgs(message)); - break; - - case MessageType.Request: - _event.Set(); - break; - - case MessageType.Cancel: - case MessageType.Progress: - case MessageType.Response: - _event.Wait(); - MessageSent?.Invoke(this, new MessageEventArgs(message)); - break; - } - - return Task.FromResult(0); - } - - public Task<TInbound> SendRequestAndReceiveResponseAsync<TOutbound, TInbound>(MessageMethod method, TOutbound payload, CancellationToken cancellationToken) - where TOutbound : class - where TInbound : class - { - throw new NotImplementedException(); - } - - internal void SimulateResponse(Message response) - { - MessageReceived?.Invoke(this, new MessageEventArgs(response)); - } - } - - private sealed class ConnectionEventRegistrationSpy : IConnection - { - internal int FaultedAddCount { get; private set; } - internal int FaultedRemoveCount { get; private set; } - internal int MessageReceivedAddCount { get; private set; } - internal int MessageReceivedRemoveCount { get; private set; } - - public IMessageDispatcher MessageDispatcher => throw new NotImplementedException(); - public ConnectionOptions Options => throw new NotImplementedException(); - public SemanticVersion ProtocolVersion => throw new NotImplementedException(); - - public event EventHandler<ProtocolErrorEventArgs> Faulted - { - add - { - ++FaultedAddCount; - } - remove - { - ++FaultedRemoveCount; - } - } - - public event EventHandler<MessageEventArgs> MessageReceived - { - add - { - ++MessageReceivedAddCount; - } - remove - { - ++MessageReceivedRemoveCount; - } - } - - public void Dispose() - { - } - - public void Close() - { - } - - public Task SendAsync(Message message, CancellationToken cancellationToken) - { - throw new NotImplementedException(); - } - - public Task<TInbound> SendRequestAndReceiveResponseAsync<TOutbound, TInbound>(MessageMethod method, TOutbound payload, CancellationToken cancellationToken) - where TOutbound : class - where TInbound : class - { - throw new NotImplementedException(); - } - } - - private sealed class Request - { - } - - private sealed class Response - { - } - - private sealed class RequestHandler : IRequestHandler - { - public CancellationToken CancellationToken { get; internal set; } - - internal Func<IConnection, Message, IResponseHandler, CancellationToken, Task> HandleCancelAsyncFunc { get; set; } - internal Func<IConnection, Message, IResponseHandler, CancellationToken, Task> HandleResponseAsyncFunc { get; set; } - - internal RequestHandler() - { - CancellationToken = CancellationToken.None; - HandleCancelAsyncFunc = (connection, request, responseHandler, cancellationToken) => throw new NotImplementedException(); - HandleResponseAsyncFunc = (connection, request, responseHandler, cancellationToken) => throw new NotImplementedException(); - } - - public Task HandleCancelAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - return HandleCancelAsyncFunc(connection, request, responseHandler, cancellationToken); - } - - public Task HandleResponseAsync( - IConnection connection, - Message request, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - return HandleResponseAsyncFunc(connection, request, responseHandler, cancellationToken); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/MessageEventArgsTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/MessageEventArgsTests.cs deleted file mode 100644 index 06ba81a4b25..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/MessageEventArgsTests.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class MessageEventArgsTests - { - [Fact] - public void Constructor_ThrowsForNullException() - { - var exception = Assert.Throws<ArgumentNullException>(() => new MessageEventArgs(message: null)); - - Assert.Equal("message", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesMessageProperty() - { - var message = new Message(requestId: "a", type: MessageType.Request, method: MessageMethod.None); - var args = new MessageEventArgs(message); - - Assert.Same(message, args.Message); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/MessageUtilitiesTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/MessageUtilitiesTests.cs deleted file mode 100644 index 8820947e626..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/MessageUtilitiesTests.cs +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class MessageUtilitiesTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Create_RequestIdTypeMethod_ThrowsForNullOrEmptyRequestId(string requestId) - { - var exception = Assert.Throws<ArgumentException>( - () => MessageUtilities.Create(requestId, MessageType.Request, MessageMethod.Handshake)); - - Assert.Equal("requestId", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Create_RequestIdTypeMethodPayload_ThrowsForNullOrEmptyRequestId(string requestId) - { - var payload = new Payload("a", 3, true, D.F); - var exception = Assert.Throws<ArgumentException>( - () => MessageUtilities.Create(requestId, MessageType.Request, MessageMethod.Handshake, payload)); - - Assert.Equal("requestId", exception.ParamName); - } - - [Fact] - public void Create_RequestIdTypeMethodPayload_ThrowsForNullPayload() - { - var exception = Assert.Throws<ArgumentNullException>( - () => MessageUtilities.Create<Payload>( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Handshake, - payload: null)); - - Assert.Equal("payload", exception.ParamName); - } - - [Fact] - public void Create_RequestIdTypeMethod_InitializesProperties() - { - var message = MessageUtilities.Create( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Handshake); - - Assert.Equal("a", message.RequestId); - Assert.Equal(MessageType.Request, message.Type); - Assert.Equal(MessageMethod.Handshake, message.Method); - Assert.Null(message.Payload); - } - - [Fact] - public void Create_RequestIdTypeMethodPayload_InitializesProperties() - { - var payload = new Payload("a", 3, true, D.F); - var message = MessageUtilities.Create( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Handshake, - payload: payload); - - Assert.Equal("a", message.RequestId); - Assert.Equal(MessageType.Request, message.Type); - Assert.Equal(MessageMethod.Handshake, message.Method); - Assert.NotNull(message.Payload); - } - - [Fact] - public void Create_SerializesPayload() - { - var payload = new Payload("a", 3, true, D.F); - var message = MessageUtilities.Create( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Handshake, - payload: payload); - - Assert.NotNull(message); - Assert.NotNull(message.Payload); - Assert.Equal("{\"A\":\"a\",\"B\":3,\"C\":true,\"D\":\"F\"}", message.Payload.ToString(Formatting.None)); - } - - [Fact] - public void DeserializePayload_ThrowsForNullMessage() - { - var exception = Assert.Throws<ArgumentNullException>( - () => MessageUtilities.DeserializePayload<Payload>(message: null)); - - Assert.Equal("message", exception.ParamName); - } - - [Fact] - public void DeserializePayload_SupportsNullPayload() - { - var message = new Message(requestId: "a", type: MessageType.Fault, method: MessageMethod.None, payload: null); - - var payload = MessageUtilities.DeserializePayload<Payload>(message); - - Assert.Null(payload); - } - - [Fact] - public void DeserializePayload_UsesDefaultSerializationOptions() - { - var payload = new Payload("a", 3, true, D.F); - var serializedPayload = JObject.FromObject(payload); - var message = new Message( - requestId: "a", - type: MessageType.Cancel, - method: MessageMethod.None, - payload: serializedPayload); - - var deserializedPayload = MessageUtilities.DeserializePayload<Payload>(message); - - Assert.NotNull(deserializedPayload); - Assert.Equal(payload.A, deserializedPayload.A); - Assert.Equal(payload.B, deserializedPayload.B); - Assert.Equal(payload.C, deserializedPayload.C); - Assert.Equal(payload.D, deserializedPayload.D); - } - - private sealed class Payload - { - public string A { get; } - public int B { get; } - public bool C { get; } - public D D { get; } - - [JsonConstructor] - public Payload(string a, int b, bool c, D d) - { - A = a; - B = b; - C = c; - D = d; - } - } - - private enum D - { - E, - F - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyFilesInPackageRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyFilesInPackageRequestTests.cs deleted file mode 100644 index 4bbd5475454..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyFilesInPackageRequestTests.cs +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Linq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class CopyFilesInPackageRequestTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageSourceRepository(string packageSourceRepository) - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyFilesInPackageRequest( - packageSourceRepository, - packageId: "a", - packageVersion: "b", - filesInPackage: new[] { "c" }, - destinationFolderPath: "d")); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageId(string packageId) - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyFilesInPackageRequest( - packageSourceRepository: "a", - packageId: packageId, - packageVersion: "b", - filesInPackage: new[] { "c" }, - destinationFolderPath: "d")); - - Assert.Equal("packageId", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageVersion(string packageVersion) - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyFilesInPackageRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: packageVersion, - filesInPackage: new[] { "c" }, - destinationFolderPath: "d")); - - Assert.Equal("packageVersion", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullFilesInPackage() - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyFilesInPackageRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c", - filesInPackage: null, - destinationFolderPath: "d")); - - Assert.Equal("filesInPackage", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForEmptyFilesInPackage() - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyFilesInPackageRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c", - filesInPackage: Enumerable.Empty<string>(), - destinationFolderPath: "d")); - - Assert.Equal("filesInPackage", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyDestinationFolderPath(string destinationFolderPath) - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyFilesInPackageRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c", - filesInPackage: new[] { "d" }, - destinationFolderPath: destinationFolderPath)); - - Assert.Equal("destinationFolderPath", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var request = new CopyFilesInPackageRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c", - filesInPackage: new[] { "d" }, - destinationFolderPath: "e"); - - Assert.Equal("a", request.PackageSourceRepository); - Assert.Equal("b", request.PackageId); - Assert.Equal("c", request.PackageVersion); - Assert.Equal(new[] { "d" }, request.FilesInPackage); - Assert.Equal("e", request.DestinationFolderPath); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new CopyFilesInPackageRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c", - filesInPackage: new[] { "d" }, - destinationFolderPath: "e"); - - var actualJson = TestUtilities.Serialize(request); - - Assert.Equal("{\"DestinationFolderPath\":\"e\",\"FilesInPackage\":[\"d\"],\"PackageId\":\"b\",\"PackageSourceRepository\":\"a\",\"PackageVersion\":\"c\"}", actualJson); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"DestinationFolderPath\":\"a\",\"FilesInPackage\":[\"b\"],\"PackageId\":\"c\",\"PackageSourceRepository\":\"d\",\"PackageVersion\":\"e\"}"; - var request = JsonSerializationUtilities.Deserialize<CopyFilesInPackageRequest>(json); - - Assert.Equal("d", request.PackageSourceRepository); - Assert.Equal("c", request.PackageId); - Assert.Equal("e", request.PackageVersion); - Assert.Equal(new[] { "b" }, request.FilesInPackage); - Assert.Equal("a", request.DestinationFolderPath); - } - - [Theory] - [InlineData("{}", "packageSourceRepository")] - [InlineData("{\"FilesInPackage\":[\"b\"],\"PackageId\":\"c\",\"PackageSourceRepository\":\"d\",\"PackageVersion\":\"e\"}", "destinationFolderPath")] - [InlineData("{\"DestinationFolderPath\":null,\"FilesInPackage\":[\"b\"],\"PackageId\":\"c\",\"PackageSourceRepository\":\"d\",\"PackageVersion\":\"e\"}", "destinationFolderPath")] - [InlineData("{\"DestinationFolderPath\":\"\",\"FilesInPackage\":[\"b\"],\"PackageId\":\"c\",\"PackageSourceRepository\":\"d\",\"PackageVersion\":\"e\"}", "destinationFolderPath")] - [InlineData("{\"DestinationFolderPath\":\"a\",\"PackageId\":\"c\",\"PackageSourceRepository\":\"d\",\"PackageVersion\":\"e\"}", "filesInPackage")] - [InlineData("{\"DestinationFolderPath\":\"a\",\"FilesInPackage\":null,\"PackageId\":\"c\",\"PackageSourceRepository\":\"d\",\"PackageVersion\":\"e\"}", "filesInPackage")] - [InlineData("{\"DestinationFolderPath\":\"a\",\"FilesInPackage\":[],\"PackageId\":\"c\",\"PackageSourceRepository\":\"d\",\"PackageVersion\":\"e\"}", "filesInPackage")] - [InlineData("{\"DestinationFolderPath\":\"a\",\"FilesInPackage\":[\"b\"],\"PackageSourceRepository\":\"d\",\"PackageVersion\":\"e\"}", "packageId")] - [InlineData("{\"DestinationFolderPath\":\"a\",\"FilesInPackage\":[\"b\"],\"PackageId\":null,\"PackageSourceRepository\":\"d\",\"PackageVersion\":\"e\"}", "packageId")] - [InlineData("{\"DestinationFolderPath\":\"a\",\"FilesInPackage\":[\"b\"],\"PackageId\":\"\",\"PackageSourceRepository\":\"d\",\"PackageVersion\":\"e\"}", "packageId")] - [InlineData("{\"DestinationFolderPath\":\"a\",\"FilesInPackage\":[\"b\"],\"PackageId\":\"c\",\"PackageVersion\":\"e\"}", "packageSourceRepository")] - [InlineData("{\"DestinationFolderPath\":\"a\",\"FilesInPackage\":[\"b\"],\"PackageId\":\"c\",\"PackageSourceRepository\":null,\"PackageVersion\":\"e\"}", "packageSourceRepository")] - [InlineData("{\"DestinationFolderPath\":\"a\",\"FilesInPackage\":[\"b\"],\"PackageId\":\"c\",\"PackageSourceRepository\":\"\",\"PackageVersion\":\"e\"}", "packageSourceRepository")] - [InlineData("{\"DestinationFolderPath\":\"a\",\"FilesInPackage\":[\"b\"],\"PackageId\":\"c\",\"PackageSourceRepository\":\"d\"}", "packageVersion")] - [InlineData("{\"DestinationFolderPath\":\"a\",\"FilesInPackage\":[\"b\"],\"PackageId\":\"c\",\"PackageSourceRepository\":\"d\",\"PackageVersion\":null}", "packageVersion")] - [InlineData("{\"DestinationFolderPath\":\"a\",\"FilesInPackage\":[\"b\"],\"PackageId\":\"c\",\"PackageSourceRepository\":\"d\",\"PackageVersion\":\"\"}", "packageVersion")] - public void JsonDeserialization_ThrowsForInvalidStringArgument(string json, string parameterName) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<CopyFilesInPackageRequest>(json)); - - Assert.Equal(parameterName, exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyFilesInPackageResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyFilesInPackageResponseTests.cs deleted file mode 100644 index ea7f42ce00f..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyFilesInPackageResponseTests.cs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class CopyFilesInPackageResponseTests - { - [Fact] - public void Constructor_ThrowsForUndefinedResponseCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyFilesInPackageResponse((MessageResponseCode)int.MaxValue, new[] { "a" })); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullCopiedFilesWhenResponseCodeIsSuccess() - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyFilesInPackageResponse(MessageResponseCode.Success, copiedFiles: null)); - - Assert.Equal("copiedFiles", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForEmptyCopiedFilesWhenResponseCodeIsSuccess() - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyFilesInPackageResponse(MessageResponseCode.Success, new string[] { })); - - Assert.Equal("copiedFiles", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var response = new CopyFilesInPackageResponse(MessageResponseCode.Success, new [] { "a" }); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - Assert.Equal(new[] { "a" }, response.CopiedFiles); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var response = new CopyFilesInPackageResponse(MessageResponseCode.Success, new[] { "a" }); - - var json = TestUtilities.Serialize(response); - - Assert.Equal("{\"CopiedFiles\":[\"a\"],\"ResponseCode\":\"Success\"}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObjectForSuccess() - { - var json = "{\"CopiedFiles\":[\"a\"],\"ResponseCode\":\"Success\"}"; - var response = JsonSerializationUtilities.Deserialize<CopyFilesInPackageResponse>(json); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - Assert.Equal(new[] { "a" }, response.CopiedFiles); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObjectForNotFound() - { - var json = "{\"ResponseCode\":\"NotFound\"}"; - var response = JsonSerializationUtilities.Deserialize<CopyFilesInPackageResponse>(json); - - Assert.Equal(MessageResponseCode.NotFound, response.ResponseCode); - Assert.Null(response.CopiedFiles); - } - - [Theory] - [InlineData("{\"ResponseCode\":null}")] - [InlineData("{\"ResponseCode\":\"\"}")] - [InlineData("{\"ResponseCode\":\"b\"}")] - public void JsonDeserialization_ThrowsForInvalidResponseCode(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<CopyFilesInPackageResponse>(json)); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"ResponseCode\":\"Success\"}")] - [InlineData("{\"CopiedFiles\":null,\"ResponseCode\":\"Success\"}")] - [InlineData("{\"CopiedFiles\":[],\"ResponseCode\":\"Success\"}")] - public void JsonDeserialization_ThrowsForInvalidCopiedFiles(string json) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<CopyFilesInPackageResponse>(json)); - - Assert.Equal("copiedFiles", exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyNupkgFileRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyNupkgFileRequestTests.cs deleted file mode 100644 index a13709442b4..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyNupkgFileRequestTests.cs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class CopyNupkgFileRequestTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageSourceRepository(string packageSourceRepository) - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyNupkgFileRequest( - packageSourceRepository, - packageId: "a", - packageVersion: "b", - destinationFilePath: "c")); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageId(string packageId) - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyNupkgFileRequest( - packageSourceRepository: "a", - packageId: packageId, - packageVersion: "b", - destinationFilePath: "c")); - - Assert.Equal("packageId", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageVersion(string packageVersion) - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyNupkgFileRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: packageVersion, - destinationFilePath: "c")); - - Assert.Equal("packageVersion", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyDestinationFilePath(string destinationFilePath) - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyNupkgFileRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c", - destinationFilePath: destinationFilePath)); - - Assert.Equal("destinationFilePath", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var request = new CopyNupkgFileRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c", - destinationFilePath: "d"); - - Assert.Equal("a", request.PackageSourceRepository); - Assert.Equal("b", request.PackageId); - Assert.Equal("c", request.PackageVersion); - Assert.Equal("d", request.DestinationFilePath); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new CopyNupkgFileRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c", - destinationFilePath: "d"); - - var actualJson = TestUtilities.Serialize(request); - - Assert.Equal("{\"DestinationFilePath\":\"d\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"a\",\"PackageVersion\":\"c\"}", actualJson); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"DestinationFilePath\":\"a\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}"; - var request = JsonSerializationUtilities.Deserialize<CopyNupkgFileRequest>(json); - - Assert.Equal("c", request.PackageSourceRepository); - Assert.Equal("b", request.PackageId); - Assert.Equal("d", request.PackageVersion); - Assert.Equal("a", request.DestinationFilePath); - } - - [Theory] - [InlineData("{}", "packageSourceRepository")] - [InlineData("{\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}", "destinationFilePath")] - [InlineData("{\"DestinationFilePath\":null,\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}", "destinationFilePath")] - [InlineData("{\"DestinationFilePath\":\"\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}", "destinationFilePath")] - [InlineData("{\"DestinationFilePath\":\"a\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}", "packageId")] - [InlineData("{\"DestinationFilePath\":\"a\",\"PackageId\":null,\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}", "packageId")] - [InlineData("{\"DestinationFilePath\":\"a\",\"PackageId\":\"\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}", "packageId")] - [InlineData("{\"DestinationFilePath\":\"a\",\"PackageId\":\"b\",\"PackageVersion\":\"d\"}", "packageSourceRepository")] - [InlineData("{\"DestinationFilePath\":\"a\",\"PackageId\":\"b\",\"PackageSourceRepository\":null,\"PackageVersion\":\"d\"}", "packageSourceRepository")] - [InlineData("{\"DestinationFilePath\":\"a\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"\",\"PackageVersion\":\"d\"}", "packageSourceRepository")] - [InlineData("{\"DestinationFilePath\":\"a\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\"}", "packageVersion")] - [InlineData("{\"DestinationFilePath\":\"a\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":null}", "packageVersion")] - [InlineData("{\"DestinationFilePath\":\"a\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"\"}", "packageVersion")] - public void JsonDeserialization_ThrowsForInvalidStringArgument(string json, string parameterName) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<CopyNupkgFileRequest>(json)); - - Assert.Equal(parameterName, exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyNupkgFileResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyNupkgFileResponseTests.cs deleted file mode 100644 index 1a83854293b..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/CopyNupkgFileResponseTests.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class CopyNupkgFileResponseTests - { - [Fact] - public void Constructor_ThrowsForUndefinedResponseCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new CopyNupkgFileResponse((MessageResponseCode)int.MaxValue)); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesResponseCodeProperty() - { - var response = new CopyNupkgFileResponse(MessageResponseCode.Success); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var response = new CopyNupkgFileResponse(MessageResponseCode.Success); - - var json = TestUtilities.Serialize(response); - - Assert.Equal("{\"ResponseCode\":\"Success\"}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"ResponseCode\":\"Success\"}"; - var response = JsonSerializationUtilities.Deserialize<CopyNupkgFileResponse>(json); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"ResponseCode\":null}")] - [InlineData("{\"ResponseCode\":\"\"}")] - [InlineData("{\"ResponseCode\":\"a\"}")] - public void JsonDeserialization_ThrowsForInvalidResponseCode(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<CopyNupkgFileResponse>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/FaultTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/FaultTests.cs deleted file mode 100644 index b745ab077b7..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/FaultTests.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class FaultTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyMessage(string message) - { - var exception = Assert.Throws<ArgumentException>(() => new Fault(message)); - - Assert.Equal("message", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesMessageProperty() - { - var fault = new Fault(message: "a"); - - Assert.Equal("a", fault.Message); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var fault = new Fault(message: "a"); - var json = TestUtilities.Serialize(fault); - - Assert.Equal("{\"Message\":\"a\"}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"Message\":\"a\"}"; - var fault = JsonSerializationUtilities.Deserialize<Fault>(json); - - Assert.Equal("a", fault.Message); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"Message\":null}")] - [InlineData("{\"Message\":\"\"}")] - public void JsonDeserialization_ThrowsForNullOrEmptyMessage(string json) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<Fault>(json)); - - Assert.Equal("message", exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetCredentialsRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetCredentialsRequestTests.cs deleted file mode 100644 index 5bc106641c0..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetCredentialsRequestTests.cs +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Net; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetCredentialsRequestTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageSourceRepository(string packageSourceRepository) - { - var exception = Assert.Throws<ArgumentException>( - () => new GetCredentialsRequest( - packageSourceRepository, - HttpStatusCode.Unauthorized)); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForUndefinedStatusCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new GetCredentialsRequest( - packageSourceRepository: "a", - statusCode: (HttpStatusCode)int.MinValue)); - - Assert.Equal("statusCode", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var request = new GetCredentialsRequest( - packageSourceRepository: "a", - statusCode: HttpStatusCode.Unauthorized); - - Assert.Equal("a", request.PackageSourceRepository); - Assert.Equal(HttpStatusCode.Unauthorized, request.StatusCode); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new GetCredentialsRequest( - packageSourceRepository: "a", - statusCode: HttpStatusCode.Unauthorized); - - var json = TestUtilities.Serialize(request); - - Assert.Equal("{\"PackageSourceRepository\":\"a\",\"StatusCode\":\"Unauthorized\"}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"PackageSourceRepository\":\"a\",\"StatusCode\":\"Unauthorized\"}"; - var request = JsonSerializationUtilities.Deserialize<GetCredentialsRequest>(json); - - Assert.Equal("a", request.PackageSourceRepository); - Assert.Equal(HttpStatusCode.Unauthorized, request.StatusCode); - } - - [Theory] - [InlineData("{\"StatusCode\":\"Unauthorized\"}")] - [InlineData("{\"PackageSourceRepository\":null,\"StatusCode\":\"Unauthorized\"}")] - [InlineData("{\"PackageSourceRepository\":\"\",\"StatusCode\":\"Unauthorized\"}")] - public void JsonDeserialization_ThrowsForInvalidPackageSourceRepository(string json) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<GetCredentialsRequest>(json)); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - - [Fact] - public void JsonDeserialization_ThrowsForMissingStatusCode() - { - var json = "{\"PackageSourceRepository\":\"a\"}"; - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<GetCredentialsRequest>(json)); - - Assert.Equal("statusCode", exception.ParamName); - } - - [Theory] - [InlineData("{\"PackageSourceRepository\":\"a\",\"StatusCode\":null}")] - [InlineData("{\"PackageSourceRepository\":\"a\",\"StatusCode\":\"\"}")] - [InlineData("{\"PackageSourceRepository\":\"a\",\"StatusCode\":\"b\"}")] - public void JsonDeserialization_ThrowsForInvalidStatusCodeValue(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<GetCredentialsRequest>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetCredentialsResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetCredentialsResponseTests.cs deleted file mode 100644 index fa452b9d80d..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetCredentialsResponseTests.cs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetCredentialsResponseTests - { - [Fact] - public void Constructor_ThrowsForUndefinedResponseCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new GetCredentialsResponse( - (MessageResponseCode)int.MinValue, - username: "a", - password: "b")); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("a")] - public void Constructor_AllowsAnyUsername(string username) - { - new GetCredentialsResponse(MessageResponseCode.Success, username, password: "b"); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("a")] - public void Constructor_AllowsAnyPassword(string password) - { - new GetCredentialsResponse(MessageResponseCode.Success, username: "a", password: password); - } - - [Theory] - [InlineData(MessageResponseCode.Success, "a", "b")] - [InlineData(MessageResponseCode.NotFound, null, null)] - public void Constructor_InitializesProperties( - MessageResponseCode responseCode, - string username, - string password) - { - var response = new GetCredentialsResponse(responseCode, username, password); - - Assert.Equal(responseCode, response.ResponseCode); - Assert.Equal(username, response.Username); - Assert.Equal(password, response.Password); - } - - [Theory] - [InlineData(MessageResponseCode.NotFound, null, null, "{\"ResponseCode\":\"NotFound\"}")] - [InlineData(MessageResponseCode.Success, "a", "b", "{\"Password\":\"b\",\"ResponseCode\":\"Success\",\"Username\":\"a\"}")] - public void JsonSerialization_ReturnsCorrectJson( - MessageResponseCode responseCode, - string username, - string password, - string expectedJson) - { - var response = new GetCredentialsResponse(responseCode, username, password); - - var actualJson = TestUtilities.Serialize(response); - - Assert.Equal(expectedJson, actualJson); - } - - [Theory] - [InlineData("{\"ResponseCode\":\"NotFound\"}", MessageResponseCode.NotFound, null, null)] - [InlineData("{\"Password\":\"a\",\"ResponseCode\":\"Success\",\"Username\":\"b\"}", MessageResponseCode.Success, "b", "a")] - public void JsonDeserialization_ReturnsCorrectObject( - string json, - MessageResponseCode responseCode, - string username, - string password) - { - var response = JsonSerializationUtilities.Deserialize<GetCredentialsResponse>(json); - - Assert.Equal(responseCode, response.ResponseCode); - Assert.Equal(username, response.Username); - Assert.Equal(password, response.Password); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"Password\":\"a\",\"Username\":\"cc\"}")] - [InlineData("{\"Password\":\"a\",\"ResponseCode\":null,\"Username\":\"c\"}")] - [InlineData("{\"Password\":\"a\",\"ResponseCode\":\"\",\"Username\":\"c\"}")] - [InlineData("{\"Password\":\"a\",\"ResponseCode\":\"b\",\"Username\":\"c\"}")] - public void JsonDeserialization_ThrowsForInvalidResponseCode(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<GetCredentialsResponse>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetFilesInPackageRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetFilesInPackageRequestTests.cs deleted file mode 100644 index 9877485ed5e..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetFilesInPackageRequestTests.cs +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetFilesInPackageRequestTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageSourceRepository(string packageSourceRepository) - { - var exception = Assert.Throws<ArgumentException>( - () => new GetFilesInPackageRequest( - packageSourceRepository, - packageId: "a", - packageVersion: "b")); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageId(string packageId) - { - var exception = Assert.Throws<ArgumentException>( - () => new GetFilesInPackageRequest( - packageSourceRepository: "a", - packageId: packageId, - packageVersion: "b")); - - Assert.Equal("packageId", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageVersion(string packageVersion) - { - var exception = Assert.Throws<ArgumentException>( - () => new GetFilesInPackageRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: packageVersion)); - - Assert.Equal("packageVersion", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var request = new GetFilesInPackageRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c"); - - Assert.Equal("a", request.PackageSourceRepository); - Assert.Equal("b", request.PackageId); - Assert.Equal("c", request.PackageVersion); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new GetFilesInPackageRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c"); - - var json = TestUtilities.Serialize(request); - - Assert.Equal("{\"PackageId\":\"b\",\"PackageSourceRepository\":\"a\",\"PackageVersion\":\"c\"}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"PackageId\":\"a\",\"PackageSourceRepository\":\"b\",\"PackageVersion\":\"c\"}"; - var request = JsonSerializationUtilities.Deserialize<GetFilesInPackageRequest>(json); - - Assert.Equal("b", request.PackageSourceRepository); - Assert.Equal("a", request.PackageId); - Assert.Equal("c", request.PackageVersion); - } - - [Theory] - [InlineData("{}", "packageSourceRepository")] - [InlineData("{\"PackageSourceRepository\":\"b\",\"PackageVersion\":\"c\"}", "packageId")] - [InlineData("{\"PackageId\":null,\"PackageSourceRepository\":\"b\",\"PackageVersion\":\"c\"}", "packageId")] - [InlineData("{\"PackageId\":\"\",\"PackageSourceRepository\":\"b\",\"PackageVersion\":\"c\"}", "packageId")] - [InlineData("{\"PackageId\":\"a\",\"PackageVersion\":\"c\"}", "packageSourceRepository")] - [InlineData("{\"PackageId\":\"a\",\"PackageSourceRepository\":null,\"PackageVersion\":\"c\"}", "packageSourceRepository")] - [InlineData("{\"PackageId\":\"a\",\"PackageSourceRepository\":\"\",\"PackageVersion\":\"c\"}", "packageSourceRepository")] - [InlineData("{\"PackageId\":\"a\",\"PackageSourceRepository\":\"b\"}", "packageVersion")] - [InlineData("{\"PackageId\":\"a\",\"PackageSourceRepository\":\"b\",\"PackageVersion\":null}", "packageVersion")] - [InlineData("{\"PackageId\":\"a\",\"PackageSourceRepository\":\"b\",\"PackageVersion\":\"\"}", "packageVersion")] - public void JsonDeserialization_ThrowsForInvalidStringArgument(string json, string parameterName) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<GetFilesInPackageRequest>(json)); - - Assert.Equal(parameterName, exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetFilesInPackageResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetFilesInPackageResponseTests.cs deleted file mode 100644 index 5c49cf3cac1..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetFilesInPackageResponseTests.cs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetFilesInPackageResponseTests - { - [Fact] - public void Constructor_ThrowsForUndefinedResponseCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new GetFilesInPackageResponse((MessageResponseCode)int.MaxValue, new[] { "a" })); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullCopiedFilesWhenResponseCodeIsSuccess() - { - var exception = Assert.Throws<ArgumentException>( - () => new GetFilesInPackageResponse(MessageResponseCode.Success, files: null)); - - Assert.Equal("files", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForEmptyCopiedFilesWhenResponseCodeIsSuccess() - { - var exception = Assert.Throws<ArgumentException>( - () => new GetFilesInPackageResponse(MessageResponseCode.Success, new string[] { })); - - Assert.Equal("files", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var response = new GetFilesInPackageResponse(MessageResponseCode.Success, new[] { "a" }); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - Assert.Equal(new[] { "a" }, response.Files); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var response = new GetFilesInPackageResponse(MessageResponseCode.Success, new[] { "a" }); - - var json = TestUtilities.Serialize(response); - - Assert.Equal("{\"Files\":[\"a\"],\"ResponseCode\":\"Success\"}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObjectForSuccess() - { - var json = "{\"Files\":[\"a\"],\"ResponseCode\":\"Success\"}"; - var response = JsonSerializationUtilities.Deserialize<GetFilesInPackageResponse>(json); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - Assert.Equal(new[] { "a" }, response.Files); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObjectForNotFound() - { - var json = "{\"ResponseCode\":\"NotFound\"}"; - var response = JsonSerializationUtilities.Deserialize<GetFilesInPackageResponse>(json); - - Assert.Equal(MessageResponseCode.NotFound, response.ResponseCode); - Assert.Null(response.Files); - } - - [Theory] - [InlineData("{\"ResponseCode\":null}")] - [InlineData("{\"ResponseCode\":\"\"}")] - [InlineData("{\"ResponseCode\":\"b\"}")] - public void JsonDeserialization_ThrowsForInvalidResponseCode(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<GetFilesInPackageResponse>(json)); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"ResponseCode\":\"Success\"}")] - [InlineData("{\"Files\":null,\"ResponseCode\":\"Success\"}")] - [InlineData("{\"Files\":[],\"ResponseCode\":\"Success\"}")] - public void JsonDeserialization_ThrowsForInvalidCopiedFiles(string json) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<GetFilesInPackageResponse>(json)); - - Assert.Equal("files", exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetOperationClaimsRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetOperationClaimsRequestTests.cs deleted file mode 100644 index 034b0825f3b..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetOperationClaimsRequestTests.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetOperationClaimsRequestTests - { - private static readonly string _packageSourceRepository = "A"; - private static readonly A _serviceIndex = new A() { B = "C" }; - private static readonly JObject _serviceIndexJson = JObject.FromObject(_serviceIndex); - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageSourceRepository(string packageSourceRepository) - { - var exception = Assert.Throws<ArgumentException>( - () => new GetOperationClaimsRequest(packageSourceRepository, _serviceIndexJson)); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullServiceIndex() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new GetOperationClaimsRequest(_packageSourceRepository, serviceIndex: null)); - - Assert.Equal("serviceIndex", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var request = new GetOperationClaimsRequest(_packageSourceRepository, _serviceIndexJson); - - Assert.Equal(_packageSourceRepository, request.PackageSourceRepository); - Assert.Equal("{\"B\":\"C\"}", request.ServiceIndex.ToString(Formatting.None)); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new GetOperationClaimsRequest(_packageSourceRepository, _serviceIndexJson); - - var json = TestUtilities.Serialize(request); - - Assert.Equal("{\"PackageSourceRepository\":\"A\",\"ServiceIndex\":{\"B\":\"C\"}}", json); - } - - [Theory] - [InlineData("{\"PackageSourceRepository\":\"A\",\"ServiceIndex\":{}}", "{}")] - [InlineData("{\"PackageSourceRepository\":\"A\",\"ServiceIndex\":{\"B\":\"C\"}}", "{\"B\":\"C\"}")] - public void JsonDeserialization_ReturnsCorrectObject(string json, string serviceIndex) - { - var request = JsonSerializationUtilities.Deserialize<GetOperationClaimsRequest>(json); - - Assert.Equal("A", request.PackageSourceRepository); - Assert.Equal(serviceIndex, request.ServiceIndex.ToString(Formatting.None)); - } - - - [Theory] - [InlineData("{\"ServiceIndex\":{}}")] - [InlineData("{\"PackageSourceRepository\":null,\"ServiceIndex\":{}}")] - [InlineData("{\"PackageSourceRepository\":\"\",\"ServiceIndex\":{}}")] - public void JsonDeserialization_ThrowsForInvalidPackageSourceRepository(string json) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<GetOperationClaimsRequest>(json)); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - - [Theory] - [InlineData("{\"PackageSourceRepository\":\"A\"}")] - [InlineData("{\"PackageSourceRepository\":\"A\",\"ServiceIndex\":null}")] - public void JsonDeserialization_ThrowsForInvalidServiceIndex(string json) - { - var exception = Assert.Throws<ArgumentNullException>( - () => JsonSerializationUtilities.Deserialize<GetOperationClaimsRequest>(json)); - - Assert.Equal("serviceIndex", exception.ParamName); - } - - [Theory] - [InlineData("{\"ServiceIndex\":\"\"}")] - [InlineData("{\"ServiceIndex\":3}")] - public void JsonDeserialization_ThrowsForInvalidServiceIndexValue(string json) - { - Assert.Throws<InvalidCastException>( - () => JsonSerializationUtilities.Deserialize<GetOperationClaimsRequest>(json)); - } - - private sealed class A - { - public string B { get; set; } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetOperationClaimsResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetOperationClaimsResponseTests.cs deleted file mode 100644 index 837d7bd90df..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetOperationClaimsResponseTests.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetOperationClaimsResponseTests - { - [Fact] - public void Constructor_ThrowsForNullClaims() - { - var exception = Assert.Throws<ArgumentNullException>(() => new GetOperationClaimsResponse(claims: null)); - - Assert.Equal("claims", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForUndefinedClaims() - { - var claims = new[] { (OperationClaim)int.MaxValue }; - var exception = Assert.Throws<ArgumentException>(() => new GetOperationClaimsResponse(claims)); - - Assert.Equal("claims", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesClaimsProperty() - { - var claims = new[] { OperationClaim.DownloadPackage }; - var response = new GetOperationClaimsResponse(claims); - - Assert.Equal(1, response.Claims.Count); - Assert.Equal(claims[0], response.Claims[0]); - } - - [Fact] - public void Constructor_ClonesClaims() - { - var claims = new[] { OperationClaim.DownloadPackage }; - var response = new GetOperationClaimsResponse(claims); - - Assert.NotSame(claims, response.Claims); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var response = new GetOperationClaimsResponse(new[] { OperationClaim.DownloadPackage }); - - var json = TestUtilities.Serialize(response); - - Assert.Equal("{\"Claims\":[\"DownloadPackage\"]}", json); - } - - [Theory] - [InlineData("{\"Claims\":[]}", new OperationClaim[] { })] - [InlineData("{\"Claims\":[\"DownloadPackage\"]}", new[] { OperationClaim.DownloadPackage })] - public void JsonDeserialization_ReturnsCorrectObject(string json, OperationClaim[] claims) - { - var response = JsonSerializationUtilities.Deserialize<GetOperationClaimsResponse>(json); - - Assert.Equal(claims.Length, response.Claims.Count); - - foreach (var claim in claims) - { - Assert.Contains(claim, response.Claims); - } - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"Claims\":null}")] - [InlineData("{\"Claims\":\"\"}")] - public void JsonDeserialization_ThrowsForInvalidClaims(string json) - { - var exception = Assert.Throws<ArgumentNullException>( - () => JsonSerializationUtilities.Deserialize<GetOperationClaimsResponse>(json)); - - Assert.Equal("claims", exception.ParamName); - } - - [Fact] - public void JsonDeserialization_ThrowsForInvalidClaimsValue() - { - var json = "{\"Claims\":[\"abc\"]}"; - - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<GetOperationClaimsResponse>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageHashRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageHashRequestTests.cs deleted file mode 100644 index 0f183d2591f..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageHashRequestTests.cs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetPackageHashRequestTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageSourceRepository(string packageSourceRepository) - { - var exception = Assert.Throws<ArgumentException>( - () => new GetPackageHashRequest( - packageSourceRepository, - packageId: "a", - packageVersion: "b", - hashAlgorithm: "c")); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageId(string packageId) - { - var exception = Assert.Throws<ArgumentException>( - () => new GetPackageHashRequest( - packageSourceRepository: "a", - packageId: packageId, - packageVersion: "b", - hashAlgorithm: "c")); - - Assert.Equal("packageId", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageVersion(string packageVersion) - { - var exception = Assert.Throws<ArgumentException>( - () => new GetPackageHashRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: packageVersion, - hashAlgorithm: "c")); - - Assert.Equal("packageVersion", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyHashAlgorithm(string hashAlgorithm) - { - var exception = Assert.Throws<ArgumentException>( - () => new GetPackageHashRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c", - hashAlgorithm: hashAlgorithm)); - - Assert.Equal("hashAlgorithm", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var request = new GetPackageHashRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c", - hashAlgorithm: "d"); - - Assert.Equal("a", request.PackageSourceRepository); - Assert.Equal("b", request.PackageId); - Assert.Equal("c", request.PackageVersion); - Assert.Equal("d", request.HashAlgorithm); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new GetPackageHashRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c", - hashAlgorithm: "d"); - - var json = TestUtilities.Serialize(request); - - Assert.Equal("{\"HashAlgorithm\":\"d\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"a\",\"PackageVersion\":\"c\"}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"HashAlgorithm\":\"a\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}"; - var request = JsonSerializationUtilities.Deserialize<GetPackageHashRequest>(json); - - Assert.Equal("a", request.HashAlgorithm); - Assert.Equal("b", request.PackageId); - Assert.Equal("c", request.PackageSourceRepository); - Assert.Equal("d", request.PackageVersion); - } - - [Theory] - [InlineData("{}", "packageSourceRepository")] - [InlineData("{\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}", "hashAlgorithm")] - [InlineData("{\"HashAlgorithm\":null,\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}", "hashAlgorithm")] - [InlineData("{\"HashAlgorithm\":\"\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}", "hashAlgorithm")] - [InlineData("{\"HashAlgorithm\":\"a\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}", "packageId")] - [InlineData("{\"HashAlgorithm\":\"a\",\"PackageId\":null,\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}", "packageId")] - [InlineData("{\"HashAlgorithm\":\"a\",\"PackageId\":\"\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"d\"}", "packageId")] - [InlineData("{\"HashAlgorithm\":\"a\",\"PackageId\":\"b\",\"PackageVersion\":\"d\"}", "packageSourceRepository")] - [InlineData("{\"HashAlgorithm\":\"a\",\"PackageId\":\"b\",\"PackageSourceRepository\":null,\"PackageVersion\":\"d\"}", "packageSourceRepository")] - [InlineData("{\"HashAlgorithm\":\"a\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"\",\"PackageVersion\":\"d\"}", "packageSourceRepository")] - [InlineData("{\"HashAlgorithm\":\"a\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\"}", "packageVersion")] - [InlineData("{\"HashAlgorithm\":\"a\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":null}", "packageVersion")] - [InlineData("{\"HashAlgorithm\":\"a\",\"PackageId\":\"b\",\"PackageSourceRepository\":\"c\",\"PackageVersion\":\"\"}", "packageVersion")] - public void JsonDeserialization_ThrowsForInvalidStringArgument(string json, string parameterName) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<GetPackageHashRequest>(json)); - - Assert.Equal(parameterName, exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageHashResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageHashResponseTests.cs deleted file mode 100644 index 0e1f25b3a1e..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageHashResponseTests.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetPackageHashResponseTests - { - [Fact] - public void Constructor_ThrowsForUndefinedResponseCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new GetPackageHashResponse((MessageResponseCode)int.MaxValue, hash: "a")); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyHashWhenResponseCodeIsSuccess(string hash) - { - var exception = Assert.Throws<ArgumentException>( - () => new GetPackageHashResponse(MessageResponseCode.Success, hash)); - - Assert.Equal("hash", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var response = new GetPackageHashResponse(MessageResponseCode.Success, hash: "a"); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - Assert.Equal("a", response.Hash); - } - - [Theory] - [InlineData(MessageResponseCode.Success, "a", "{\"Hash\":\"a\",\"ResponseCode\":\"Success\"}")] - [InlineData(MessageResponseCode.NotFound, null, "{\"ResponseCode\":\"NotFound\"}")] - [InlineData(MessageResponseCode.Error, null, "{\"ResponseCode\":\"Error\"}")] - public void JsonSerialization_ReturnsCorrectJson( - MessageResponseCode responseCode, - string hash, - string expectedJson) - { - var response = new GetPackageHashResponse(responseCode, hash); - - var actualJson = TestUtilities.Serialize(response); - - Assert.Equal(expectedJson, actualJson); - } - - [Theory] - [InlineData("{\"Hash\":\"a\",\"ResponseCode\":\"Success\"}", MessageResponseCode.Success, "a")] - [InlineData("{\"ResponseCode\":\"NotFound\"}", MessageResponseCode.NotFound, null)] - [InlineData("{\"ResponseCode\":\"Error\"}", MessageResponseCode.Error, null)] - public void JsonDeserialization_ReturnsCorrectObject( - string json, - MessageResponseCode responseCode, - string hash) - { - var response = JsonSerializationUtilities.Deserialize<GetPackageHashResponse>(json); - - Assert.Equal(responseCode, response.ResponseCode); - Assert.Equal(hash, response.Hash); - } - - [Theory] - [InlineData("{\"ResponseCode\":null}")] - [InlineData("{\"ResponseCode\":\"\"}")] - [InlineData("{\"ResponseCode\":\"b\"}")] - public void JsonDeserialization_ThrowsForInvalidResponseCode(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<GetPackageHashResponse>(json)); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"ResponseCode\":\"Success\"}")] - [InlineData("{\"Hash\":null,\"ResponseCode\":\"Success\"}")] - [InlineData("{\"Hash\":\"\",\"ResponseCode\":\"Success\"}")] - public void JsonDeserialization_ThrowsForInvalidHash(string json) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<GetPackageHashResponse>(json)); - - Assert.Equal("hash", exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageVersionsRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageVersionsRequestTests.cs deleted file mode 100644 index da4c5ad0f28..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageVersionsRequestTests.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetPackageVersionsRequestTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageSourceRepository(string packageSourceRepository) - { - var exception = Assert.Throws<ArgumentException>( - () => new GetPackageVersionsRequest( - packageSourceRepository, - packageId: "a")); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageId(string packageId) - { - var exception = Assert.Throws<ArgumentException>( - () => new GetPackageVersionsRequest( - packageSourceRepository: "a", - packageId: packageId)); - - Assert.Equal("packageId", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var request = new GetPackageVersionsRequest( - packageSourceRepository: "a", - packageId: "b"); - - Assert.Equal("a", request.PackageSourceRepository); - Assert.Equal("b", request.PackageId); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new GetPackageVersionsRequest( - packageSourceRepository: "a", - packageId: "b"); - - var json = TestUtilities.Serialize(request); - - Assert.Equal("{\"PackageId\":\"b\",\"PackageSourceRepository\":\"a\"}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"PackageId\":\"a\",\"PackageSourceRepository\":\"b\"}"; - var request = JsonSerializationUtilities.Deserialize<GetPackageVersionsRequest>(json); - - Assert.Equal("b", request.PackageSourceRepository); - Assert.Equal("a", request.PackageId); - } - - [Theory] - [InlineData("{}", "packageSourceRepository")] - [InlineData("{\"PackageSourceRepository\":\"b\"}", "packageId")] - [InlineData("{\"PackageId\":null,\"PackageSourceRepository\":\"b\"}", "packageId")] - [InlineData("{\"PackageId\":\"\",\"PackageSourceRepository\":\"b\"}", "packageId")] - [InlineData("{\"PackageId\":\"a\"}", "packageSourceRepository")] - [InlineData("{\"PackageId\":\"a\",\"PackageSourceRepository\":null}", "packageSourceRepository")] - [InlineData("{\"PackageId\":\"a\",\"PackageSourceRepository\":\"\"}", "packageSourceRepository")] - public void JsonDeserialization_ThrowsForInvalidPackageSourceRepository(string json, string parameterName) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<GetPackageVersionsRequest>(json)); - - Assert.Equal(parameterName, exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageVersionsResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageVersionsResponseTests.cs deleted file mode 100644 index a58ee09dcc0..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetPackageVersionsResponseTests.cs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetPackageVersionsResponseTests - { - [Fact] - public void Constructor_ThrowsForUndefinedResponseCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new GetPackageVersionsResponse((MessageResponseCode)int.MaxValue, new[] { "a" })); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullVersionsWhenResponseCodeIsSuccess() - { - var exception = Assert.Throws<ArgumentException>( - () => new GetPackageVersionsResponse(MessageResponseCode.Success, versions: null)); - - Assert.Equal("versions", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForEmptyVersionsWhenResponseCodeIsSuccess() - { - var exception = Assert.Throws<ArgumentException>( - () => new GetPackageVersionsResponse(MessageResponseCode.Success, new string[] { })); - - Assert.Equal("versions", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var response = new GetPackageVersionsResponse(MessageResponseCode.Success, new[] { "a" }); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - Assert.Equal(new[] { "a" }, response.Versions); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var response = new GetPackageVersionsResponse(MessageResponseCode.Success, new[] { "a" }); - - var json = TestUtilities.Serialize(response); - - Assert.Equal("{\"ResponseCode\":\"Success\",\"Versions\":[\"a\"]}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObjectForSuccess() - { - var json = "{\"ResponseCode\":\"Success\",\"Versions\":[\"a\"]}"; - var response = JsonSerializationUtilities.Deserialize<GetPackageVersionsResponse>(json); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - Assert.Equal(new[] { "a" }, response.Versions); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObjectForNotFound() - { - var json = "{\"ResponseCode\":\"NotFound\"}"; - var response = JsonSerializationUtilities.Deserialize<GetPackageVersionsResponse>(json); - - Assert.Equal(MessageResponseCode.NotFound, response.ResponseCode); - Assert.Null(response.Versions); - } - - [Theory] - [InlineData("{\"ResponseCode\":null}")] - [InlineData("{\"ResponseCode\":\"\"}")] - [InlineData("{\"ResponseCode\":\"b\"}")] - public void JsonDeserialization_ThrowsForInvalidResponseCode(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<GetPackageVersionsResponse>(json)); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"ResponseCode\":\"Success\"}")] - [InlineData("{\"ResponseCode\":\"Success\",\"Versions\":null}")] - [InlineData("{\"ResponseCode\":\"Success\",\"Versions\":[]}")] - public void JsonDeserialization_ThrowsForInvalidVersions(string json) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<GetPackageVersionsResponse>(json)); - - Assert.Equal("versions", exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetServiceIndexRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetServiceIndexRequestTests.cs deleted file mode 100644 index 467b7d682b1..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetServiceIndexRequestTests.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetServiceIndexRequestTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageSourceRepository(string packageSourceRepository) - { - var exception = Assert.Throws<ArgumentException>( - () => new GetServiceIndexRequest(packageSourceRepository)); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesPackageSourceRepositoryProperty() - { - var request = new GetServiceIndexRequest(packageSourceRepository: "a"); - - Assert.Equal("a", request.PackageSourceRepository); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new GetServiceIndexRequest(packageSourceRepository: "a"); - - var json = TestUtilities.Serialize(request); - - Assert.Equal("{\"PackageSourceRepository\":\"a\"}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"PackageSourceRepository\":\"a\"}"; - var request = JsonSerializationUtilities.Deserialize<GetServiceIndexRequest>(json); - - Assert.Equal("a", request.PackageSourceRepository); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"PackageSourceRepository\":null}")] - [InlineData("{\"PackageSourceRepository\":\"\"}")] - public void JsonDeserialization_ThrowsForInvalidPackageSourceRepository(string json) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<GetServiceIndexRequest>(json)); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetServiceIndexResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetServiceIndexResponseTests.cs deleted file mode 100644 index 514920e992c..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/GetServiceIndexResponseTests.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetServiceIndexResponseTests - { - [Fact] - public void Constructor_ThrowsForUndefinedResponseCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new GetServiceIndexResponse((MessageResponseCode)int.MaxValue, JObject.Parse("{}"))); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullServiceIndexWhenResponseCodeIsSuccess() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new GetServiceIndexResponse(MessageResponseCode.Success, serviceIndex: null)); - - Assert.Equal("serviceIndex", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var serviceIndex = JObject.Parse("{}"); - var response = new GetServiceIndexResponse(MessageResponseCode.Success, serviceIndex); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - Assert.Same(serviceIndex, response.ServiceIndex); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var serviceIndex = JObject.Parse("{\"a\":\"b\"}"); - var response = new GetServiceIndexResponse(MessageResponseCode.Success, serviceIndex); - - var json = TestUtilities.Serialize(response); - - Assert.Equal("{\"ResponseCode\":\"Success\",\"ServiceIndex\":{\"a\":\"b\"}}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObjectForSuccess() - { - var json = "{\"ResponseCode\":\"Success\",\"ServiceIndex\":{\"a\":\"b\"}}"; - var response = JsonSerializationUtilities.Deserialize<GetServiceIndexResponse>(json); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - Assert.Equal("{\"a\":\"b\"}", response.ServiceIndex.ToString(Formatting.None)); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObjectForNotFound() - { - var json = "{\"ResponseCode\":\"NotFound\"}"; - var response = JsonSerializationUtilities.Deserialize<GetServiceIndexResponse>(json); - - Assert.Equal(MessageResponseCode.NotFound, response.ResponseCode); - Assert.Null(response.ServiceIndex); - } - - [Theory] - [InlineData("{\"ResponseCode\":null}")] - [InlineData("{\"ResponseCode\":\"\"}")] - [InlineData("{\"ResponseCode\":\"b\"}")] - public void JsonDeserialization_ThrowsForInvalidResponseCode(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<GetServiceIndexResponse>(json)); - } - - [Theory] - [InlineData("{}", typeof(ArgumentNullException))] - [InlineData("{\"ResponseCode\":\"Success\"}", typeof(ArgumentNullException))] - [InlineData("{\"ResponseCode\":\"Success\",\"ServiceIndex\":null}", typeof(ArgumentNullException))] - [InlineData("{\"ResponseCode\":\"Success\",\"ServiceIndex\":\"a\"}", typeof(InvalidCastException))] - [InlineData("{\"ResponseCode\":\"Success\",\"ServiceIndex\":1}", typeof(InvalidCastException))] - public void JsonDeserialization_ThrowsForInvalidServiceIndex(string json, Type exceptionType) - { - var exception = Assert.Throws( - exceptionType, - () => JsonSerializationUtilities.Deserialize<GetServiceIndexResponse>(json)); - - if (exception is ArgumentNullException) - { - Assert.Equal("serviceIndex", ((ArgumentNullException)exception).ParamName); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/HandshakeRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/HandshakeRequestTests.cs deleted file mode 100644 index 060db83b702..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/HandshakeRequestTests.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class HandshakeRequestTests - { - private static readonly SemanticVersion _version1_0_0 = new SemanticVersion(major: 1, minor: 0, patch: 0); - private static readonly SemanticVersion _version2_0_0 = new SemanticVersion(major: 2, minor: 0, patch: 0); - - [Fact] - public void Constructor_ThrowsForNullProtocolVersion() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new HandshakeRequest(protocolVersion: null, minimumProtocolVersion: _version1_0_0)); - - Assert.Equal("protocolVersion", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullMinimumProtocolVersion() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new HandshakeRequest(_version1_0_0, minimumProtocolVersion: null)); - - Assert.Equal("minimumProtocolVersion", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForInvalidVersionRange() - { - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new HandshakeRequest(_version1_0_0, _version2_0_0)); - - Assert.Equal("protocolVersion", exception.ParamName); - Assert.Equal(_version1_0_0, exception.ActualValue); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var request = new HandshakeRequest(_version2_0_0, _version1_0_0); - - Assert.Equal(_version2_0_0, request.ProtocolVersion); - Assert.Equal(_version1_0_0, request.MinimumProtocolVersion); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new HandshakeRequest(_version2_0_0, _version1_0_0); - - var json = TestUtilities.Serialize(request); - - Assert.Equal("{\"ProtocolVersion\":\"2.0.0\",\"MinimumProtocolVersion\":\"1.0.0\"}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"ProtocolVersion\":\"2.0.0\",\"MinimumProtocolVersion\":\"1.0.0\"}"; - - var request = JsonSerializationUtilities.Deserialize<HandshakeRequest>(json); - - Assert.Equal(_version2_0_0, request.ProtocolVersion); - Assert.Equal(_version1_0_0, request.MinimumProtocolVersion); - } - - [Theory] - [InlineData("{\"MinimumProtocolVersion\":\"1.0.0\"}", "protocolVersion")] - [InlineData("{\"ProtocolVersion\":null,\"MinimumProtocolVersion\":\"1.0.0\"}", "protocolVersion")] - [InlineData("{\"ProtocolVersion\":\"1.0.0\"}", "minimumProtocolVersion")] - [InlineData("{\"ProtocolVersion\":\"1.0.0\",\"MinimumProtocolVersion\":null}", "minimumProtocolVersion")] - public void JsonDeserialization_ThrowsForNullVersion(string json, string parameterName) - { - var exception = Assert.Throws<ArgumentNullException>( - () => JsonSerializationUtilities.Deserialize<HandshakeRequest>(json)); - - Assert.Equal(parameterName, exception.ParamName); - } - - [Theory] - [InlineData("{\"ProtocolVersion\":\"\",\"MinimumProtocolVersion\":\"1.0.0\"}", "protocolVersion")] - [InlineData("{\"ProtocolVersion\":\" \",\"MinimumProtocolVersion\":\"1.0.0\"}", "protocolVersion")] - [InlineData("{\"ProtocolVersion\":\"a\",\"MinimumProtocolVersion\":\"1.0.0\"}", "protocolVersion")] - [InlineData("{\"ProtocolVersion\":3,\"MinimumProtocolVersion\":\"1.0.0\"}", "protocolVersion")] - [InlineData("{\"ProtocolVersion\":false,\"MinimumProtocolVersion\":\"1.0.0\"}", "protocolVersion")] - [InlineData("{\"ProtocolVersion\":\"1.0.0\",\"MinimumProtocolVersion\":\"\"}", "minimumProtocolVersion")] - [InlineData("{\"ProtocolVersion\":\"1.0.0\",\"MinimumProtocolVersion\":\" \"}", "minimumProtocolVersion")] - [InlineData("{\"ProtocolVersion\":\"1.0.0\",\"MinimumProtocolVersion\":\"a\"}", "minimumProtocolVersion")] - [InlineData("{\"ProtocolVersion\":\"1.0.0\",\"MinimumProtocolVersion\":3,}", "minimumProtocolVersion")] - [InlineData("{\"ProtocolVersion\":\"1.0.0\",\"MinimumProtocolVersion\":false}", "minimumProtocolVersion")] - public void JsonDeserialization_ThrowsForInvalidVersion(string json, string parameterName) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<HandshakeRequest>(json)); - - Assert.Equal("value", exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/HandshakeResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/HandshakeResponseTests.cs deleted file mode 100644 index d04b68ef41c..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/HandshakeResponseTests.cs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class HandshakeResponseTests - { - private static readonly SemanticVersion _version = new SemanticVersion(major: 1, minor: 0, patch: 0); - - [Fact] - public void Constructor_ThrowsForUndefinedMessageResponseCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new HandshakeResponse((MessageResponseCode)int.MinValue, _version)); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullProtocolVersionIfResponseCodeIsSuccess() - { - var exception = Assert.Throws<ArgumentException>( - () => new HandshakeResponse(MessageResponseCode.Success, protocolVersion: null)); - - Assert.Equal("protocolVersion", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNonNullProtocolVersionIfResponseCodeIsError() - { - var exception = Assert.Throws<ArgumentException>( - () => new HandshakeResponse(MessageResponseCode.Error, _version)); - - Assert.Equal("protocolVersion", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesPropertiesForSuccess() - { - var response = new HandshakeResponse(MessageResponseCode.Success, _version); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - Assert.Equal(_version, response.ProtocolVersion); - } - - [Fact] - public void Constructor_InitializesPropertiesForError() - { - var response = new HandshakeResponse(MessageResponseCode.Error, protocolVersion: null); - - Assert.Equal(MessageResponseCode.Error, response.ResponseCode); - Assert.Null(response.ProtocolVersion); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var response = new HandshakeResponse(MessageResponseCode.Success, _version); - - var json = TestUtilities.Serialize(response); - - Assert.Equal("{\"ResponseCode\":\"Success\",\"ProtocolVersion\":\"1.0.0\"}", json); - } - - [Theory] - [InlineData("{\"ResponseCode\":\"Success\",\"ProtocolVersion\":\"1.0.0\"}", MessageResponseCode.Success, "1.0.0")] - [InlineData("{\"ResponseCode\":\"Error\"}", MessageResponseCode.Error, null)] - public void JsonDeserialization_ReturnsCorrectObject( - string json, - MessageResponseCode responseCode, - string versionString) - { - var version = versionString == null ? null : SemanticVersion.Parse(versionString); - - var response = JsonSerializationUtilities.Deserialize<HandshakeResponse>(json); - - Assert.Equal(responseCode, response.ResponseCode); - Assert.Equal(version, response.ProtocolVersion); - } - - [Theory] - [InlineData("{\"ResponseCode\":\"Success\"}", "protocolVersion")] - [InlineData("{\"ResponseCode\":\"Success\",\"ProtocolVersion\":null}", "protocolVersion")] - [InlineData("{\"ResponseCode\":\"Success\",\"ProtocolVersion\":\"\"}", "value")] - [InlineData("{\"ResponseCode\":\"Success\",\"ProtocolVersion\":\"a\"}", "value")] - [InlineData("{\"ResponseCode\":\"Error\",\"ProtocolVersion\":\"1.0.0\"}", "protocolVersion")] - public void JsonDeserialization_ThrowsForInvalidProtocolVersion(string json, string parameterName) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<HandshakeResponse>(json)); - - Assert.Equal(parameterName, exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/InitializeRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/InitializeRequestTests.cs deleted file mode 100644 index fb130a14497..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/InitializeRequestTests.cs +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class InitializeRequestTests - { - private static readonly TimeSpan _requestTimeout = new TimeSpan(days: 1, hours: 2, minutes: 3, seconds: 4, milliseconds: 5); - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyClientVersion(string clientVersion) - { - var exception = Assert.Throws<ArgumentException>( - () => new InitializeRequest( - clientVersion, - culture: "a", - requestTimeout: TimeSpan.MaxValue)); - - Assert.Equal("clientVersion", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyCulture(string culture) - { - var exception = Assert.Throws<ArgumentException>( - () => new InitializeRequest( - clientVersion: "1.0.0", - culture: culture, - requestTimeout: TimeSpan.MaxValue)); - - Assert.Equal("culture", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForZeroRequestTimeout() - { - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new InitializeRequest( - clientVersion: "a", - culture: "b", - requestTimeout: TimeSpan.Zero)); - - Assert.Equal("requestTimeout", exception.ParamName); - Assert.Equal(TimeSpan.Zero, exception.ActualValue); - } - - [Fact] - public void Constructor_ThrowsForNegativeRequestTimeout() - { - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new InitializeRequest( - clientVersion: "a", - culture: "b", - requestTimeout: TimeSpan.FromSeconds(-1))); - - Assert.Equal("requestTimeout", exception.ParamName); - Assert.Equal(TimeSpan.FromSeconds(-1), exception.ActualValue); - } - - [Fact] - public void Constructor_ThrowsForTooLargeRequestTimeout() - { - var milliseconds = int.MaxValue + 1L; - - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new InitializeRequest( - clientVersion: "a", - culture: "b", - requestTimeout: TimeSpan.FromMilliseconds(milliseconds))); - - Assert.Equal("requestTimeout", exception.ParamName); - Assert.Equal(TimeSpan.FromMilliseconds(milliseconds), exception.ActualValue); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var request = new InitializeRequest( - clientVersion: "a", - culture: "b", - requestTimeout: _requestTimeout); - - Assert.Equal("a", request.ClientVersion); - Assert.Equal("b", request.Culture); - Assert.Equal(_requestTimeout, request.RequestTimeout); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new InitializeRequest( - clientVersion: "a", - culture: "b", - requestTimeout: _requestTimeout); - - var actualJson = TestUtilities.Serialize(request); - var expectedJson = "{\"ClientVersion\":\"a\",\"Culture\":\"b\",\"RequestTimeout\":\"1.02:03:04.0050000\"}"; - - Assert.Equal(expectedJson, actualJson); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"ClientVersion\":\"a\",\"Culture\":\"b\",\"RequestTimeout\":\"1.02:03:04.0050000\"}"; - - var request = JsonSerializationUtilities.Deserialize<InitializeRequest>(json); - - Assert.NotNull(request); - Assert.Equal("a", request.ClientVersion); - Assert.Equal("b", request.Culture); - Assert.Equal(_requestTimeout, request.RequestTimeout); - } - - [Theory] - [InlineData("{\"Culture\":\"b\",\"RequestTimeout\":\"1.02:03:04.0050000\"}", "clientVersion")] - [InlineData("{\"ClientVersion\":null,\"Culture\":\"b\",\"RequestTimeout\":\"1.02:03:04.0050000\"}", "clientVersion")] - [InlineData("{\"ClientVersion\":\"\",\"Culture\":\"b\",\"RequestTimeout\":\"1.02:03:04.0050000\"}", "clientVersion")] - [InlineData("{\"ClientVersion\":\"a\",\"RequestTimeout\":\"1.02:03:04.0050000\"}", "culture")] - [InlineData("{\"ClientVersion\":\"a\",\"Culture\":null,\"RequestTimeout\":\"1.02:03:04.0050000\"}", "culture")] - [InlineData("{\"ClientVersion\":\"a\",\"Culture\":\"\",\"RequestTimeout\":\"1.02:03:04.0050000\"}", "culture")] - public void JsonDeserialization_ThrowsForNullOrEmptyStringProperties(string json, string parameterName) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<InitializeRequest>(json)); - - Assert.Equal(parameterName, exception.ParamName); - } - - [Theory] - [InlineData("{\"ClientVersion\":\"a\",\"Culture\":\"b\",\"RequestTimeout\":null}")] - [InlineData("{\"ClientVersion\":\"a\",\"Culture\":\"b\",\"RequestTimeout\":\"a\"}")] - public void JsonDeserialization_ThrowsForInvalidRequestTimeout(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<InitializeRequest>(json)); - } - - [Theory] - [InlineData("{\"ClientVersion\":\"a\",\"Culture\":\"b\"}")] - [InlineData("{\"ClientVersion\":\"a\",\"Culture\":\"b\",\"RequestTimeout\":\"-00:01:00\"}")] - public void JsonDeserialization_ThrowsForInvalidRequestTimeoutValue(string json) - { - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => JsonSerializationUtilities.Deserialize<InitializeRequest>(json)); - - Assert.Equal("requestTimeout", exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/InitializeResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/InitializeResponseTests.cs deleted file mode 100644 index e468936e833..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/InitializeResponseTests.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class InitializeResponseTests - { - [Fact] - public void Constructor_ThrowsForUndefinedResponseCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new InitializeResponse((MessageResponseCode)int.MinValue)); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesResponseCodeProperty() - { - var response = new InitializeResponse(MessageResponseCode.Success); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var response = new InitializeResponse(MessageResponseCode.Success); - - var json = TestUtilities.Serialize(response); - - Assert.Equal("{\"ResponseCode\":\"Success\"}", json); - } - - [Theory] - [InlineData("{\"ResponseCode\":\"Success\"}", MessageResponseCode.Success)] - [InlineData("{\"ResponseCode\":\"Error\"}", MessageResponseCode.Error)] - public void JsonDeserialization_ReturnsCorrectObject(string json, MessageResponseCode responseCode) - { - var response = JsonSerializationUtilities.Deserialize<InitializeResponse>(json); - - Assert.Equal(responseCode, response.ResponseCode); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"ResponseCode\":null}")] - [InlineData("{\"ResponseCode\":\"\"}")] - [InlineData("{\"ResponseCode\":\"abc\"}")] - public void JsonDeserialization_ThrowsForInvalidResponseCode(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<InitializeResponse>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/LogRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/LogRequestTests.cs deleted file mode 100644 index d3f7978e1cb..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/LogRequestTests.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using NuGet.Common; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class LogRequestTests - { - [Fact] - public void Constructor_ThrowsForUndefinedLogLevel() - { - var exception = Assert.Throws<ArgumentException>( - () => new LogRequest((LogLevel)int.MinValue, message: "a")); - - Assert.Equal("logLevel", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyMessage(string message) - { - var exception = Assert.Throws<ArgumentException>( - () => new LogRequest(LogLevel.Information, message)); - - Assert.Equal("message", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var request = new LogRequest(LogLevel.Minimal, message: "a"); - - Assert.Equal(LogLevel.Minimal, request.LogLevel); - Assert.Equal("a", request.Message); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new LogRequest(LogLevel.Verbose, message: "a"); - - var json = TestUtilities.Serialize(request); - - Assert.Equal("{\"LogLevel\":\"Verbose\",\"Message\":\"a\"}", json); - } - - [Theory] - [InlineData("{\"LogLevel\":\"Warning\",\"Message\":\"a\"}", "a")] - [InlineData("{\"LogLevel\":\"Warning\",\"Message\":3}", "3")] - public void JsonDeserialization_ReturnsCorrectObject(string json, string message) - { - var request = JsonSerializationUtilities.Deserialize<LogRequest>(json); - - Assert.Equal(LogLevel.Warning, request.LogLevel); - Assert.Equal(message, request.Message); - } - - [Theory] - [InlineData("", typeof(ArgumentException))] - [InlineData("{}", typeof(ArgumentException))] - [InlineData("{\"Message\":\"a\"}", typeof(JsonSerializationException))] - [InlineData("{\"LogLevel\":null,\"Message\":\"a\"}", typeof(JsonSerializationException))] - [InlineData("{\"LogLevel\":\"\",\"Message\":\"a\"}", typeof(JsonSerializationException))] - [InlineData("{\"LogLevel\":\"abc\",\"Message\":\"a\"}", typeof(JsonSerializationException))] - [InlineData("{\"LogLevel\":\"Debug\"}", typeof(ArgumentException))] - [InlineData("{\"LogLevel\":\"Debug\",\"Message\":null}", typeof(ArgumentException))] - [InlineData("{\"LogLevel\":\"Debug\",\"Message\":\"\"}", typeof(ArgumentException))] - public void JsonDeserialization_ThrowsForInvalidJson(string json, Type exceptionType) - { - Assert.Throws(exceptionType, () => JsonSerializationUtilities.Deserialize<LogRequest>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/LogResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/LogResponseTests.cs deleted file mode 100644 index 21daf90a20d..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/LogResponseTests.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class LogResponseTests - { - [Fact] - public void Constructor_ThrowsForUndefinedResponseCode() - { - var exception = Assert.Throws<ArgumentException>(() => new LogResponse((MessageResponseCode)int.MaxValue)); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesResponseCodeProperty() - { - var response = new LogResponse(MessageResponseCode.Success); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var response = new LogResponse(MessageResponseCode.Success); - - var json = TestUtilities.Serialize(response); - - Assert.Equal("{\"ResponseCode\":\"Success\"}", json); - } - - [Theory] - [InlineData("{\"ResponseCode\":\"Success\"}", MessageResponseCode.Success)] - [InlineData("{\"ResponseCode\":\"Error\"}", MessageResponseCode.Error)] - public void JsonDeserialization_ReturnsCorrectObject(string json, MessageResponseCode responseCode) - { - var response = JsonSerializationUtilities.Deserialize<LogResponse>(json); - - Assert.Equal(responseCode, response.ResponseCode); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"ResponseCode\":null}")] - [InlineData("{\"ResponseCode\":\"\"}")] - [InlineData("{\"ResponseCode\":\"abc\"}")] - public void JsonDeserialization_ThrowsForInvalidResponseCode(string json) - { - Assert.Throws<JsonSerializationException>(() => JsonSerializationUtilities.Deserialize<LogResponse>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/MessageTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/MessageTests.cs deleted file mode 100644 index b0e00575a91..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/MessageTests.cs +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class MessageTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyRequestId(string requestId) - { - var exception = Assert.Throws<ArgumentException>( - () => new Message(requestId, MessageType.Cancel, MessageMethod.None)); - - Assert.Equal("requestId", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForUndefinedType() - { - var exception = Assert.Throws<ArgumentException>( - () => new Message("requestId", (MessageType)int.MinValue, MessageMethod.None)); - - Assert.Equal("type", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForUndefinedMethod() - { - var exception = Assert.Throws<ArgumentException>( - () => new Message("requestId", MessageType.Fault, (MessageMethod)int.MinValue)); - - Assert.Equal("method", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var payload = new { E = 7 }; - var message = new Message("a", MessageType.Request, MessageMethod.None, JObject.FromObject(payload)); - - Assert.Equal("a", message.RequestId); - Assert.Equal(MessageType.Request, message.Type); - Assert.Equal(MessageMethod.None, message.Method); - Assert.Equal("{\"E\":7}", message.Payload.ToString(Formatting.None)); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var version = new SemanticVersion(major: 1, minor: 2, patch: 3); - var request = new HandshakeRequest(protocolVersion: version, minimumProtocolVersion: version); - var payload = JsonSerializationUtilities.FromObject(request); - var message = new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.None, - payload: payload); - - var actualJson = TestUtilities.Serialize(message); - var expectedJson = "{\"RequestId\":\"a\",\"Type\":\"Request\",\"Method\":\"None\",\"Payload\":{\"ProtocolVersion\":\"1.2.3\",\"MinimumProtocolVersion\":\"1.2.3\"}}"; - - Assert.Equal(expectedJson, actualJson); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"RequestId\":\"a\",\"Type\":\"Request\",\"Method\":\"None\",\"Payload\":{\"ProtocolVersion\":\"c\",\"MinimumProtocolVersion\":\"d\"}}"; - - var message = JsonSerializationUtilities.Deserialize<Message>(json); - - Assert.NotNull(message); - Assert.Equal("a", message.RequestId); - Assert.Equal(MessageType.Request, message.Type); - Assert.Equal(MessageMethod.None, message.Method); - Assert.Equal("{\"ProtocolVersion\":\"c\",\"MinimumProtocolVersion\":\"d\"}", message.Payload.ToString(Formatting.None)); - } - - [Theory] - [InlineData("{\"Type\":\"Request\",\"Method\":\"None\",\"Payload\":{\"E\":1}}")] - [InlineData("{\"RequestId\":null,\"Type\":\"Request\",\"Method\":\"None\",\"Payload\":{\"E\":1}}")] - [InlineData("{\"RequestId\":\"\",\"Type\":\"Request\",\"Method\":\"None\",\"Payload\":{\"E\":1}}")] - public void JsonDeserialization_ThrowsForNullOrEmptyRequestId(string json) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<Message>(json)); - - Assert.Equal("requestId", exception.ParamName); - } - - [Theory] - [InlineData("{\"RequestId\":\"a\",\"Method\":\"None\"}")] - [InlineData("{\"RequestId\":\"a\",\"Type\":null,\"Method\":\"None\"}")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"\",\"Method\":\"None\"}")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"abc\",\"Method\":\"None\"}")] - public void JsonDeserialization_ThrowsForUndefinedType(string json) - { - Assert.Throws<JsonSerializationException>(() => JsonSerializationUtilities.Deserialize<Message>(json)); - } - - [Theory] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Request\"}")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Request\",\"Method\":null}")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Request\",\"Method\":\"\"}")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Request\",\"Method\":\"abc\"}")] - public void JsonDeserialization_ThrowsForUndefinedMethod(string json) - { - Assert.Throws<JsonSerializationException>(() => JsonSerializationUtilities.Deserialize<Message>(json)); - } - - [Fact] - public void JsonDeserialization_ThrowsForPayloadParseError() - { - var json = "{\"RequestId\":\"a\",\"Type\":\"Request\",\"Method\":\"None\",\"Payload\":{\"E\":}}"; - - Assert.Throws<JsonReaderException>(() => JsonSerializationUtilities.Deserialize<Message>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/MonitorNuGetProcessExitRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/MonitorNuGetProcessExitRequestTests.cs deleted file mode 100644 index f371b20324c..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/MonitorNuGetProcessExitRequestTests.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class MonitorNuGetProcessExitRequestTests - { - private static readonly int _processId = 7; - - [Theory] - [InlineData(int.MinValue)] - [InlineData(0)] - [InlineData(int.MaxValue)] - public void Constructor_AcceptsAnyProcessId(int processId) - { - new MonitorNuGetProcessExitRequest(processId); - } - - [Fact] - public void Constructor_InitializesProcessIdProperty() - { - var request = new MonitorNuGetProcessExitRequest(_processId); - - Assert.Equal(_processId, request.ProcessId); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new MonitorNuGetProcessExitRequest(_processId); - - var json = TestUtilities.Serialize(request); - - Assert.Equal($"{{\"ProcessId\":{_processId}}}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = $"{{\"ProcessId\":{_processId}}}"; - var request = JsonSerializationUtilities.Deserialize<MonitorNuGetProcessExitRequest>(json); - - Assert.Equal(_processId, request.ProcessId); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"ProcessId\":null}")] - [InlineData("{\"ProcessId\":\"\"}")] - public void JsonDeserialization_ThrowsForInvalidProcessId(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<MonitorNuGetProcessExitRequest>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/MonitorNuGetProcessExitResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/MonitorNuGetProcessExitResponseTests.cs deleted file mode 100644 index e35a3335c6b..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/MonitorNuGetProcessExitResponseTests.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class MonitorNuGetProcessExitResponseTests - { - [Fact] - public void Constructor_ThrowsForUndefinedResponseCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new MonitorNuGetProcessExitResponse((MessageResponseCode)int.MinValue)); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesResponseCodeProperty() - { - var response = new MonitorNuGetProcessExitResponse(MessageResponseCode.Success); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var response = new MonitorNuGetProcessExitResponse(MessageResponseCode.Success); - - var json = TestUtilities.Serialize(response); - - Assert.Equal("{\"ResponseCode\":\"Success\"}", json); - } - - [Theory] - [InlineData("{\"ResponseCode\":\"Success\"}", MessageResponseCode.Success)] - [InlineData("{\"ResponseCode\":\"NotFound\"}", MessageResponseCode.NotFound)] - [InlineData("{\"ResponseCode\":\"Error\"}", MessageResponseCode.Error)] - public void JsonDeserialization_ReturnsCorrectObject(string json, MessageResponseCode responseCode) - { - var response = JsonSerializationUtilities.Deserialize<MonitorNuGetProcessExitResponse>(json); - - Assert.Equal(responseCode, response.ResponseCode); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"ResponseCode\":null}")] - [InlineData("{\"ResponseCode\":\"\"}")] - [InlineData("{\"ResponseCode\":\"abc\"}")] - public void JsonDeserialization_ThrowsForInvalidResponseCode(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<MonitorNuGetProcessExitResponse>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/PrefetchPackageRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/PrefetchPackageRequestTests.cs deleted file mode 100644 index 8c5413c0796..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/PrefetchPackageRequestTests.cs +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PrefetchPackageRequestTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageSourceRepository(string packageSourceRepository) - { - var exception = Assert.Throws<ArgumentException>( - () => new PrefetchPackageRequest( - packageSourceRepository, - packageId: "a", - packageVersion: "b")); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageId(string packageId) - { - var exception = Assert.Throws<ArgumentException>( - () => new PrefetchPackageRequest( - packageSourceRepository: "a", - packageId: packageId, - packageVersion: "b")); - - Assert.Equal("packageId", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageVersion(string packageVersion) - { - var exception = Assert.Throws<ArgumentException>( - () => new PrefetchPackageRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: packageVersion)); - - Assert.Equal("packageVersion", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var request = new PrefetchPackageRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c"); - - Assert.Equal("a", request.PackageSourceRepository); - Assert.Equal("b", request.PackageId); - Assert.Equal("c", request.PackageVersion); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new PrefetchPackageRequest( - packageSourceRepository: "a", - packageId: "b", - packageVersion: "c"); - - var json = TestUtilities.Serialize(request); - - Assert.Equal("{\"PackageId\":\"b\",\"PackageSourceRepository\":\"a\",\"PackageVersion\":\"c\"}", json); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"PackageId\":\"a\",\"PackageSourceRepository\":\"b\",\"PackageVersion\":\"c\"}"; - var request = JsonSerializationUtilities.Deserialize<PrefetchPackageRequest>(json); - - Assert.Equal("a", request.PackageId); - Assert.Equal("b", request.PackageSourceRepository); - Assert.Equal("c", request.PackageVersion); - } - - [Theory] - [InlineData("{\"PackageId\":\"b\",\"PackageVersion\":\"c\"}", "packageSourceRepository")] - [InlineData("{\"PackageSourceRepository\":null,\"PackageId\":\"b\",\"PackageVersion\":\"c\"}", "packageSourceRepository")] - [InlineData("{\"PackageSourceRepository\":\"\",\"PackageId\":\"b\",\"PackageVersion\":\"c\"}", "packageSourceRepository")] - [InlineData("{\"PackageSourceRepository\":\"a\",\"PackageVersion\":\"c\"}", "packageId")] - [InlineData("{\"PackageSourceRepository\":\"a\",\"PackageId\":null,\"PackageVersion\":\"c\"}", "packageId")] - [InlineData("{\"PackageSourceRepository\":\"a\",\"PackageId\":\"\",\"PackageVersion\":\"c\"}", "packageId")] - [InlineData("{\"PackageSourceRepository\":\"a\",\"PackageId\":\"b\"}", "packageVersion")] - [InlineData("{\"PackageSourceRepository\":\"a\",\"PackageId\":\"b\",\"PackageVersion\":null}", "packageVersion")] - [InlineData("{\"PackageSourceRepository\":\"a\",\"PackageId\":\"b\",\"PackageVersion\":\"\"}", "packageVersion")] - public void JsonDeserialization_ThrowsForInvalidStringArgument(string json, string parameterName) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<PrefetchPackageRequest>(json)); - - Assert.Equal(parameterName, exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/PrefetchPackageResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/PrefetchPackageResponseTests.cs deleted file mode 100644 index ba682411a20..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/PrefetchPackageResponseTests.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PrefetchPackageResponseTests - { - [Fact] - public void Constructor_ThrowsForUndefinedResponseCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new PrefetchPackageResponse((MessageResponseCode)int.MinValue)); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesResponseCodeProperty() - { - var response = new PrefetchPackageResponse(MessageResponseCode.Success); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var response = new PrefetchPackageResponse(MessageResponseCode.Success); - - var json = TestUtilities.Serialize(response); - - Assert.Equal("{\"ResponseCode\":\"Success\"}", json); - } - - [Theory] - [InlineData("{\"ResponseCode\":\"Success\"}", MessageResponseCode.Success)] - [InlineData("{\"ResponseCode\":\"NotFound\"}", MessageResponseCode.NotFound)] - [InlineData("{\"ResponseCode\":\"Error\"}", MessageResponseCode.Error)] - public void JsonDeserialization_ReturnsCorrectObject(string json, MessageResponseCode responseCode) - { - var response = JsonSerializationUtilities.Deserialize<PrefetchPackageResponse>(json); - - Assert.Equal(responseCode, response.ResponseCode); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"ResponseCode\":null}")] - [InlineData("{\"ResponseCode\":\"\"}")] - [InlineData("{\"ResponseCode\":\"abc\"}")] - public void JsonDeserialization_ThrowsForInvalidResponseCode(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<PrefetchPackageResponse>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/ProgressTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/ProgressTests.cs deleted file mode 100644 index 3167ba6968b..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/ProgressTests.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class ProgressTests - { - [Theory] - [InlineData(double.NaN)] - [InlineData(double.NegativeInfinity)] - [InlineData(double.PositiveInfinity)] - [InlineData(double.MinValue)] - [InlineData(double.MaxValue)] - [InlineData(-0.1)] - [InlineData(2D)] - public void Constructor_ThrowsForInvalidPercentage(double percentage) - { - var exception = Assert.Throws<ArgumentException>(() => new Progress(percentage)); - - Assert.Equal("percentage", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData(0D)] - [InlineData(0.5)] - [InlineData(1D)] - public void Constructor_InitializesPercentageProperty(double? percentage) - { - var progress = new Progress(percentage); - - Assert.Equal(percentage, progress.Percentage); - } - - [Theory] - [InlineData(null, "{}")] - [InlineData(0.5, "{\"Percentage\":0.5}")] - public void JsonSerialization_ReturnsCorrectJson(double? percentage, string expectedJson) - { - var progress = new Progress(percentage); - var actualJson = TestUtilities.Serialize(progress); - - Assert.Equal(expectedJson, actualJson); - } - - [Theory] - [InlineData("{}", null)] - [InlineData("{\"Percentage\":0}", 0D)] - [InlineData("{\"Percentage\":0.5}", 0.5)] - [InlineData("{\"Percentage\":1}", 1D)] - public void JsonDeserialization_ReturnsCorrectObject(string json, double? percentage) - { - var progress = JsonSerializationUtilities.Deserialize<Progress>(json); - - Assert.Equal(percentage, progress.Percentage); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetCredentialsRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetCredentialsRequestTests.cs deleted file mode 100644 index add049ce637..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetCredentialsRequestTests.cs +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class SetCredentialsRequestTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageSourceRepository(string packageSourceRepository) - { - var exception = Assert.Throws<ArgumentException>( - () => new SetCredentialsRequest( - packageSourceRepository, - proxyUsername: "a", - proxyPassword: "b", - username: "c", - password: "d")); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("b")] - public void Constructor_InitializesProperties(string argument) - { - var request = new SetCredentialsRequest( - packageSourceRepository: "a", - proxyUsername: argument, - proxyPassword: argument, - username: argument, - password: argument); - - Assert.Equal("a", request.PackageSourceRepository); - Assert.Equal(argument, request.ProxyUsername); - Assert.Equal(argument, request.ProxyPassword); - Assert.Equal(argument, request.Username); - Assert.Equal(argument, request.Password); - } - - [Theory] - [InlineData("a", null, null, null, null, "{\"PackageSourceRepository\":\"a\"}")] - [InlineData("a", "b", "c", "d", "e", "{\"PackageSourceRepository\":\"a\",\"Password\":\"e\",\"ProxyPassword\":\"c\",\"ProxyUsername\":\"b\",\"Username\":\"d\"}")] - public void JsonSerialization_ReturnsCorrectJson( - string packageSourceRepository, - string proxyUsername, - string proxyPassword, - string username, - string password, - string expectedJson) - { - var request = new SetCredentialsRequest( - packageSourceRepository, - proxyUsername, - proxyPassword, - username, - password); - - var actualJson = TestUtilities.Serialize(request); - - Assert.Equal(expectedJson, actualJson); - } - - [Theory] - [InlineData("{\"PackageSourceRepository\":\"a\"}", "a", null, null, null, null)] - [InlineData("{\"PackageSourceRepository\":\"a\",\"Password\":\"b\",\"ProxyPassword\":\"c\",\"ProxyUsername\":\"d\",\"Username\":\"e\"}", "a", "d", "c", "e", "b")] - public void JsonDeserialization_ReturnsCorrectObject( - string json, - string packageSourceRepository, - string proxyUsername, - string proxyPassword, - string username, - string password) - { - var request = JsonSerializationUtilities.Deserialize<SetCredentialsRequest>(json); - - Assert.Equal(packageSourceRepository, request.PackageSourceRepository); - Assert.Equal(proxyUsername, request.ProxyUsername); - Assert.Equal(proxyPassword, request.ProxyPassword); - Assert.Equal(username, request.Username); - Assert.Equal(password, request.Password); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"PackageSourceRepository\":null}")] - [InlineData("{\"PackageSourceRepository\":\"\"}")] - public void JsonDeserialization_ThrowsForInvalidPackageSourceRepository(string json) - { - var exception = Assert.Throws<ArgumentException>( - () => JsonSerializationUtilities.Deserialize<SetCredentialsRequest>(json)); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetCredentialsResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetCredentialsResponseTests.cs deleted file mode 100644 index 038bab46d6a..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetCredentialsResponseTests.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class SetCredentialsResponseTests - { - [Fact] - public void Constructor_ThrowsForUndefinedResponseCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new SetCredentialsResponse((MessageResponseCode)int.MinValue)); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesResponseCodeProperty() - { - var response = new SetCredentialsResponse(MessageResponseCode.Success); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var response = new SetCredentialsResponse(MessageResponseCode.Success); - - var json = TestUtilities.Serialize(response); - - Assert.Equal("{\"ResponseCode\":\"Success\"}", json); - } - - [Theory] - [InlineData("{\"ResponseCode\":\"Success\"}", MessageResponseCode.Success)] - [InlineData("{\"ResponseCode\":\"Error\"}", MessageResponseCode.Error)] - public void JsonDeserialization_ReturnsCorrectObject(string json, MessageResponseCode responseCode) - { - var response = JsonSerializationUtilities.Deserialize<SetCredentialsResponse>(json); - - Assert.Equal(responseCode, response.ResponseCode); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"ResponseCode\":null}")] - [InlineData("{\"ResponseCode\":\"\"}")] - [InlineData("{\"ResponseCode\":\"abc\"}")] - public void JsonDeserialization_ThrowsForInvalidResponseCode(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<SetCredentialsResponse>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetLogLevelRequestTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetLogLevelRequestTests.cs deleted file mode 100644 index c269447a720..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetLogLevelRequestTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using NuGet.Common; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class SetLogLevelRequestTests - { - [Fact] - public void Constructor_ThrowsForUndefinedLogLevel() - { - var exception = Assert.Throws<ArgumentException>( - () => new SetLogLevelRequest((LogLevel)int.MaxValue)); - - Assert.Equal("logLevel", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesLogLevelProperty() - { - var request = new SetLogLevelRequest(LogLevel.Minimal); - - Assert.Equal(LogLevel.Minimal, request.LogLevel); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var request = new SetLogLevelRequest(LogLevel.Debug); - - var actualJson = TestUtilities.Serialize(request); - var expectedJson = "{\"LogLevel\":\"Debug\"}"; - - Assert.Equal(expectedJson, actualJson); - } - - [Fact] - public void JsonDeserialization_ReturnsCorrectObject() - { - var json = "{\"LogLevel\":\"Error\"}"; - - var request = JsonSerializationUtilities.Deserialize<SetLogLevelRequest>(json); - - Assert.NotNull(request); - Assert.Equal(LogLevel.Error, request.LogLevel); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"LogLevel\":null}")] - [InlineData("{\"LogLevel\":\"\"}")] - [InlineData("{\"LogLevel\":\"abc\"}")] - public void JsonDeserialization_ThrowsForInvalidLogLevel(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<SetLogLevelRequest>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetLogLevelResponseTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetLogLevelResponseTests.cs deleted file mode 100644 index c1bff7aa52a..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/Messages/SetLogLevelResponseTests.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class SetLogLevelResponseTests - { - [Fact] - public void Constructor_ThrowsForUndefinedResponseCode() - { - var exception = Assert.Throws<ArgumentException>( - () => new SetLogLevelResponse((MessageResponseCode)int.MinValue)); - - Assert.Equal("responseCode", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesResponseCodeProperty() - { - var response = new SetLogLevelResponse(MessageResponseCode.Success); - - Assert.Equal(MessageResponseCode.Success, response.ResponseCode); - } - - [Fact] - public void JsonSerialization_ReturnsCorrectJson() - { - var response = new SetLogLevelResponse(MessageResponseCode.Success); - - var json = TestUtilities.Serialize(response); - - Assert.Equal("{\"ResponseCode\":\"Success\"}", json); - } - - [Theory] - [InlineData("{\"ResponseCode\":\"Success\"}", MessageResponseCode.Success)] - [InlineData("{\"ResponseCode\":\"Error\"}", MessageResponseCode.Error)] - public void JsonDeserialization_ReturnsCorrectObject(string json, MessageResponseCode responseCode) - { - var response = JsonSerializationUtilities.Deserialize<SetLogLevelResponse>(json); - - Assert.Equal(responseCode, response.ResponseCode); - } - - [Theory] - [InlineData("{}")] - [InlineData("{\"ResponseCode\":null}")] - [InlineData("{\"ResponseCode\":\"\"}")] - [InlineData("{\"ResponseCode\":\"abc\"}")] - public void JsonDeserialization_ThrowsForInvalidResponseCode(string json) - { - Assert.Throws<JsonSerializationException>( - () => JsonSerializationUtilities.Deserialize<SetLogLevelResponse>(json)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/NoOpDisposePluginTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/NoOpDisposePluginTests.cs deleted file mode 100644 index 8ab682292a3..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/NoOpDisposePluginTests.cs +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Moq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class NoOpDisposePluginTests - { - [Fact] - public void Constructor_ThrowsForNullPlugin() - { - var exception = Assert.Throws<ArgumentNullException>(() => new NoOpDisposePlugin(plugin: null)); - - Assert.Equal("plugin", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var connection = Mock.Of<IConnection>(); - var plugin = new Mock<IPlugin>(MockBehavior.Strict); - - plugin.SetupGet(x => x.Connection) - .Returns(connection); - plugin.SetupGet(x => x.FilePath) - .Returns("a"); - plugin.SetupGet(x => x.Id) - .Returns("b"); - plugin.SetupGet(x => x.Name) - .Returns("c"); - - using (var noOpDisposePlugin = new NoOpDisposePlugin(plugin.Object)) - { - Assert.Same(connection, noOpDisposePlugin.Connection); - Assert.Equal("a", noOpDisposePlugin.FilePath); - Assert.Equal("b", noOpDisposePlugin.Id); - Assert.Equal("c", noOpDisposePlugin.Name); - } - - plugin.Verify(x => x.Connection, Times.Once); - plugin.Verify(x => x.FilePath, Times.Once); - plugin.Verify(x => x.Id, Times.Once); - plugin.Verify(x => x.Name, Times.Once); - } - - [Fact] - public void Dispose_DoesNotCallPluginDispose() - { - var plugin = new Mock<IPlugin>(MockBehavior.Strict); - - using (var noOpDisposePlugin = new NoOpDisposePlugin(plugin.Object)) - { - } - - plugin.Verify(); - } - - [Fact] - public void Close_ClosesPlugin() - { - var plugin = new Mock<IPlugin>(MockBehavior.Strict); - - plugin.Setup(x => x.Close()); - - using (var noOpDisposePlugin = new NoOpDisposePlugin(plugin.Object)) - { - noOpDisposePlugin.Close(); - - plugin.Verify(x => x.Close(), Times.Once); - } - } - - [Fact] - public void BeforeClose_Add_SubscribesToBeforeClose() - { - var plugin = new PluginStub(); - - using (var noOpDisposePlugin = new NoOpDisposePlugin(plugin)) - { - noOpDisposePlugin.BeforeClose += OnBeforeClose; - - Assert.Equal(1, plugin.BeforeCloseAddCallCount); - } - } - - [Fact] - public void BeforeClose_Remove_UnsubscribesFromBeforeClose() - { - var plugin = new PluginStub(); - - using (var noOpDisposePlugin = new NoOpDisposePlugin(plugin)) - { - noOpDisposePlugin.BeforeClose -= OnBeforeClose; - - Assert.Equal(1, plugin.BeforeCloseRemoveCallCount); - } - } - - [Fact] - public void Closed_Add_SubscribesToBeforeClose() - { - var plugin = new PluginStub(); - - using (var noOpDisposePlugin = new NoOpDisposePlugin(plugin)) - { - noOpDisposePlugin.Closed += OnClosed; - - Assert.Equal(1, plugin.ClosedAddCallCount); - } - } - - [Fact] - public void Closed_Remove_UnsubscribesFromBeforeClose() - { - var plugin = new PluginStub(); - - using (var noOpDisposePlugin = new NoOpDisposePlugin(plugin)) - { - noOpDisposePlugin.Closed -= OnClosed; - - Assert.Equal(1, plugin.ClosedRemoveCallCount); - } - } - - private void OnBeforeClose(object sender, EventArgs e) - { - } - - private void OnClosed(object sender, EventArgs e) - { - } - - private sealed class PluginStub : IPlugin - { - public IConnection Connection => throw new NotImplementedException(); - public string FilePath => throw new NotImplementedException(); - public string Id => throw new NotImplementedException(); - public string Name => throw new NotImplementedException(); - - internal int BeforeCloseAddCallCount { get; private set; } - internal int BeforeCloseRemoveCallCount { get; private set; } - internal int ClosedAddCallCount { get; private set; } - internal int ClosedRemoveCallCount { get; private set; } - - public event EventHandler BeforeClose - { - add - { - ++BeforeCloseAddCallCount; - } - remove - { - ++BeforeCloseRemoveCallCount; - } - } - - public event EventHandler Closed - { - add - { - ++ClosedAddCallCount; - } - remove - { - ++ClosedRemoveCallCount; - } - } - - public void Close() - { - throw new NotImplementedException(); - } - - public void Dispose() - { - throw new NotImplementedException(); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/OutboundRequestContextTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/OutboundRequestContextTests.cs deleted file mode 100644 index 4d027a0d196..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/OutboundRequestContextTests.cs +++ /dev/null @@ -1,256 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class OutboundRequestContextTests - { - [Fact] - public void Constructor_ThrowsForNullConnection() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new OutboundRequestContext<HandshakeResponse>( - connection: null, - request: new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Handshake, - payload: null), - timeout: TimeSpan.FromMinutes(1), - isKeepAlive: true, - cancellationToken: CancellationToken.None)); - - Assert.Equal("connection", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullRequest() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new OutboundRequestContext<HandshakeResponse>( - Mock.Of<IConnection>(), - request: null, - timeout: TimeSpan.FromMinutes(1), - isKeepAlive: true, - cancellationToken: CancellationToken.None)); - - Assert.Equal("request", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - using (var test = new OutboundRequestContextTest()) - { - Assert.Equal(test.Request.RequestId, test.Context.RequestId); - Assert.NotNull(test.Context.CompletionTask); - Assert.Equal(TaskStatus.WaitingForActivation, test.Context.CompletionTask.Status); - } - } - - [Fact] - public async Task Constructor_ClosesIfTimedOut() - { - using (var test = new OutboundRequestContextTest(TimeSpan.FromMilliseconds(10))) - { - await Assert.ThrowsAsync<TaskCanceledException>( - () => test.Context.CompletionTask); - } - } - - [Fact] - public void Constructor_ClosesIfCancelled() - { - using (var test = new OutboundRequestContextTest()) - { - test.CancellationTokenSource.Cancel(); - - Assert.Equal(TaskStatus.Canceled, test.Context.CompletionTask.Status); - } - } - - [Fact] - public void Dispose_DoesNotDisposeConnection() - { - using (var test = new OutboundRequestContextTest()) - { - test.Context.Dispose(); - test.Connection.Verify(); - } - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var test = new OutboundRequestContextTest()) - { - test.Context.Dispose(); - test.Context.Dispose(); - } - } - - [Fact] - public void HandleCancel_CancelsCompletionTask() - { - using (var test = new OutboundRequestContextTest()) - { - test.Context.HandleCancel(); - - Assert.Equal(TaskStatus.Canceled, test.Context.CompletionTask.Status); - } - } - - [Fact] - public void HandleProgress_ThrowsForNullProgress() - { - using (var test = new OutboundRequestContextTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => test.Context.HandleProgress(progress: null)); - - Assert.Equal("progress", exception.ParamName); - } - } - - [Fact] - public void HandleResponse_ThrowsForNullProgress() - { - using (var test = new OutboundRequestContextTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => test.Context.HandleResponse(response: null)); - - Assert.Equal("response", exception.ParamName); - } - } - - [Fact] - public void HandleResponse_CompletesCompletionTask() - { - using (var test = new OutboundRequestContextTest()) - { - var payload = new HandshakeResponse(MessageResponseCode.Error, protocolVersion: null); - var response = MessageUtilities.Create( - test.Request.RequestId, - MessageType.Response, - test.Request.Method, - payload); - - test.Context.HandleResponse(response); - - Assert.Equal(TaskStatus.RanToCompletion, test.Context.CompletionTask.Status); - Assert.Equal(MessageResponseCode.Error, test.Context.CompletionTask.Result.ResponseCode); - Assert.Null(test.Context.CompletionTask.Result.ProtocolVersion); - } - } - - [Fact] - public void HandleResponse_SecondResponseIsIgnored() - { - using (var test = new OutboundRequestContextTest()) - { - var payload = new HandshakeResponse(MessageResponseCode.Error, protocolVersion: null); - var firstResponse = MessageUtilities.Create( - test.Request.RequestId, - MessageType.Response, - test.Request.Method, - payload); - - test.Context.HandleResponse(firstResponse); - - var response = test.Context.CompletionTask.Result; - - payload = new HandshakeResponse(MessageResponseCode.Success, ProtocolConstants.CurrentVersion); - var secondResponse = MessageUtilities.Create( - test.Request.RequestId, - MessageType.Response, - test.Request.Method, - payload); - - test.Context.HandleResponse(secondResponse); - - Assert.Same(response, test.Context.CompletionTask.Result); - } - } - - [Fact] - public void HandleFault_ThrowsForNullProgress() - { - using (var test = new OutboundRequestContextTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => test.Context.HandleFault(fault: null)); - - Assert.Equal("fault", exception.ParamName); - } - } - - [Fact] - public void HandleFault_ThrowsFault() - { - using (var test = new OutboundRequestContextTest()) - { - var payload = new Fault("test"); - var response = MessageUtilities.Create( - test.Request.RequestId, - MessageType.Fault, - test.Request.Method, - payload); - - var exception = Assert.Throws<ProtocolException>( - () => test.Context.HandleFault(response)); - - Assert.Equal("test", exception.Message); - } - } - - private sealed class OutboundRequestContextTest : IDisposable - { - internal CancellationTokenSource CancellationTokenSource { get; } - internal Mock<IConnection> Connection { get; } - internal OutboundRequestContext<HandshakeResponse> Context { get; } - internal Message Request { get; } - - internal OutboundRequestContextTest(TimeSpan? timeout = null) - { - CancellationTokenSource = new CancellationTokenSource(); - Connection = new Mock<IConnection>(MockBehavior.Strict); - Request = new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Handshake, - payload: null); - Context = new OutboundRequestContext<HandshakeResponse>( - Connection.Object, - Request, - timeout, - isKeepAlive: false, - cancellationToken: CancellationTokenSource.Token); - } - - public void Dispose() - { - try - { - using (CancellationTokenSource) - { - CancellationTokenSource.Cancel(); - } - } - catch (Exception) - { - } - - Context.Dispose(); - - GC.SuppressFinalize(this); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginCreationResultTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginCreationResultTests.cs deleted file mode 100644 index 8da8330cc1f..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginCreationResultTests.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Moq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginCreationResultTests - { - [Fact] - public void Constructor_PluginClaims_ThrowsForNullPlugin() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginCreationResult( - plugin: null, - utilities: Mock.Of<IPluginMulticlientUtilities>(), - claims: new List<OperationClaim>())); - - Assert.Equal("plugin", exception.ParamName); - } - - [Fact] - public void Constructor_PluginClaims_ThrowsForNullPluginMulticlientUtilities() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginCreationResult( - Mock.Of<IPlugin>(), - utilities: null, - claims: new List<OperationClaim>())); - - Assert.Equal("utilities", exception.ParamName); - } - - [Fact] - public void Constructor_PluginClaims_ThrowsForNullClaims() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginCreationResult( - Mock.Of<IPlugin>(), - Mock.Of<IPluginMulticlientUtilities>(), - claims: null)); - - Assert.Equal("claims", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_Message_ThrowsForNullOrEmptyMessage(string message) - { - var exception = Assert.Throws<ArgumentException>( - () => new PluginCreationResult(message)); - - Assert.Equal("message", exception.ParamName); - } - - [Fact] - public void Constructor_PluginClaims_InitializesProperties() - { - var plugin = Mock.Of<IPlugin>(); - var utilities = Mock.Of<IPluginMulticlientUtilities>(); - var claims = new List<OperationClaim>(); - - var result = new PluginCreationResult(plugin, utilities, claims); - - Assert.Same(plugin, result.Plugin); - Assert.Same(utilities, result.PluginMulticlientUtilities); - Assert.Same(claims, result.Claims); - Assert.Null(result.Message); - } - - [Fact] - public void Constructor_Message_InitializesProperties() - { - var result = new PluginCreationResult(message: "a"); - - Assert.Null(result.Plugin); - Assert.Null(result.PluginMulticlientUtilities); - Assert.Null(result.Claims); - Assert.Equal("a", result.Message); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginDiscovererTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginDiscovererTests.cs deleted file mode 100644 index 03947c8e819..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginDiscovererTests.cs +++ /dev/null @@ -1,236 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Test.Utility; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginDiscovererTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData(" ")] - public void Constructor_AcceptsAnyString(string rawPluginPaths) - { - using (new PluginDiscoverer(rawPluginPaths, Mock.Of<EmbeddedSignatureVerifier>())) - { - } - } - - [Fact] - public void DiscoverAsync_ThrowsForNullVerifier() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginDiscoverer(rawPluginPaths: "", verifier: null)); - - Assert.Equal("verifier", exception.ParamName); - } - - [Fact] - public async Task DiscoverAsync_ThrowsIfCancelled() - { - using (var discoverer = new PluginDiscoverer( - rawPluginPaths: "", - verifier: Mock.Of<EmbeddedSignatureVerifier>())) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => discoverer.DiscoverAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task DiscoverAsync_ThrowsPlatformNotSupportedIfEmbeddedSignatureVerifierIsRequired() - { - using (var testDirectory = TestDirectory.Create()) - { - var pluginPath = Path.Combine(testDirectory.Path, "a"); - - File.WriteAllText(pluginPath, string.Empty); - - using (var discoverer = new PluginDiscoverer(pluginPath, new FallbackEmbeddedSignatureVerifier())) - { - await Assert.ThrowsAsync<PlatformNotSupportedException>( - () => discoverer.DiscoverAsync(CancellationToken.None)); - } - } - } - - [Fact] - public async Task DiscoverAsync_DoesNotThrowIfNoValidFilePathsAndFallbackEmbeddedSignatureVerifier() - { - using (var discoverer = new PluginDiscoverer( - rawPluginPaths: "", - verifier: new FallbackEmbeddedSignatureVerifier())) - { - var pluginFiles = await discoverer.DiscoverAsync(CancellationToken.None); - - Assert.Empty(pluginFiles); - } - } - - [Fact] - public async Task DiscoverAsync_PerformsDiscoveryOnlyOnce() - { - using (var testDirectory = TestDirectory.Create()) - { - var pluginPath = Path.Combine(testDirectory.Path, "a"); - - File.WriteAllText(pluginPath, string.Empty); - - var responses = new Dictionary<string, bool>() - { - { pluginPath, true } - }; - var verifierStub = new EmbeddedSignatureVerifierStub(responses); - - using (var discoverer = new PluginDiscoverer(pluginPath, verifierStub)) - { - var results = (await discoverer.DiscoverAsync(CancellationToken.None)).ToArray(); - - Assert.Equal(1, results.Length); - Assert.Equal(1, verifierStub.IsValidCallCount); - - results = (await discoverer.DiscoverAsync(CancellationToken.None)).ToArray(); - - Assert.Equal(1, results.Length); - Assert.Equal(1, verifierStub.IsValidCallCount); - } - } - } - - [Fact] - public async Task DiscoverAsync_HandlesAllPluginFileStates() - { - using (var testDirectory = TestDirectory.Create()) - { - var pluginPaths = new[] { "a", "b", "c", "d" } - .Select(fileName => Path.Combine(testDirectory.Path, fileName)) - .ToArray(); - - File.WriteAllText(pluginPaths[1], string.Empty); - File.WriteAllText(pluginPaths[2], string.Empty); - - var responses = new Dictionary<string, bool>() - { - { pluginPaths[0], false }, - { pluginPaths[1], false }, - { pluginPaths[2], true }, - { pluginPaths[3], false }, - { "e", true } - }; - var verifierStub = new EmbeddedSignatureVerifierStub(responses); - var rawPluginPaths = string.Join(";", responses.Keys); - - using (var discoverer = new PluginDiscoverer(rawPluginPaths, verifierStub)) - { - var results = (await discoverer.DiscoverAsync(CancellationToken.None)).ToArray(); - - Assert.Equal(5, results.Length); - - Assert.Equal(pluginPaths[0], results[0].PluginFile.Path); - Assert.Equal(PluginFileState.NotFound, results[0].PluginFile.State); - Assert.Equal($"A plugin was not found at path '{pluginPaths[0]}'.", results[0].Message); - - Assert.Equal(pluginPaths[1], results[1].PluginFile.Path); - Assert.Equal(PluginFileState.InvalidEmbeddedSignature, results[1].PluginFile.State); - Assert.Equal($"The plugin at '{pluginPaths[1]}' did not have a valid embedded signature.", results[1].Message); - - Assert.Equal(pluginPaths[2], results[2].PluginFile.Path); - Assert.Equal(PluginFileState.Valid, results[2].PluginFile.State); - Assert.Null(results[2].Message); - - Assert.Equal(pluginPaths[3], results[3].PluginFile.Path); - Assert.Equal(PluginFileState.NotFound, results[3].PluginFile.State); - Assert.Equal($"A plugin was not found at path '{pluginPaths[3]}'.", results[3].Message); - - Assert.Equal("e", results[4].PluginFile.Path); - Assert.Equal(PluginFileState.InvalidFilePath, results[4].PluginFile.State); - Assert.Equal($"The plugin file path 'e' is invalid.", results[4].Message); - } - } - } - - [Theory] - [InlineData("a")] - [InlineData(@"\a")] - [InlineData(@".\a")] - [InlineData(@"..\a")] - public async Task DiscoverAsync_DisallowsNonRootedFilePaths(string pluginPath) - { - var responses = new Dictionary<string, bool>() { { pluginPath, true } }; - var verifierStub = new EmbeddedSignatureVerifierStub(responses); - - using (var discoverer = new PluginDiscoverer(pluginPath, verifierStub)) - { - var results = (await discoverer.DiscoverAsync(CancellationToken.None)).ToArray(); - - Assert.Equal(1, results.Length); - Assert.Equal(pluginPath, results[0].PluginFile.Path); - Assert.Equal(PluginFileState.InvalidFilePath, results[0].PluginFile.State); - } - } - - [Fact] - public async Task DiscoverAsync_IsIdempotent() - { - using (var testDirectory = TestDirectory.Create()) - { - var pluginPath = Path.Combine(testDirectory.Path, "a"); - - File.WriteAllText(pluginPath, string.Empty); - - var verifierSpy = new Mock<EmbeddedSignatureVerifier>(); - - verifierSpy.Setup(spy => spy.IsValid(It.IsAny<string>())) - .Returns(true); - - using (var discoverer = new PluginDiscoverer(pluginPath, verifierSpy.Object)) - { - var firstResult = await discoverer.DiscoverAsync(CancellationToken.None); - - verifierSpy.Verify(spy => spy.IsValid(It.IsAny<string>()), - Times.Once); - - var secondResult = await discoverer.DiscoverAsync(CancellationToken.None); - - verifierSpy.Verify(spy => spy.IsValid(It.IsAny<string>()), - Times.Once); - - Assert.Same(firstResult, secondResult); - } - } - } - - private sealed class EmbeddedSignatureVerifierStub : EmbeddedSignatureVerifier - { - private readonly Dictionary<string, bool> _responses; - - internal int IsValidCallCount { get; private set; } - - public EmbeddedSignatureVerifierStub(Dictionary<string, bool> responses) - { - _responses = responses; - } - - public override bool IsValid(string filePath) - { - ++IsValidCallCount; - - bool value; - - Assert.True(_responses.TryGetValue(filePath, out value)); - - return value; - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginDiscoveryResultTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginDiscoveryResultTests.cs deleted file mode 100644 index c5c066e08bc..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginDiscoveryResultTests.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginDiscoveryResultTests - { - [Fact] - public void Constructor_ThrowsForNullPluginFile() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginDiscoveryResult(pluginFile: null, message: "a")); - - Assert.Equal("pluginFile", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var pluginFile = new PluginFile(filePath: "a", state: PluginFileState.InvalidEmbeddedSignature); - - var result = new PluginDiscoveryResult(pluginFile, message: "b"); - - Assert.Same(pluginFile, result.PluginFile); - Assert.Equal("b", result.Message); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginEventArgsTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginEventArgsTests.cs deleted file mode 100644 index e2efab804c8..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginEventArgsTests.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Moq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginEventArgsTests - { - [Fact] - public void Constructor_ThrowsForNullPlugin() - { - var exception = Assert.Throws<ArgumentNullException>(() => new PluginEventArgs(plugin: null)); - - Assert.Equal("plugin", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesPluginProperty() - { - var plugin = Mock.Of<IPlugin>(); - var args = new PluginEventArgs(plugin); - - Assert.Same(plugin, args.Plugin); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFactoryTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFactoryTests.cs deleted file mode 100644 index 78ba2b057d2..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFactoryTests.cs +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginFactoryTests - { - [Fact] - public void Constructor_ThrowsForTimeSpanBelowMinimum() - { - var timeout = TimeSpan.FromMilliseconds(Timeout.InfiniteTimeSpan.TotalMilliseconds - 1); - - var exception = Assert.Throws<ArgumentOutOfRangeException>(() => new PluginFactory(timeout)); - - Assert.Equal("pluginIdleTimeout", exception.ParamName); - Assert.Equal(timeout, exception.ActualValue); - } - - [Fact] - public void Constructor_AcceptsInfiniteTimeSpan() - { - new PluginFactory(Timeout.InfiniteTimeSpan); - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var factory = new PluginFactory(Timeout.InfiniteTimeSpan)) - { - factory.Dispose(); - factory.Dispose(); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetOrCreateAsync_ThrowsForNullOrEmptyFilePath(string filePath) - { - var factory = new PluginFactory(Timeout.InfiniteTimeSpan); - - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => factory.GetOrCreateAsync( - filePath, - PluginConstants.PluginArguments, - new RequestHandlers(), - ConnectionOptions.CreateDefault(), - CancellationToken.None)); - - Assert.Equal("filePath", exception.ParamName); - } - - [Fact] - public async Task GetOrCreateAsync_ThrowsForNullArguments() - { - var factory = new PluginFactory(Timeout.InfiniteTimeSpan); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => factory.GetOrCreateAsync( - filePath: "a", - arguments: null, - requestHandlers: new RequestHandlers(), - options: ConnectionOptions.CreateDefault(), - sessionCancellationToken: CancellationToken.None)); - - Assert.Equal("arguments", exception.ParamName); - } - - [Fact] - public async Task GetOrCreateAsync_ThrowsForNullRequestHandlers() - { - var factory = new PluginFactory(Timeout.InfiniteTimeSpan); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => factory.GetOrCreateAsync( - filePath: "a", - arguments: PluginConstants.PluginArguments, - requestHandlers: null, - options: ConnectionOptions.CreateDefault(), - sessionCancellationToken: CancellationToken.None)); - - Assert.Equal("requestHandlers", exception.ParamName); - } - - [Fact] - public async Task GetOrCreateAsync_ThrowsForNullConnectionOptions() - { - var factory = new PluginFactory(Timeout.InfiniteTimeSpan); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => factory.GetOrCreateAsync( - filePath: "a", - arguments: PluginConstants.PluginArguments, - requestHandlers: new RequestHandlers(), - options: null, - sessionCancellationToken: CancellationToken.None)); - - Assert.Equal("options", exception.ParamName); - } - - [Fact] - public async Task GetOrCreateAsync_ThrowsIfCancelled() - { - var factory = new PluginFactory(Timeout.InfiniteTimeSpan); - - await Assert.ThrowsAsync<OperationCanceledException>( - () => factory.GetOrCreateAsync( - filePath: "a", - arguments: PluginConstants.PluginArguments, - requestHandlers: new RequestHandlers(), - options: ConnectionOptions.CreateDefault(), - sessionCancellationToken: new CancellationToken(canceled: true))); - } - - [Fact] - public async Task GetOrCreateAsync_ThrowsIfDisposed() - { - var factory = new PluginFactory(Timeout.InfiniteTimeSpan); - - factory.Dispose(); - - var exception = await Assert.ThrowsAsync<ObjectDisposedException>( - () => factory.GetOrCreateAsync( - filePath: "a", - arguments: PluginConstants.PluginArguments, - requestHandlers: new RequestHandlers(), - options: ConnectionOptions.CreateDefault(), - sessionCancellationToken: CancellationToken.None)); - - Assert.Equal(nameof(PluginFactory), exception.ObjectName); - } - - [Fact] - public async Task CreateFromCurrentProcessAsync_ThrowsForNullRequestHandlers() - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => PluginFactory.CreateFromCurrentProcessAsync( - requestHandlers: null, - options: ConnectionOptions.CreateDefault(), - sessionCancellationToken: CancellationToken.None)); - - Assert.Equal("requestHandlers", exception.ParamName); - } - - [Fact] - public async Task CreateFromCurrentProcessAsync_ThrowsForNullConnectionOptions() - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => PluginFactory.CreateFromCurrentProcessAsync( - requestHandlers: new RequestHandlers(), - options: null, - sessionCancellationToken: CancellationToken.None)); - - Assert.Equal("options", exception.ParamName); - } - - [Fact] - public async Task CreateFromCurrentProcessAsync_ThrowsIfCancelled() - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => PluginFactory.CreateFromCurrentProcessAsync( - new RequestHandlers(), - ConnectionOptions.CreateDefault(), - sessionCancellationToken: new CancellationToken(canceled: true))); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFileTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFileTests.cs deleted file mode 100644 index ad7a33f9570..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFileTests.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginFileTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyFilePath(string filePath) - { - var exception = Assert.Throws<ArgumentException>(() => new PluginFile(filePath, state: PluginFileState.NotFound)); - - Assert.Equal("filePath", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var pluginFile = new PluginFile(filePath: "a", state: PluginFileState.Valid); - - Assert.Equal("a", pluginFile.Path); - Assert.Equal(PluginFileState.Valid, pluginFile.State); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFindPackageByIdResourceProviderTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFindPackageByIdResourceProviderTests.cs deleted file mode 100644 index 87f3647b183..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFindPackageByIdResourceProviderTests.cs +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using Newtonsoft.Json.Linq; -using NuGet.Configuration; -using NuGet.Protocol.Core.Types; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginFindPackageByIdResourceProviderTests - { - private readonly PluginFindPackageByIdResourceProvider _provider; - - public PluginFindPackageByIdResourceProviderTests() - { - _provider = new PluginFindPackageByIdResourceProvider(); - - HttpHandlerResourceV3.CredentialService = Mock.Of<ICredentialService>(); - } - - [Fact] - public void Before_IsBeforeHttpFileSystemBasedFindPackageByIdResourceProvider() - { - Assert.Equal(new[] { nameof(HttpFileSystemBasedFindPackageByIdResourceProvider) }, _provider.Before); - } - - [Fact] - public void After_IsEmpty() - { - Assert.Empty(_provider.After); - } - - [Fact] - public void Name_IsPluginFindPackageByIdResourceProvider() - { - Assert.Equal(nameof(PluginFindPackageByIdResourceProvider), _provider.Name); - } - - [Fact] - public void ResourceType_IsFindPackageByIdResource() - { - Assert.Equal(typeof(FindPackageByIdResource), _provider.ResourceType); - } - - [Fact] - public async Task TryCreate_ThrowsForNullSource() - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => _provider.TryCreate(source: null, cancellationToken: CancellationToken.None)); - - Assert.Equal("source", exception.ParamName); - } - - [Fact] - public async Task TryCreate_ThrowsIfCancelled() - { - var sourceRepository = CreateSourceRepository( - createPluginResource: true, - createServiceIndexResourceV3: true, - createHttpHandlerResource: true); - - await Assert.ThrowsAsync<OperationCanceledException>( - () => _provider.TryCreate(sourceRepository, new CancellationToken(canceled: true))); - } - - [Fact] - public async Task TryCreate_ReturnsFalseIfNoPluginResource() - { - var sourceRepository = CreateSourceRepository( - createPluginResource: false, - createServiceIndexResourceV3: true, - createHttpHandlerResource: true); - - var result = await _provider.TryCreate(sourceRepository, CancellationToken.None); - - Assert.False(result.Item1); - Assert.Null(result.Item2); - } - - [Fact] - public async Task TryCreate_ReturnsFalseIfNoServiceIndexResourceV3() - { - var sourceRepository = CreateSourceRepository( - createPluginResource: true, - createServiceIndexResourceV3: false, - createHttpHandlerResource: true); - - var result = await _provider.TryCreate(sourceRepository, CancellationToken.None); - - Assert.False(result.Item1); - Assert.Null(result.Item2); - } - - [Fact] - public async Task TryCreate_ReturnsFalseIfNoHttpHandlerResource() - { - var sourceRepository = CreateSourceRepository( - createPluginResource: true, - createServiceIndexResourceV3: true, - createHttpHandlerResource: false); - - var result = await _provider.TryCreate(sourceRepository, CancellationToken.None); - - Assert.False(result.Item1); - Assert.Null(result.Item2); - } - - [Fact] - public async Task TryCreate_ReturnsPluginFindPackageByIdResource() - { - var sourceRepository = CreateSourceRepository( - createPluginResource: true, - createServiceIndexResourceV3: true, - createHttpHandlerResource: true); - - var result = await _provider.TryCreate(sourceRepository, CancellationToken.None); - - Assert.True(result.Item1); - Assert.IsType<PluginFindPackageByIdResource>(result.Item2); - } - - private static SourceRepository CreateSourceRepository( - bool createPluginResource, - bool createServiceIndexResourceV3, - bool createHttpHandlerResource) - { - var packageSource = new PackageSource(source: "https://unit.test"); - var providers = new INuGetResourceProvider[] - { - CreatePluginResourceProvider(createPluginResource), - CreateServiceIndexResourceV3Provider(createServiceIndexResourceV3), - CreateMockHttpHandlerResource(createHttpHandlerResource) - }; - - return new SourceRepository(packageSource, providers); - } - - private static HttpHandlerResourceV3Provider CreateMockHttpHandlerResource(bool createResource) - { - var provider = new Mock<HttpHandlerResourceV3Provider>(); - - provider.Setup(x => x.Name) - .Returns(nameof(HttpHandlerResourceV3Provider)); - provider.Setup(x => x.ResourceType) - .Returns(typeof(HttpHandlerResource)); - - HttpHandlerResource resource = null; - - if (createResource) - { - resource = Mock.Of<HttpHandlerResource>(); - } - - var tryCreateResult = new Tuple<bool, INuGetResource>(resource != null, resource); - - provider.Setup(x => x.TryCreate(It.IsAny<SourceRepository>(), It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(tryCreateResult)); - - return provider.Object; - } - - private static PluginResourceProvider CreatePluginResourceProvider(bool createResource) - { - var provider = new Mock<PluginResourceProvider>(); - - provider.Setup(x => x.Name) - .Returns(nameof(PluginResourceProvider)); - provider.Setup(x => x.ResourceType) - .Returns(typeof(PluginResource)); - - PluginResource pluginResource = null; - - if (createResource) - { - var plugin = new Mock<IPlugin>(); - var utilities = new Mock<IPluginMulticlientUtilities>(); - var connection = new Mock<IConnection>(); - var dispatcher = new Mock<IMessageDispatcher>(); - - dispatcher.SetupGet(x => x.RequestHandlers) - .Returns(new RequestHandlers()); - - connection.SetupGet(x => x.MessageDispatcher) - .Returns(dispatcher.Object); - - plugin.Setup(x => x.Connection) - .Returns(connection.Object); - - var creationResult = new PluginCreationResult( - plugin.Object, - utilities.Object, - new List<OperationClaim>() { OperationClaim.DownloadPackage }); - var packageSource = new PackageSource(source: "https://unit.test"); - - pluginResource = new PluginResource( - new[] { creationResult }, - packageSource, - Mock.Of<ICredentialService>()); - } - - var tryCreateResult = new Tuple<bool, INuGetResource>(pluginResource != null, pluginResource); - - provider.Setup(x => x.TryCreate(It.IsAny<SourceRepository>(), It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(tryCreateResult)); - - return provider.Object; - } - - private static ServiceIndexResourceV3Provider CreateServiceIndexResourceV3Provider(bool createResource) - { - var provider = new Mock<ServiceIndexResourceV3Provider>(); - - provider.Setup(x => x.Name) - .Returns(nameof(ServiceIndexResourceV3Provider)); - provider.Setup(x => x.ResourceType) - .Returns(typeof(ServiceIndexResourceV3)); - - var serviceIndexResource = createResource - ? new ServiceIndexResourceV3(JObject.Parse("{}"), DateTime.UtcNow) : null; - var tryCreateResult = new Tuple<bool, INuGetResource>(serviceIndexResource != null, serviceIndexResource); - - provider.Setup(x => x.TryCreate(It.IsAny<SourceRepository>(), It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(tryCreateResult)); - - return provider.Object; - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFindPackageByIdResourceTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFindPackageByIdResourceTests.cs deleted file mode 100644 index 55d4d4e61c3..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginFindPackageByIdResourceTests.cs +++ /dev/null @@ -1,546 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; -using NuGet.Test.Utility; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginFindPackageByIdResourceTests - { - private readonly Mock<ICredentialService> _credentialService; - private readonly PackageSource _packageSource; - private readonly Mock<IPlugin> _plugin; - private readonly Mock<IWebProxy> _proxy; - private readonly Mock<IPluginMulticlientUtilities> _utilities; - - public PluginFindPackageByIdResourceTests() - { - _packageSource = new PackageSource("https://unit.test"); - _proxy = new Mock<IWebProxy>(); - _credentialService = new Mock<ICredentialService>(); - _plugin = new Mock<IPlugin>(); - _utilities = new Mock<IPluginMulticlientUtilities>(); - - HttpHandlerResourceV3.CredentialService = Mock.Of<ICredentialService>(); - } - - [Fact] - public void Constructor_ThrowsForNullPlugin() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginFindPackageByIdResource( - plugin: null, - utilities: _utilities.Object, - packageSource: _packageSource)); - - Assert.Equal("plugin", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullPluginMulticlientUtilities() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginFindPackageByIdResource( - _plugin.Object, - utilities: null, - packageSource: _packageSource)); - - Assert.Equal("utilities", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullPackageSource() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginFindPackageByIdResource( - _plugin.Object, - _utilities.Object, - packageSource: null)); - - Assert.Equal("packageSource", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetAllVersionsAsync_ThrowsForNullOrEmptyId(string id) - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.GetAllVersionsAsync( - id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowsForNullSourceCacheContext() - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowsForNullLogger() - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowIfCancelled() - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowsForError() - { - using (var test = PluginFindPackageByIdResourceTest.Create(MessageResponseCode.Error)) - { - await Assert.ThrowsAsync<FatalProtocolException>( - () => test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ReturnsEmptyEnumerableIfPackageIdNotFound() - { - using (var test = PluginFindPackageByIdResourceTest.Create(MessageResponseCode.NotFound)) - { - var versions = await test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Empty(versions); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ReturnsAllVersions() - { - using (var test = PluginFindPackageByIdResourceTest.Create(MessageResponseCode.Success)) - { - var versions = await test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Equal(new[] - { - NuGetVersion.Parse("1.0.0"), - NuGetVersion.Parse("2.0.0"), - NuGetVersion.Parse("3.0.0"), - }, versions); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetDependencyInfoAsync_ThrowsForNullOrEmptyId(string id) - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.GetDependencyInfoAsync( - id, - NuGetVersion.Parse("1.0.0"), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullVersion() - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id, - version: null, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("version", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullSourceCacheContext() - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullLogger() - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowIfCancelled() - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ReturnsNullIfPackageNotFound() - { - using (var test = PluginFindPackageByIdResourceTest.Create(MessageResponseCode.NotFound)) - { - var dependencyInfo = await test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Null(dependencyInfo); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_GetsOriginalIdentity() - { - using (var test = PluginFindPackageByIdResourceTest.Create(MessageResponseCode.Success)) - { - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<PrefetchPackageRequest, PrefetchPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.PrefetchPackage), - It.IsNotNull<PrefetchPackageRequest>(), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new PrefetchPackageResponse(MessageResponseCode.Success)); - - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<GetFilesInPackageRequest, GetFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.GetFilesInPackage), - It.IsNotNull<GetFilesInPackageRequest>(), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new GetFilesInPackageResponse(MessageResponseCode.Success, new[] { $"{test.PackageIdentity.Id}.nuspec" })); - - string tempNuspecFilePath = null; - - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyFilesInPackageRequest, CopyFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyFilesInPackage), - It.IsNotNull<CopyFilesInPackageRequest>(), - It.IsAny<CancellationToken>())) - .Callback<MessageMethod, CopyFilesInPackageRequest, CancellationToken>( - (method, request, cancellationToken) => - { - tempNuspecFilePath = Path.Combine( - request.DestinationFolderPath, - $"{test.PackageIdentity.Id}.nuspec"); - - File.WriteAllText( - tempNuspecFilePath, - $@"<?xml version=""1.0"" encoding=""utf-8""?> - <package> - <metadata> - <id>{test.PackageIdentity.Id}</id> - <version>{test.PackageIdentity.Version.ToNormalizedString()}</version> - <title /> - <frameworkAssemblies> - <frameworkAssembly assemblyName=""System.Runtime"" /> - </frameworkAssemblies> - </metadata> - </package>"); - - }) - .ReturnsAsync(() => new CopyFilesInPackageResponse(MessageResponseCode.Success, new[] { tempNuspecFilePath })); - - var dependencyInfo = await test.Resource.GetDependencyInfoAsync( - test.PackageIdentity.Id.ToUpper(), - test.PackageIdentity.Version, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.NotNull(dependencyInfo); - Assert.Equal(test.PackageIdentity, dependencyInfo.PackageIdentity); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_Throws() - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<NotSupportedException>( - () => test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - Stream.Null, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullPackageIdentity() - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - packageIdentity: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullSourceCacheContext() - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullLogger() - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsIfCancelled() - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsNullIfPackageNotFound() - { - using (var test = PluginFindPackageByIdResourceTest.Create(MessageResponseCode.NotFound)) - { - var downloader = await test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "b", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.IsType<PluginPackageDownloader>(downloader); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsPackageDownloaderIfPackageFound() - { - using (var test = PluginFindPackageByIdResourceTest.Create()) - { - var downloader = await test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.IsType<PluginPackageDownloader>(downloader); - } - } - - private sealed class PluginFindPackageByIdResourceTest : IDisposable - { - internal Mock<IConnection> Connection { get; } - internal FileInfo Package { get; } - internal PackageIdentity PackageIdentity { get; } - internal PluginFindPackageByIdResource Resource { get; } - internal SourceCacheContext SourceCacheContext { get; } - internal TestDirectory TestDirectory { get; } - - private PluginFindPackageByIdResourceTest( - PluginFindPackageByIdResource resource, - FileInfo package, - PackageIdentity packageIdentity, - Mock<IConnection> connection, - SourceCacheContext sourceCacheContext, - TestDirectory testDirectory) - { - Resource = resource; - Package = package; - PackageIdentity = packageIdentity; - Connection = connection; - SourceCacheContext = sourceCacheContext; - TestDirectory = testDirectory; - } - - public void Dispose() - { - SourceCacheContext.Dispose(); - TestDirectory.Dispose(); - - GC.SuppressFinalize(this); - } - - internal static PluginFindPackageByIdResourceTest Create( - MessageResponseCode responseCode = MessageResponseCode.Error) - { - var packageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); - var testDirectory = TestDirectory.Create(); - var packageSource = new PackageSource("http://unit.test"); - var package = SimpleTestPackageUtility.CreateFullPackage( - testDirectory.Path, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); - var packageBytes = File.ReadAllBytes(package.FullName); - var plugin = new Mock<IPlugin>(); - var dispatcher = new Mock<IMessageDispatcher>(); - var connection = new Mock<IConnection>(); - - dispatcher.SetupGet(x => x.RequestHandlers) - .Returns(new RequestHandlers()); - - connection.SetupGet(x => x.MessageDispatcher) - .Returns(dispatcher.Object); - - var versions = responseCode == MessageResponseCode.Success ? new[] { "1.0.0", "2.0.0", "3.0.0" } : null; - var response = new GetPackageVersionsResponse(responseCode, versions); - - connection.Setup(x => x.SendRequestAndReceiveResponseAsync<GetPackageVersionsRequest, GetPackageVersionsResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.GetPackageVersions), - It.Is<GetPackageVersionsRequest>( - c => string.Equals(c.PackageId, packageIdentity.Id, StringComparison.OrdinalIgnoreCase) && - c.PackageSourceRepository == packageSource.Source), - It.IsAny<CancellationToken>())) - .ReturnsAsync(response); - - plugin.SetupGet(x => x.Connection) - .Returns(connection.Object); - - var utilities = new Mock<IPluginMulticlientUtilities>(); - var credentialService = new Mock<ICredentialService>(); - var credentialsProvider = new GetCredentialsRequestHandler( - plugin.Object, - proxy: null, - credentialService: credentialService.Object); - - var resource = new PluginFindPackageByIdResource( - plugin.Object, - utilities.Object, - packageSource); - - return new PluginFindPackageByIdResourceTest( - resource, - package, - packageIdentity, - connection, - new SourceCacheContext(), - testDirectory); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginMulticlientUtilitiesTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginMulticlientUtilitiesTests.cs deleted file mode 100644 index 694534cf06f..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginMulticlientUtilitiesTests.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginMulticlientUtilitiesTests - { - private readonly PluginMulticlientUtilities _utilities; - - public PluginMulticlientUtilitiesTests() - { - _utilities = new PluginMulticlientUtilities(); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task DoOncePerPluginLifetimeAsync_ThrowsForNullOrEmptyKey(string key) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => _utilities.DoOncePerPluginLifetimeAsync( - key, - () => Task.FromResult(0), - CancellationToken.None)); - - Assert.Equal("key", exception.ParamName); - } - - [Fact] - public async Task DoOncePerPluginLifetimeAsync_ThrowsForNullTaskFunc() - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => _utilities.DoOncePerPluginLifetimeAsync( - key: "a", - taskFunc: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("taskFunc", exception.ParamName); - } - - [Fact] - public async Task DoOncePerPluginLifetimeAsync_ThrowsIfCancelled() - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => _utilities.DoOncePerPluginLifetimeAsync( - key: "a", - taskFunc: () => Task.FromResult(0), - cancellationToken: new CancellationToken(canceled: true))); - } - - [Fact] - public async Task DoOncePerPluginLifetimeAsync_ExecutesTaskOnlyOncePerKey() - { - var wasExecuted = false; - - await _utilities.DoOncePerPluginLifetimeAsync( - key: "a", - taskFunc: () => - { - wasExecuted = true; - return Task.FromResult(0); - }, - cancellationToken: CancellationToken.None); - - Assert.True(wasExecuted); - - wasExecuted = false; - - await _utilities.DoOncePerPluginLifetimeAsync( - key: "a", - taskFunc: () => - { - wasExecuted = true; - return Task.FromResult(0); - }, - cancellationToken: CancellationToken.None); - - Assert.False(wasExecuted); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginPackageDownloaderTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginPackageDownloaderTests.cs deleted file mode 100644 index 65a5f0bcfe6..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginPackageDownloaderTests.cs +++ /dev/null @@ -1,442 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Packaging.Core; -using NuGet.Test.Utility; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginPackageDownloaderTests - { - private static readonly PackageIdentity _packageIdentity; - private static readonly string _packageSourceRepository; - - static PluginPackageDownloaderTests() - { - _packageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); - _packageSourceRepository = "https://unit.test"; - } - - [Fact] - public void Constructor_ThrowsForNullPlugin() - { - using (var packageReader = new PluginPackageReader( - Mock.Of<IPlugin>(), - _packageIdentity, - _packageSourceRepository)) - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginPackageDownloader( - plugin: null, - packageIdentity: _packageIdentity, - packageReader: packageReader, - packageSourceRepository: _packageSourceRepository)); - - Assert.Equal("plugin", exception.ParamName); - } - } - - [Fact] - public void Constructor_ThrowsForNullPackageIdentity() - { - using (var packageReader = new PluginPackageReader( - Mock.Of<IPlugin>(), - _packageIdentity, - _packageSourceRepository)) - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginPackageDownloader( - Mock.Of<IPlugin>(), - packageIdentity: null, - packageReader: packageReader, - packageSourceRepository: _packageSourceRepository)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public void Constructor_ThrowsForNullPackageReader() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginPackageDownloader( - Mock.Of<IPlugin>(), - _packageIdentity, - packageReader: null, - packageSourceRepository: _packageSourceRepository)); - - Assert.Equal("packageReader", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageSourceRepository(string packageSourceRepository) - { - using (var packageReader = new PluginPackageReader( - Mock.Of<IPlugin>(), - _packageIdentity, - _packageSourceRepository)) - { - var exception = Assert.Throws<ArgumentException>( - () => new PluginPackageDownloader( - Mock.Of<IPlugin>(), - _packageIdentity, - packageReader, - packageSourceRepository)); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - } - - [Fact] - public void Constructor_InitializesProperties() - { - using (var test = PluginPackageDownloaderTest.Create()) - { - Assert.Same(test.PackageReader, test.Downloader.ContentReader); - Assert.Same(test.PackageReader, test.Downloader.CoreReader); - } - } - - [Fact] - public void Dispose_DisposesDisposables() - { - using (var test = PluginPackageDownloaderTest.Create()) - { - test.Downloader.Dispose(); - - // PluginPackageDownloader.Dispose() calls both IPlugin.Dispose() and - // PluginPackageReader.Dispose(). The latter call IPlugin.Dispose() - // on its own IPlugin instance. - test.Plugin.Verify(x => x.Dispose(), Times.Exactly(2)); - } - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var test = PluginPackageDownloaderTest.Create()) - { - test.Downloader.Dispose(); - test.Downloader.Dispose(); - - test.Plugin.Verify(x => x.Dispose(), Times.Exactly(2)); - } - } - - [Fact] - public void ContentReader_ThrowsIfDisposed() - { - using (var test = PluginPackageDownloaderTest.Create()) - { - test.Downloader.Dispose(); - - var exception = Assert.Throws<ObjectDisposedException>(() => test.Downloader.ContentReader); - - Assert.Equal(nameof(PluginPackageDownloader), exception.ObjectName); - } - } - - [Fact] - public void CoreReader_ThrowsIfDisposed() - { - using (var test = PluginPackageDownloaderTest.Create()) - { - test.Downloader.Dispose(); - - var exception = Assert.Throws<ObjectDisposedException>(() => test.Downloader.CoreReader); - - Assert.Equal(nameof(PluginPackageDownloader), exception.ObjectName); - } - } - - [Fact] - public async Task CopyNupkgFileToAsync_ThrowsIfDisposed() - { - using (var test = PluginPackageDownloaderTest.Create()) - { - test.Downloader.Dispose(); - - var exception = await Assert.ThrowsAsync<ObjectDisposedException>( - () => test.Downloader.CopyNupkgFileToAsync( - destinationFilePath: "a", - cancellationToken: CancellationToken.None)); - - Assert.Equal(nameof(PluginPackageDownloader), exception.ObjectName); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task CopyNupkgFileToAsync_ThrowsForNullOrEmptyDestinationFilePath(string destinationFilePath) - { - using (var test = PluginPackageDownloaderTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Downloader.CopyNupkgFileToAsync(destinationFilePath, CancellationToken.None)); - - Assert.Equal("destinationFilePath", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgFileToAsync_ThrowsIfCancelled() - { - using (var test = PluginPackageDownloaderTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Downloader.CopyNupkgFileToAsync( - destinationFilePath: "a", - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task CopyNupkgFileToAsync_ReturnsFalseIfNupkgFileNotCopied() - { - var destinationFilePath = "a"; - var connection = new Mock<IConnection>(MockBehavior.Strict); - - connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyNupkgFileRequest, CopyNupkgFileResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyNupkgFile), - It.Is<CopyNupkgFileRequest>(c => c.PackageId == _packageIdentity.Id && - c.PackageVersion == _packageIdentity.Version.ToNormalizedString() && - c.PackageSourceRepository == _packageSourceRepository && - c.DestinationFilePath == destinationFilePath), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new CopyNupkgFileResponse(MessageResponseCode.Error)); - - using (var test = PluginPackageDownloaderTest.Create()) - { - test.Plugin.SetupGet(x => x.Connection) - .Returns(connection.Object); - - var wasCopied = await test.Downloader.CopyNupkgFileToAsync( - destinationFilePath, - CancellationToken.None); - - Assert.False(wasCopied); - } - } - - [Fact] - public async Task CopyNupkgFileToAsync_ReturnsTrueIfNupkgFileCopied() - { - var destinationFilePath = "a"; - var connection = new Mock<IConnection>(MockBehavior.Strict); - - connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyNupkgFileRequest, CopyNupkgFileResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyNupkgFile), - It.Is<CopyNupkgFileRequest>(c => c.PackageId == _packageIdentity.Id && - c.PackageVersion == _packageIdentity.Version.ToNormalizedString() && - c.PackageSourceRepository == _packageSourceRepository && - c.DestinationFilePath == destinationFilePath), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new CopyNupkgFileResponse(MessageResponseCode.Success)); - - using (var test = PluginPackageDownloaderTest.Create()) - { - test.Plugin.SetupGet(x => x.Connection) - .Returns(connection.Object); - - var wasCopied = await test.Downloader.CopyNupkgFileToAsync( - destinationFilePath, - CancellationToken.None); - - Assert.True(wasCopied); - } - } - - [Fact] - public async Task CopyNupkgFileToAsync_ReturnsFalseIfPackageDownloadMarkerFileCreated() - { - using (var testDirectory = TestDirectory.Create()) - { - var destinationFilePath = Path.Combine(testDirectory.Path, _packageIdentity.Id); - var connection = new Mock<IConnection>(MockBehavior.Strict); - - connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyNupkgFileRequest, CopyNupkgFileResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyNupkgFile), - It.Is<CopyNupkgFileRequest>(c => c.PackageId == _packageIdentity.Id && - c.PackageVersion == _packageIdentity.Version.ToNormalizedString() && - c.PackageSourceRepository == _packageSourceRepository && - c.DestinationFilePath == destinationFilePath), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new CopyNupkgFileResponse(MessageResponseCode.NotFound)); - - using (var test = PluginPackageDownloaderTest.Create()) - { - test.Plugin.SetupGet(x => x.Connection) - .Returns(connection.Object); - - var wasCopied = await test.Downloader.CopyNupkgFileToAsync( - destinationFilePath, - CancellationToken.None); - - var markerFilePath = Path.Combine(testDirectory.Path, $"{_packageIdentity.Id}.packagedownload.marker"); - - Assert.False(wasCopied); - Assert.True(File.Exists(markerFilePath)); - } - } - } - - [Fact] - public async Task GetPackageHashAsync_ThrowsIfDisposed() - { - using (var test = PluginPackageDownloaderTest.Create()) - { - test.Downloader.Dispose(); - - var exception = await Assert.ThrowsAsync<ObjectDisposedException>( - () => test.Downloader.GetPackageHashAsync( - hashAlgorithm: "a", - cancellationToken: CancellationToken.None)); - - Assert.Equal(nameof(PluginPackageDownloader), exception.ObjectName); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetPackageHashAsync_ThrowsForNullOrEmptyDestinationFilePath(string hashAlgorithm) - { - using (var test = PluginPackageDownloaderTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Downloader.GetPackageHashAsync(hashAlgorithm, CancellationToken.None)); - - Assert.Equal("hashAlgorithm", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageHashAsync_ThrowsIfCancelled() - { - using (var test = PluginPackageDownloaderTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Downloader.GetPackageHashAsync( - hashAlgorithm: "SHA512", - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Theory] - [InlineData(MessageResponseCode.Error)] - [InlineData(MessageResponseCode.NotFound)] - public async Task GetPackageHashAsync_ReturnsNullForNonSuccess(MessageResponseCode responseCode) - { - var hashAlgorithm = "a"; - var response = new GetPackageHashResponse(responseCode, hash: null); - var connection = new Mock<IConnection>(MockBehavior.Strict); - - connection.Setup(x => x.SendRequestAndReceiveResponseAsync<GetPackageHashRequest, GetPackageHashResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.GetPackageHash), - It.Is<GetPackageHashRequest>(c => c.PackageId == _packageIdentity.Id && - c.PackageVersion == _packageIdentity.Version.ToNormalizedString() && - c.PackageSourceRepository == _packageSourceRepository && - c.HashAlgorithm == hashAlgorithm), - It.IsAny<CancellationToken>())) - .ReturnsAsync(response); - - using (var test = PluginPackageDownloaderTest.Create()) - { - test.Plugin.SetupGet(x => x.Connection) - .Returns(connection.Object); - - var packageHash = await test.Downloader.GetPackageHashAsync( - hashAlgorithm, - CancellationToken.None); - - Assert.Null(packageHash); - } - } - - [Fact] - public async Task GetPackageHashAsync_ReturnsPackageHashForSuccess() - { - var hashAlgorithm = "a"; - var response = new GetPackageHashResponse(MessageResponseCode.Success, hash: "b"); - var connection = new Mock<IConnection>(MockBehavior.Strict); - - connection.Setup(x => x.SendRequestAndReceiveResponseAsync<GetPackageHashRequest, GetPackageHashResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.GetPackageHash), - It.Is<GetPackageHashRequest>(c => c.PackageId == _packageIdentity.Id && - c.PackageVersion == _packageIdentity.Version.ToNormalizedString() && - c.PackageSourceRepository == _packageSourceRepository && - c.HashAlgorithm == hashAlgorithm), - It.IsAny<CancellationToken>())) - .ReturnsAsync(response); - - using (var test = PluginPackageDownloaderTest.Create()) - { - test.Plugin.SetupGet(x => x.Connection) - .Returns(connection.Object); - - var packageHash = await test.Downloader.GetPackageHashAsync( - hashAlgorithm, - CancellationToken.None); - - Assert.Equal(response.Hash, packageHash); - } - } - - private sealed class PluginPackageDownloaderTest : IDisposable - { - internal PluginPackageDownloader Downloader { get; } - internal PackageIdentity PackageIdentity { get; } - internal PluginPackageReader PackageReader { get; } - internal Mock<IPlugin> Plugin { get; } - - private PluginPackageDownloaderTest( - PackageIdentity packageIdentity, - Mock<IPlugin> plugin, - PluginPackageReader packageReader, - PluginPackageDownloader downloader) - { - PackageIdentity = packageIdentity; - Plugin = plugin; - PackageReader = packageReader; - Downloader = downloader; - } - - public void Dispose() - { - Downloader.Dispose(); - - GC.SuppressFinalize(this); - } - - internal static PluginPackageDownloaderTest Create() - { - var plugin = new Mock<IPlugin>(MockBehavior.Strict); - - plugin.Setup(x => x.Dispose()); - - var packageReader = new PluginPackageReader(plugin.Object, _packageIdentity, _packageSourceRepository); - var downloader = new PluginPackageDownloader( - plugin.Object, - _packageIdentity, - packageReader, - _packageSourceRepository); - - return new PluginPackageDownloaderTest( - _packageIdentity, - plugin, - packageReader, - downloader); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginPackageReaderTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginPackageReaderTests.cs deleted file mode 100644 index 334e0b2fdf2..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginPackageReaderTests.cs +++ /dev/null @@ -1,1430 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using System.Xml.Linq; -using Moq; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Test.Utility; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginPackageReaderTests - { - [Fact] - public void Constructor_ThrowsForNullPlugin() - { - using (var test = new PluginPackageReaderTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginPackageReader( - plugin: null, - packageIdentity: test.PackageIdentity, - packageSourceRepository: "b")); - - Assert.Equal("plugin", exception.ParamName); - } - } - - [Fact] - public void Constructor_ThrowsForNullPackageIdentity() - { - using (var test = new PluginPackageReaderTest()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginPackageReader( - test.Plugin.Object, - packageIdentity: null, - packageSourceRepository: "b")); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyPackageSourceRepository(string packageSourceRepository) - { - using (var test = new PluginPackageReaderTest()) - { - var exception = Assert.Throws<ArgumentException>( - () => new PluginPackageReader( - test.Plugin.Object, - test.PackageIdentity, - packageSourceRepository)); - - Assert.Equal("packageSourceRepository", exception.ParamName); - } - } - - [Fact] - public void GetStream_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetStream(path: "a")); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetStreamAsync_ThrowsForNullOrEmptyPath(string path) - { - using (var test = new PluginPackageReaderTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Reader.GetStreamAsync(path, CancellationToken.None)); - - Assert.Equal("path", exception.ParamName); - } - } - - [Fact] - public async Task GetStreamAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetStreamAsync( - path: "a", - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetStreamAsync_ReturnsNullOnNotFound() - { - const string fileInPackage = "a"; - - using (var test = new PluginPackageReaderTest()) - { - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyFilesInPackageRequest, CopyFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyFilesInPackage), - It.Is<CopyFilesInPackageRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString() - && c.FilesInPackage.Single() == fileInPackage), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new CopyFilesInPackageResponse(MessageResponseCode.NotFound, copiedFiles: null)); - - var stream = await test.Reader.GetStreamAsync(fileInPackage, CancellationToken.None); - - Assert.Null(stream); - } - } - - [Fact] - public async Task GetStreamAsync_ThrowsOnError() - { - const string fileInPackage = "a"; - - using (var test = new PluginPackageReaderTest()) - { - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyFilesInPackageRequest, CopyFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyFilesInPackage), - It.Is<CopyFilesInPackageRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString() - && c.FilesInPackage.Single() == fileInPackage), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new CopyFilesInPackageResponse(MessageResponseCode.Error, copiedFiles: null)); - - var exception = await Assert.ThrowsAsync<PluginException>( - () => test.Reader.GetStreamAsync(fileInPackage, CancellationToken.None)); - - Assert.Equal($"Plugin '{test.PluginName}' failed a CopyFilesInPackage operation for package {test.PackageIdentity.Id}.{test.PackageIdentity.Version.ToNormalizedString()}.", exception.Message); - } - } - - [Fact] - public async Task GetStreamAsync_ReturnsStreamOnSuccess() - { - const string fileInPackage = "a"; - const string fileContent = "b"; - - using (var test = new PluginPackageReaderTest()) - { - CopyFilesInPackageResponse response = null; - - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyFilesInPackageRequest, CopyFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyFilesInPackage), - It.Is<CopyFilesInPackageRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString() - && c.FilesInPackage.Single() == fileInPackage), - It.IsAny<CancellationToken>())) - .Callback<MessageMethod, CopyFilesInPackageRequest, CancellationToken>( - (method, request, cancellationToken) => - { - var filePath = Path.Combine(request.DestinationFolderPath, request.FilesInPackage.Single()); - - File.WriteAllText(filePath, fileContent); - - response = new CopyFilesInPackageResponse(MessageResponseCode.Success, new[] { filePath }); - } - ) - .ReturnsAsync(() => response); - - using (var stream = await test.Reader.GetStreamAsync(fileInPackage, CancellationToken.None)) - using (var reader = new StreamReader(stream)) - { - var streamContent = reader.ReadToEnd(); - - Assert.Equal(fileContent, streamContent); - } - } - } - - [Fact] - public void GetFiles_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetFiles()); - } - } - - [Fact] - public async Task GetFilesAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetFilesAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetFilesAsync_ReturnsEmptyEnumerableOnNotFound() - { - using (var test = new PluginPackageReaderTest()) - { - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<GetFilesInPackageRequest, GetFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.GetFilesInPackage), - It.Is<GetFilesInPackageRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString()), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new GetFilesInPackageResponse(MessageResponseCode.NotFound, files: null)); - - var files = await test.Reader.GetFilesAsync(CancellationToken.None); - - Assert.Empty(files); - } - } - - [Fact] - public async Task GetFilesAsync_ThrowsOnError() - { - using (var test = new PluginPackageReaderTest()) - { - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<GetFilesInPackageRequest, GetFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.GetFilesInPackage), - It.Is<GetFilesInPackageRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString()), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new GetFilesInPackageResponse(MessageResponseCode.Error, files: null)); - - var exception = await Assert.ThrowsAsync<PluginException>( - () => test.Reader.GetFilesAsync(CancellationToken.None)); - - Assert.Equal($"Plugin '{test.PluginName}' failed a GetFilesInPackage operation for package {test.PackageIdentity.Id}.{test.PackageIdentity.Version.ToNormalizedString()}.", exception.Message); - } - } - - [Fact] - public async Task GetFilesAsync_ReturnsFilesOnSuccess() - { - var expectedFiles = new[] { "a", "b", "c" }; - - using (var test = new PluginPackageReaderTest()) - { - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<GetFilesInPackageRequest, GetFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.GetFilesInPackage), - It.Is<GetFilesInPackageRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString()), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new GetFilesInPackageResponse(MessageResponseCode.Success, expectedFiles)); - - var actualFiles = await test.Reader.GetFilesAsync(CancellationToken.None); - - Assert.Equal(expectedFiles, actualFiles); - } - } - - [Fact] - public async Task GetFilesAsync_IsIdempotent() - { - var expectedFiles = new[] { "a", "b", "c" }; - - using (var test = new PluginPackageReaderTest()) - { - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<GetFilesInPackageRequest, GetFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.GetFilesInPackage), - It.Is<GetFilesInPackageRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString()), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new GetFilesInPackageResponse(MessageResponseCode.Success, expectedFiles)); - - var actualFiles = await test.Reader.GetFilesAsync(CancellationToken.None); - actualFiles = await test.Reader.GetFilesAsync(CancellationToken.None); - - test.Connection.Verify(x => x.SendRequestAndReceiveResponseAsync<GetFilesInPackageRequest, GetFilesInPackageResponse>( - It.IsAny<MessageMethod>(), - It.IsAny<GetFilesInPackageRequest>(), - It.IsAny<CancellationToken>()), Times.Once); - } - } - - [Fact] - public void GetFiles_String_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetFiles(folder: "a")); - } - } - - [Fact] - public async Task GetFilesAsync_String_ThrowsForNullFolder() - { - using (var test = new PluginPackageReaderTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Reader.GetFilesAsync(folder: null, cancellationToken: CancellationToken.None)); - - Assert.Equal("folder", exception.ParamName); - } - } - - [Fact] - public async Task GetFilesAsync_String_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetFilesAsync( - folder: "a", - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetFilesAsync_String_ReturnsFilesInFolder() - { - var filesInPackage = new[] { "a", "b/c", "b/d", "e" }; - var expectedFiles = new[] { "b/c", "b/d" }; - - using (var test = new PluginPackageReaderTest()) - { - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<GetFilesInPackageRequest, GetFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.GetFilesInPackage), - It.Is<GetFilesInPackageRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString()), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new GetFilesInPackageResponse(MessageResponseCode.Success, filesInPackage)); - - var actualFiles = await test.Reader.GetFilesAsync( - folder: "b", - cancellationToken: CancellationToken.None); - - Assert.Equal(expectedFiles, actualFiles); - } - } - - [Fact] - public void CopyFiles_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>( - () => test.Reader.CopyFiles( - destination: "a", - packageFiles: Enumerable.Empty<string>(), - extractFile: ExtractPackageFile, - logger: NullLogger.Instance, - token: CancellationToken.None)); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task CopyFilesAsync_ThrowsForNullOrEmptyDestination(string destination) - { - using (var test = new PluginPackageReaderTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Reader.CopyFilesAsync( - destination, - Enumerable.Empty<string>(), - ExtractPackageFile, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("destination", exception.ParamName); - } - } - - [Fact] - public async Task CopyFilesAsync_ThrowsForNullPackageFiles() - { - using (var test = new PluginPackageReaderTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Reader.CopyFilesAsync( - destination: "a", - packageFiles: null, - extractFile: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("packageFiles", exception.ParamName); - } - } - - [Fact] - public async Task CopyFilesAsync_ThrowsForNullLogger() - { - using (var test = new PluginPackageReaderTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Reader.CopyFilesAsync( - destination: "a", - packageFiles: Enumerable.Empty<string>(), - extractFile: null, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task CopyFilesAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.CopyFilesAsync( - destination: "a", - packageFiles: Enumerable.Empty<string>(), - extractFile: null, - logger: NullLogger.Instance, - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task CopyFilesAsync_ReturnsEmptyEnumerableOnNotFound() - { - const string fileInPackage = "a"; - - using (var test = new PluginPackageReaderTest()) - { - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyFilesInPackageRequest, CopyFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyFilesInPackage), - It.Is<CopyFilesInPackageRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString() - && c.FilesInPackage.Single() == fileInPackage), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new CopyFilesInPackageResponse(MessageResponseCode.NotFound, copiedFiles: null)); - - var copiedFiles = await test.Reader.CopyFilesAsync( - destination: "a", - packageFiles: new[] { fileInPackage }, - extractFile: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.Empty(copiedFiles); - } - } - - [Fact] - public async Task CopyFilesAsync_ThrowsOnError() - { - const string fileInPackage = "a"; - - using (var test = new PluginPackageReaderTest()) - { - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyFilesInPackageRequest, CopyFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyFilesInPackage), - It.Is<CopyFilesInPackageRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString() - && c.FilesInPackage.Single() == fileInPackage), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new CopyFilesInPackageResponse(MessageResponseCode.Error, copiedFiles: null)); - - var exception = await Assert.ThrowsAsync<PluginException>( - () => test.Reader.CopyFilesAsync( - destination: "a", - packageFiles: new[] { fileInPackage }, - extractFile: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal($"Plugin '{test.PluginName}' failed a CopyFilesInPackage operation for package {test.PackageIdentity.Id}.{test.PackageIdentity.Version.ToNormalizedString()}.", exception.Message); - } - } - - [Fact] - public async Task CopyFilesAsync_ReturnsFilesOnSuccess() - { - var expectedFiles = new[] { "a", "b", "c" }; - - using (var testDirectory = TestDirectory.Create()) - using (var test = new PluginPackageReaderTest()) - { - CopyFilesInPackageResponse response = null; - - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyFilesInPackageRequest, CopyFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyFilesInPackage), - It.Is<CopyFilesInPackageRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString() - && c.FilesInPackage.Count() == expectedFiles.Length), - It.IsAny<CancellationToken>())) - .Callback<MessageMethod, CopyFilesInPackageRequest, CancellationToken>( - (method, request, cancellationToken) => - { - var copiedFiles = new List<string>(); - - foreach (var fileInPackage in request.FilesInPackage) - { - var filePath = Path.Combine(request.DestinationFolderPath, fileInPackage); - - File.WriteAllText(filePath, fileInPackage); - - copiedFiles.Add(filePath); - } - - response = new CopyFilesInPackageResponse(MessageResponseCode.Success, copiedFiles); - } - ) - .ReturnsAsync(() => response); - - var actualCopiedFilePaths = await test.Reader.CopyFilesAsync( - testDirectory.Path, - expectedFiles, - extractFile: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - var expectedCopiedFilePaths = expectedFiles.Select(f => Path.Combine(testDirectory.Path, f)); - - Assert.Equal(expectedCopiedFilePaths, actualCopiedFilePaths); - } - } - - [Fact] - public void GetIdentity_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetIdentity()); - } - } - - [Fact] - public async Task GetIdentityAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetIdentityAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetIdentityAsync_ReturnsIdentity() - { - using (var test = new NuspecPluginPackageReaderTest()) - { - var packageIdentity = await test.Reader.GetIdentityAsync(CancellationToken.None); - - Assert.Equal(test.PackageIdentity, packageIdentity); - } - } - - [Fact] - public void GetMinClientVersion_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetMinClientVersion()); - } - } - - [Fact] - public async Task GetMinClientVersionAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetMinClientVersionAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetMinClientVersionAsync_ReturnsMinClientVersion() - { - using (var test = new NuspecPluginPackageReaderTest()) - { - var minClientVersion = await test.Reader.GetMinClientVersionAsync(CancellationToken.None); - - Assert.Equal(NuGetVersion.Parse("1.2.3"), minClientVersion); - } - } - - [Fact] - public void GetPackageTypes_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetPackageTypes()); - } - } - - [Fact] - public async Task GetPackageTypesAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetPackageTypesAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetPackageTypesAsync_ReturnsPackageTypes() - { - using (var test = new NuspecPluginPackageReaderTest()) - { - var packageTypes = await test.Reader.GetPackageTypesAsync(CancellationToken.None); - - Assert.NotNull(packageTypes); - Assert.Equal(1, packageTypes.Count); - Assert.Equal("f", packageTypes[0].Name); - Assert.Equal("4.5.6", packageTypes[0].Version.ToString()); - } - } - - [Fact] - public void GetNuspec_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetNuspec()); - } - } - - [Fact] - public async Task GetNuspecAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetNuspecAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetNuspecAsync_ReturnsNuspec() - { - using (var test = new NuspecPluginPackageReaderTest()) - using (var stream = await test.Reader.GetNuspecAsync(CancellationToken.None)) - using (var streamReader = new StreamReader(stream)) - { - var content = streamReader.ReadToEnd(); - - var expectedResult = XDocument.Parse(test.NuspecFileInPackage.Content).ToString(); - var actualResult = XDocument.Parse(content).ToString(); - - Assert.Equal(expectedResult, actualResult); - } - } - - [Fact] - public void GetNuspecFile_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetNuspecFile()); - } - } - - [Fact] - public async Task GetNuspecFileAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetNuspecFileAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetNuspecFileAsync_ReturnsNuspecPathInPackage() - { - using (var test = new NuspecPluginPackageReaderTest()) - { - var nuspecPathInPackage = await test.Reader.GetNuspecFileAsync(CancellationToken.None); - - Assert.Equal(test.NuspecFileInPackage.Path, nuspecPathInPackage); - } - } - - [Fact] - public void NuspecReader_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.NuspecReader); - } - } - - [Fact] - public async Task GetNuspecReaderAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetNuspecReaderAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetNuspecReaderAsync_ReturnsNuspecPathInPackage() - { - using (var test = new NuspecPluginPackageReaderTest()) - { - var reader = await test.Reader.GetNuspecReaderAsync(CancellationToken.None); - - Assert.NotNull(reader); - } - } - - [Fact] - public void GetSupportedFrameworks_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetSupportedFrameworks()); - } - } - - [Fact] - public async Task GetSupportedFrameworksAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetSupportedFrameworksAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetSupportedFrameworksAsync_ReturnsSupportedFrameworks() - { - using (var test = new NuspecPluginPackageReaderTest(addFiles: true)) - { - var frameworks = await test.Reader.GetSupportedFrameworksAsync(CancellationToken.None); - - Assert.NotEmpty(frameworks); - Assert.Equal(new[] - { - ".NETFramework,Version=v4.0", - ".NETFramework,Version=v4.5", - "Silverlight,Version=v3.0", - }, frameworks.Select(f => f.DotNetFrameworkName)); - } - } - - [Fact] - public void GetFrameworkItems_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetFrameworkItems()); - } - } - - [Fact] - public async Task GetFrameworkItemsAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetSupportedFrameworksAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetFrameworkItemsAsync_ReturnsFrameworkItems() - { - using (var test = new NuspecPluginPackageReaderTest()) - { - var groups = await test.Reader.GetFrameworkItemsAsync(CancellationToken.None); - - Assert.NotEmpty(groups); - Assert.Equal(new[] - { - ".NETFramework,Version=v4.0", - "Silverlight,Version=v3.0" - }, groups.Select(g => g.TargetFramework.DotNetFrameworkName)); - } - } - - [Fact] - public void IsServiceable_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.IsServiceable()); - } - } - - [Fact] - public async Task IsServiceableAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.IsServiceableAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task IsServiceableAsync_ReturnsIsServiceable() - { - using (var test = new NuspecPluginPackageReaderTest()) - { - var isServiceable = await test.Reader.IsServiceableAsync(CancellationToken.None); - - Assert.True(isServiceable); - } - } - - [Fact] - public void GetBuildItems_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetBuildItems()); - } - } - - [Fact] - public async Task GetBuildItemsAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetBuildItemsAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetBuildItemsAsync_ReturnsBuildItems() - { - using (var test = new NuspecPluginPackageReaderTest(addFiles: true)) - { - var groups = await test.Reader.GetBuildItemsAsync(CancellationToken.None); - - Assert.NotEmpty(groups); - Assert.Equal(new[] - { - ".NETFramework,Version=v4.5" - }, groups.Select(g => g.TargetFramework.DotNetFrameworkName)); - Assert.Equal(new[] - { - "build/net45/a.props", - "build/net45/a.targets" - }, groups.Single().Items); - } - } - - [Fact] - public void GetToolItems_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetToolItems()); - } - } - - [Fact] - public async Task GetToolItemsAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetToolItemsAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetToolItemsAsync_ReturnsToolItems() - { - using (var test = new NuspecPluginPackageReaderTest(addFiles: true)) - { - var groups = await test.Reader.GetToolItemsAsync(CancellationToken.None); - - Assert.NotEmpty(groups); - Assert.Equal(new[] - { - ".NETFramework,Version=v4.5" - }, groups.Select(g => g.TargetFramework.DotNetFrameworkName)); - Assert.Equal(new[] - { - "tools/net45/j", - "tools/net45/k" - }, groups.Single().Items); - } - } - - [Fact] - public void GetContentItems_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetContentItems()); - } - } - - [Fact] - public async Task GetContentItemsAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetContentItemsAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetContentItemsAsync_ReturnsContentItems() - { - using (var test = new NuspecPluginPackageReaderTest(addFiles: true)) - { - var groups = await test.Reader.GetContentItemsAsync(CancellationToken.None); - - Assert.NotEmpty(groups); - Assert.Equal(new[] - { - ".NETFramework,Version=v4.5" - }, groups.Select(g => g.TargetFramework.DotNetFrameworkName)); - Assert.Equal(new[] - { - "content/net45/b", - "content/net45/c" - }, groups.Single().Items); - } - } - - [Fact] - public void GetItems_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetItems(folderName: "a")); - } - } - - [Fact] - public async Task GetItemsAsync_ThrowsForNullFolderName() - { - using (var test = new PluginPackageReaderTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Reader.GetItemsAsync( - folderName: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("folderName", exception.ParamName); - } - } - - [Fact] - public async Task GetItemsAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetItemsAsync( - folderName: "a", - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetItemsAsync_ReturnsItems() - { - using (var test = new NuspecPluginPackageReaderTest(addFiles: true)) - { - var groups = await test.Reader.GetItemsAsync( - folderName: "lib", - cancellationToken: CancellationToken.None); - - Assert.NotEmpty(groups); - Assert.Equal(new[] - { - ".NETFramework,Version=v4.5" - }, groups.Select(g => g.TargetFramework.DotNetFrameworkName)); - Assert.Equal(new[] - { - "lib/net45/d", - "lib/net45/e", - "lib/net45/f.dll", - "lib/net45/g.dll" - }, groups.Single().Items); - } - } - - [Fact] - public void GetPackageDependencies_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetPackageDependencies()); - } - } - - [Fact] - public async Task GetPackageDependenciesAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetPackageDependenciesAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetPackageDependenciesAsync_ReturnsPackageDependencies() - { - using (var test = new NuspecPluginPackageReaderTest(addFiles: true)) - { - var groups = await test.Reader.GetPackageDependenciesAsync(CancellationToken.None); - - Assert.NotEmpty(groups); - Assert.Equal(new[] - { - ".NETFramework,Version=v4.0", - ".NETFramework,Version=v4.5" - }, groups.Select(g => g.TargetFramework.DotNetFrameworkName)); - Assert.Equal(new[] { "b","c" }, groups.First().Packages.Select(p => p.Id)); - } - } - - [Fact] - public void GetLibItems_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetLibItems()); - } - } - - [Fact] - public async Task GetLibItemsAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetLibItemsAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetLibItemsAsync_ReturnsLibItems() - { - using (var test = new NuspecPluginPackageReaderTest(addFiles: true)) - { - var groups = await test.Reader.GetLibItemsAsync(CancellationToken.None); - - Assert.NotEmpty(groups); - Assert.Equal( - new[] { ".NETFramework,Version=v4.5" }, - groups.Select(g => g.TargetFramework.DotNetFrameworkName)); - Assert.Equal(new[] - { - "lib/net45/d", - "lib/net45/e", - "lib/net45/f.dll", - "lib/net45/g.dll" - }, groups.First().Items); - } - } - - [Fact] - public void GetReferenceItems_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetReferenceItems()); - } - } - - [Fact] - public async Task GetReferenceItemsAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetReferenceItemsAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetReferenceItemsAsync_ReturnsReferenceItems() - { - using (var test = new NuspecPluginPackageReaderTest(addFiles: true)) - { - var groups = await test.Reader.GetReferenceItemsAsync(CancellationToken.None); - - Assert.NotEmpty(groups); - Assert.Equal( - new[] { ".NETFramework,Version=v4.5" }, - groups.Select(g => g.TargetFramework.DotNetFrameworkName)); - Assert.Equal(new[] - { - "lib/net45/g.dll" - }, groups.First().Items); - } - } - - [Fact] - public void GetDevelopmentDependency_Throws() - { - using (var test = new PluginPackageReaderTest()) - { - Assert.Throws<NotSupportedException>(() => test.Reader.GetDevelopmentDependency()); - } - } - - [Fact] - public async Task GetDevelopmentDependencyAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.GetDevelopmentDependencyAsync(new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetDevelopmentDependencyAsync_ReturnsDevelopmentDependency() - { - using (var test = new NuspecPluginPackageReaderTest()) - { - var isDevelopmentDependency = await test.Reader.GetDevelopmentDependencyAsync(CancellationToken.None); - - Assert.True(isDevelopmentDependency); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task CopyNupkgAsync_ThrowsForNullOrEmptyNupkgFilePath(string nupkgFilePath) - { - using (var test = new PluginPackageReaderTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Reader.CopyNupkgAsync(nupkgFilePath, CancellationToken.None)); - - Assert.Equal("nupkgFilePath", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgAsync_ThrowsIfCancelled() - { - using (var test = new PluginPackageReaderTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Reader.CopyNupkgAsync( - nupkgFilePath: "a", - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task CopyNupkgAsync_ReturnsNullAndCreatesPackageDownloadMarkerFileOnNotFound() - { - using (var testDirectory = TestDirectory.Create()) - using (var test = new PluginPackageReaderTest()) - { - var pathResolver = new VersionFolderPathResolver(testDirectory.Path); - var nupkgFilePath = Path.Combine( - testDirectory.Path, - $"{test.PackageIdentity.Id}.${test.PackageIdentity.Version.ToNormalizedString()}.nupkg"); - var markerFilePath = Path.Combine( - testDirectory.Path, - pathResolver.GetPackageDownloadMarkerFileName(test.PackageIdentity.Id)); - - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyNupkgFileRequest, CopyNupkgFileResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyNupkgFile), - It.Is<CopyNupkgFileRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString()), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new CopyNupkgFileResponse(MessageResponseCode.NotFound)); - - var actualFilePath = await test.Reader.CopyNupkgAsync(nupkgFilePath, CancellationToken.None); - - Assert.Null(actualFilePath); - Assert.False(File.Exists(nupkgFilePath)); - Assert.True(File.Exists(markerFilePath)); - } - } - - [Fact] - public async Task CopyNupkgAsync_ReturnsNullOnError() - { - using (var testDirectory = TestDirectory.Create()) - using (var test = new PluginPackageReaderTest()) - { - var pathResolver = new VersionFolderPathResolver(testDirectory.Path); - var nupkgFilePath = Path.Combine( - testDirectory.Path, - $"{test.PackageIdentity.Id}.${test.PackageIdentity.Version.ToNormalizedString()}.nupkg"); - var markerFilePath = Path.Combine( - testDirectory.Path, - pathResolver.GetPackageDownloadMarkerFileName(test.PackageIdentity.Id)); - - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyNupkgFileRequest, CopyNupkgFileResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyNupkgFile), - It.Is<CopyNupkgFileRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString()), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new CopyNupkgFileResponse(MessageResponseCode.Error)); - - var actualFilePath = await test.Reader.CopyNupkgAsync(nupkgFilePath, CancellationToken.None); - - Assert.Null(actualFilePath); - Assert.False(File.Exists(nupkgFilePath)); - Assert.False(File.Exists(markerFilePath)); - } - } - - [Fact] - public async Task CopyNupkgAsync_CopiesNupkgOnSuccess() - { - using (var testDirectory = TestDirectory.Create()) - using (var test = new PluginPackageReaderTest()) - { - var pathResolver = new VersionFolderPathResolver(testDirectory.Path); - var nupkgFilePath = Path.Combine( - testDirectory.Path, - $"{test.PackageIdentity.Id}.${test.PackageIdentity.Version.ToNormalizedString()}.nupkg"); - var markerFilePath = Path.Combine( - testDirectory.Path, - pathResolver.GetPackageDownloadMarkerFileName(test.PackageIdentity.Id)); - - test.Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyNupkgFileRequest, CopyNupkgFileResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyNupkgFile), - It.Is<CopyNupkgFileRequest>(c => c.PackageSourceRepository == test.PackageSource.Source - && c.PackageId == test.PackageIdentity.Id - && c.PackageVersion == test.PackageIdentity.Version.ToNormalizedString()), - It.IsAny<CancellationToken>())) - .Callback<MessageMethod, CopyNupkgFileRequest, CancellationToken>( - (method, request, cancellationToken) => - { - File.WriteAllText(request.DestinationFilePath, string.Empty); - }) - .ReturnsAsync(new CopyNupkgFileResponse(MessageResponseCode.Success)); - - var actualFilePath = await test.Reader.CopyNupkgAsync(nupkgFilePath, CancellationToken.None); - - Assert.Equal(nupkgFilePath, actualFilePath); - Assert.True(File.Exists(actualFilePath)); - Assert.False(File.Exists(markerFilePath)); - } - } - - private string ExtractPackageFile(string sourceFile, string targetPath, Stream fileStream) - { - throw new NotImplementedException(); - } - - private class PluginPackageReaderTest : IDisposable - { - internal Mock<IConnection> Connection { get; } - internal PackageIdentity PackageIdentity { get; } - internal PackageSource PackageSource { get; } - internal Mock<IPlugin> Plugin { get; } - internal string PluginName { get; } - internal PluginPackageReader Reader { get; } - - internal PluginPackageReaderTest() - { - Connection = new Mock<IConnection>(MockBehavior.Strict); - - PackageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); - PackageSource = new PackageSource("https://unit.test"); - PluginName = "b"; - Plugin = new Mock<IPlugin>(MockBehavior.Strict); - - Plugin.Setup(x => x.Dispose()); - Plugin.SetupGet(x => x.Name) - .Returns(PluginName); - Plugin.SetupGet(x => x.Connection) - .Returns(Connection.Object); - - Reader = new PluginPackageReader(Plugin.Object, PackageIdentity, PackageSource.Source); - } - - public void Dispose() - { - Dispose(disposing: true); - GC.SuppressFinalize(this); - - Connection.Verify(); - Plugin.Verify(); - } - - protected virtual void Dispose(bool disposing) - { - Reader.Dispose(); - } - } - - private sealed class NuspecPluginPackageReaderTest : PluginPackageReaderTest - { - private static readonly IEnumerable<FileInPackage> _additionalFilesInPackage; - - internal FileInPackage NuspecFileInPackage { get; } - - static NuspecPluginPackageReaderTest() - { - _additionalFilesInPackage = new FileInPackage[] - { - new FileInPackage(path: "build/net45/a.dll", content: string.Empty), - new FileInPackage(path: "build/net45/a.props", content: string.Empty), - new FileInPackage(path: "build/net45/a.targets", content: string.Empty), - new FileInPackage(path: "content/net45/b", content: string.Empty), - new FileInPackage(path: "content/net45/c", content: string.Empty), - new FileInPackage(path: "lib/net45/d", content: string.Empty), - new FileInPackage(path: "lib/net45/e", content: string.Empty), - new FileInPackage(path: "lib/net45/f.dll", content: string.Empty), - new FileInPackage(path: "lib/net45/g.dll", content: string.Empty), - new FileInPackage(path: "other/net45/h", content: string.Empty), - new FileInPackage(path: "other/net45/i", content: string.Empty), - new FileInPackage(path: "tools/net45/j", content: string.Empty), - new FileInPackage(path: "tools/net45/k", content: string.Empty) - }; - } - - internal NuspecPluginPackageReaderTest(bool addFiles = false) - : base() - { - var additionalFilesInPackage = addFiles ? _additionalFilesInPackage : Enumerable.Empty<FileInPackage>(); - - NuspecFileInPackage = new FileInPackage( - path: $"{PackageIdentity.Id}.nuspec", - content: $@"<?xml version=""1.0"" encoding=""utf-8""?> - <package> - <metadata minClientVersion=""1.2.3""> - <id>{PackageIdentity.Id}</id> - <version>{PackageIdentity.Version.ToNormalizedString()}</version> - <title /> - <dependencies> - <group targetFramework=""net40""> - <dependency id=""b"" /> - <dependency id=""c"" /> - </group> - <group targetFramework=""net45"" /> - </dependencies> - <developmentDependency>true</developmentDependency> - <frameworkAssemblies> - <frameworkAssembly assemblyName=""d"" targetFramework=""net40"" /> - <frameworkAssembly assemblyName=""e"" targetFramework=""sl3"" /> - </frameworkAssemblies> - <packageTypes> - <packageType name=""f"" version=""4.5.6"" /> - </packageTypes> - <references> - <group targetFramework=""net45""> - <reference file=""g.dll"" /> - <reference file=""h.dll"" /> - </group> - </references> - <serviceable>true</serviceable> - </metadata> - </package>"); - var filesInPackage = new[] { NuspecFileInPackage }.Concat(additionalFilesInPackage); - - Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<GetFilesInPackageRequest, GetFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.GetFilesInPackage), - It.Is<GetFilesInPackageRequest>(c => c.PackageSourceRepository == PackageSource.Source - && c.PackageId == PackageIdentity.Id - && c.PackageVersion == PackageIdentity.Version.ToNormalizedString()), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new GetFilesInPackageResponse(MessageResponseCode.Success, filesInPackage.Select(f => f.Path))); - - CopyFilesInPackageResponse response = null; - - Connection.Setup(x => x.SendRequestAndReceiveResponseAsync<CopyFilesInPackageRequest, CopyFilesInPackageResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.CopyFilesInPackage), - It.Is<CopyFilesInPackageRequest>(c => c.PackageSourceRepository == PackageSource.Source - && c.PackageId == PackageIdentity.Id - && c.PackageVersion == PackageIdentity.Version.ToNormalizedString() - && c.FilesInPackage.Count() == 1), - It.IsAny<CancellationToken>())) - .Callback<MessageMethod, CopyFilesInPackageRequest, CancellationToken>( - (method, request, cancellationToken) => - { - var copiedFiles = new List<string>(); - - foreach (var fileInPackage in request.FilesInPackage) - { - var filePath = Path.Combine(request.DestinationFolderPath, fileInPackage); - var content = filesInPackage.Single(f => f.Path == fileInPackage).Content; - - File.WriteAllText(filePath, content); - - copiedFiles.Add(filePath); - } - - response = new CopyFilesInPackageResponse(MessageResponseCode.Success, copiedFiles); - } - ) - .ReturnsAsync(() => response); - } - } - - private sealed class FileInPackage - { - internal string Content { get; } - internal string Path { get; } - - internal FileInPackage(string path, string content) - { - Path = path; - Content = content; - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginProcessTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginProcessTests.cs deleted file mode 100644 index 7d826237b30..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginProcessTests.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginProcessTests - { - [Fact] - public void Constructor_ThrowsForNullProcess() - { - Assert.Throws<ArgumentNullException>(() => new PluginProcess(process: null)); - } - - // Cannot test other members since System.Diagnostics.Process is not mockable. - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginResourceProviderTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginResourceProviderTests.cs deleted file mode 100644 index 03803f0f11f..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginResourceProviderTests.cs +++ /dev/null @@ -1,482 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using Newtonsoft.Json.Linq; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Protocol.Core.Types; -using NuGet.Test.Utility; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginResourceProviderTests - { - private const string _pluginPathsEnvironmentVariable = "NUGET_PLUGIN_PATHS"; - private const string _pluginRequestTimeoutEnvironmentVariable = "NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS"; - private const string _sourceUri = "https://unit.test"; - - [Fact] - public void Before_IsEmpty() - { - var provider = new PluginResourceProvider(); - - Assert.Empty(provider.Before); - } - - [Fact] - public void After_IsEmpty() - { - var provider = new PluginResourceProvider(); - - Assert.Empty(provider.After); - } - - [Fact] - public void Name_IsPluginResourceProvider() - { - var provider = new PluginResourceProvider(); - - Assert.Equal(nameof(PluginResourceProvider), provider.Name); - } - - [Fact] - public void ResourceType_IsPluginResource() - { - var provider = new PluginResourceProvider(); - - Assert.Equal(typeof(PluginResource), provider.ResourceType); - } - - [Fact] - public async Task TryCreate_ThrowsForNullSource() - { - var provider = new PluginResourceProvider(); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => provider.TryCreate(source: null, cancellationToken: CancellationToken.None)); - - Assert.Equal("source", exception.ParamName); - } - - [Fact] - public async Task TryCreate_ThrowsIfCancelled() - { - var sourceRepository = CreateSourceRepository(serviceIndexResource: null, sourceUri: _sourceUri); - var provider = new PluginResourceProvider(); - - await Assert.ThrowsAsync<OperationCanceledException>( - () => provider.TryCreate(sourceRepository, new CancellationToken(canceled: true))); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task TryCreate_ReturnsFalseForNullOrEmptyEnvironmentVariable(string pluginsPath) - { - var test = new PluginResourceProviderNegativeTest( - serviceIndexJson: "{}", - sourceUri: _sourceUri, - pluginsPath: pluginsPath); - - var result = await test.Provider.TryCreate(test.SourceRepository, CancellationToken.None); - - Assert.False(result.Item1); - Assert.Null(result.Item2); - } - - [Fact] - public async Task TryCreate_ReturnsFalseIfNoServiceIndexResourceV3() - { - var test = new PluginResourceProviderNegativeTest( - serviceIndexJson: null, - sourceUri: _sourceUri); - - var result = await test.Provider.TryCreate(test.SourceRepository, CancellationToken.None); - - Assert.False(result.Item1); - Assert.Null(result.Item2); - } - - [Theory] - [InlineData("\\unit\test")] - [InlineData("file:///C:/unit/test")] - public async Task TryCreate_ReturnsFalseIfPackageSourceIsNotHttpOrHttps(string sourceUri) - { - var test = new PluginResourceProviderNegativeTest( - serviceIndexJson: "{}", - sourceUri: sourceUri); - - var result = await test.Provider.TryCreate(test.SourceRepository, CancellationToken.None); - - Assert.False(result.Item1); - Assert.Null(result.Item2); - } - - [PlatformFact(Platform.Windows)] - public async Task TryCreate_ReturnsPluginResource() - { - var expectations = new[] - { - new PositiveTestExpectation("{}", "https://unit.test", new [] { OperationClaim.DownloadPackage }) - }; - - using (var test = new PluginResourceProviderPositiveTest( - pluginFilePath: "a", - pluginFileState: PluginFileState.Valid, - expectations: expectations)) - { - var result = await test.Provider.TryCreate(expectations[0].SourceRepository, CancellationToken.None); - - Assert.True(result.Item1); - Assert.IsType<PluginResource>(result.Item2); - - var pluginResource = (PluginResource)result.Item2; - var pluginResult = await pluginResource.GetPluginAsync( - OperationClaim.DownloadPackage, - CancellationToken.None); - - Assert.NotNull(pluginResult); - Assert.NotNull(pluginResult.Plugin); - Assert.NotNull(pluginResult.PluginMulticlientUtilities); - } - } - - [PlatformFact(Platform.Windows)] - public async Task TryCreate_QueriesPluginForEachPackageSourceRepository() - { - var expectations = new[] - { - new PositiveTestExpectation("{\"serviceIndex\":1}", "https://1.unit.test", new [] { OperationClaim.DownloadPackage }), - new PositiveTestExpectation("{\"serviceIndex\":2}", "https://2.unit.test", Enumerable.Empty<OperationClaim>()), - new PositiveTestExpectation("{\"serviceIndex\":3}", "https://3.unit.test", new [] { OperationClaim.DownloadPackage }) - }; - - using (var test = new PluginResourceProviderPositiveTest( - pluginFilePath: "a", - pluginFileState: PluginFileState.Valid, - expectations: expectations)) - { - IPlugin firstPluginResult = null; - IPlugin thirdPluginResult = null; - - for (var i = 0; i < expectations.Length; ++i) - { - var expectation = expectations[i]; - var result = await test.Provider.TryCreate(expectation.SourceRepository, CancellationToken.None); - - Assert.True(result.Item1); - Assert.IsType<PluginResource>(result.Item2); - - var pluginResource = (PluginResource)result.Item2; - var pluginResult = await pluginResource.GetPluginAsync( - OperationClaim.DownloadPackage, - CancellationToken.None); - - switch (i) - { - case 0: - firstPluginResult = pluginResult.Plugin; - break; - - case 1: - Assert.Null(pluginResult); - break; - - case 2: - thirdPluginResult = pluginResult.Plugin; - break; - } - } - - Assert.NotNull(firstPluginResult); - Assert.Same(firstPluginResult, thirdPluginResult); - } - } - - [Fact] - public void Reinitialize_ThrowsForNullReader() - { - var provider = new PluginResourceProvider(); - var exception = Assert.Throws<ArgumentNullException>( - () => provider.Reinitialize( - reader: null, - pluginDiscoverer: new Lazy<IPluginDiscoverer>(), - pluginFactory: Mock.Of<IPluginFactory>())); - - Assert.Equal("reader", exception.ParamName); - } - - [Fact] - public void Reinitialize_ThrowsForNullPluginDiscoverer() - { - var provider = new PluginResourceProvider(); - var exception = Assert.Throws<ArgumentNullException>( - () => provider.Reinitialize( - Mock.Of<IEnvironmentVariableReader>(), - pluginDiscoverer: null, - pluginFactory: Mock.Of<IPluginFactory>())); - - Assert.Equal("pluginDiscoverer", exception.ParamName); - } - - [Fact] - public void Reinitialize_ThrowsForNullPluginFactory() - { - var provider = new PluginResourceProvider(); - var exception = Assert.Throws<ArgumentNullException>( - () => provider.Reinitialize( - Mock.Of<IEnvironmentVariableReader>(), - new Lazy<IPluginDiscoverer>(() => Mock.Of<IPluginDiscoverer>()), - pluginFactory: null)); - - Assert.Equal("pluginFactory", exception.ParamName); - } - - [Fact] - public void Reinitialize_SetsNewReader() - { - var reader = Mock.Of<IEnvironmentVariableReader>(); - var provider = new PluginResourceProvider(); - - provider.Reinitialize( - reader, - new Lazy<IPluginDiscoverer>(() => Mock.Of<IPluginDiscoverer>()), - Mock.Of<IPluginFactory>()); - - Assert.Same(reader, PluginResourceProvider.EnvironmentVariableReader); - } - - private static SourceRepository CreateSourceRepository( - ServiceIndexResourceV3 serviceIndexResource, - string sourceUri) - { - var packageSource = new PackageSource(sourceUri); - var provider = new Mock<ServiceIndexResourceV3Provider>(); - - provider.Setup(x => x.Name) - .Returns(nameof(ServiceIndexResourceV3Provider)); - provider.Setup(x => x.ResourceType) - .Returns(typeof(ServiceIndexResourceV3)); - - var tryCreateResult = new Tuple<bool, INuGetResource>(serviceIndexResource != null, serviceIndexResource); - - provider.Setup(x => x.TryCreate(It.IsAny<SourceRepository>(), It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(tryCreateResult)); - - return new SourceRepository(packageSource, new[] { provider.Object }); - } - - private sealed class PluginResourceProviderNegativeTest - { - internal PluginResourceProvider Provider { get; } - internal SourceRepository SourceRepository { get; } - - internal PluginResourceProviderNegativeTest(string serviceIndexJson, string sourceUri, string pluginsPath = "a") - { - var serviceIndex = string.IsNullOrEmpty(serviceIndexJson) - ? null : new ServiceIndexResourceV3(JObject.Parse(serviceIndexJson), DateTime.UtcNow); - - SourceRepository = CreateSourceRepository(serviceIndex, sourceUri); - - var reader = new Mock<IEnvironmentVariableReader>(MockBehavior.Strict); - - reader.Setup(x => x.GetEnvironmentVariable( - It.Is<string>(value => value == _pluginPathsEnvironmentVariable))) - .Returns(pluginsPath); - reader.Setup(x => x.GetEnvironmentVariable( - It.Is<string>(value => value == _pluginRequestTimeoutEnvironmentVariable))) - .Returns("b"); - - var pluginDiscoverer = new Mock<IPluginDiscoverer>(MockBehavior.Strict); - var pluginDiscoveryResults = GetPluginDiscoveryResults(pluginsPath); - - pluginDiscoverer.Setup(x => x.DiscoverAsync(It.IsAny<CancellationToken>())) - .ReturnsAsync(pluginDiscoveryResults); - - Provider = new PluginResourceProvider(); - - Provider.Reinitialize( - reader.Object, - new Lazy<IPluginDiscoverer>(() => pluginDiscoverer.Object), - Mock.Of<IPluginFactory>()); - } - - private static IEnumerable<PluginDiscoveryResult> GetPluginDiscoveryResults(string pluginPaths) - { - var results = new List<PluginDiscoveryResult>(); - - if (string.IsNullOrEmpty(pluginPaths)) - { - return results; - } - - foreach (var path in pluginPaths.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) - { - var state = path == "a" ? PluginFileState.Valid : PluginFileState.InvalidEmbeddedSignature; - var file = new PluginFile(path, state); - - results.Add(new PluginDiscoveryResult(file)); - } - - return results; - } - } - - private sealed class PluginResourceProviderPositiveTest : IDisposable - { - private readonly Mock<IConnection> _connection; - private readonly IEnumerable<PositiveTestExpectation> _expectations; - private readonly Mock<IPluginFactory> _factory; - private readonly Mock<IPlugin> _plugin; - private readonly Mock<IPluginDiscoverer> _pluginDiscoverer; - private readonly Mock<IEnvironmentVariableReader> _reader; - - internal PluginResourceProvider Provider { get; } - - internal PluginResourceProviderPositiveTest( - string pluginFilePath, - PluginFileState pluginFileState, - IEnumerable<PositiveTestExpectation> expectations) - { - _expectations = expectations; - - _reader = new Mock<IEnvironmentVariableReader>(MockBehavior.Strict); - - _reader.Setup(x => x.GetEnvironmentVariable( - It.Is<string>(value => value == _pluginPathsEnvironmentVariable))) - .Returns(pluginFilePath); - _reader.Setup(x => x.GetEnvironmentVariable( - It.Is<string>(value => value == _pluginRequestTimeoutEnvironmentVariable))) - .Returns("timeout"); - - _pluginDiscoverer = new Mock<IPluginDiscoverer>(MockBehavior.Strict); - - _pluginDiscoverer.Setup(x => x.Dispose()); - _pluginDiscoverer.Setup(x => x.DiscoverAsync(It.IsAny<CancellationToken>())) - .ReturnsAsync(new[] - { - new PluginDiscoveryResult(new PluginFile(pluginFilePath, pluginFileState)) - }); - - _connection = new Mock<IConnection>(MockBehavior.Strict); - - _connection.Setup(x => x.Dispose()); - _connection.SetupGet(x => x.Options) - .Returns(ConnectionOptions.CreateDefault()); - - _connection.Setup(x => x.SendRequestAndReceiveResponseAsync<MonitorNuGetProcessExitRequest, MonitorNuGetProcessExitResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.MonitorNuGetProcessExit), - It.IsNotNull<MonitorNuGetProcessExitRequest>(), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new MonitorNuGetProcessExitResponse(MessageResponseCode.Success)); - - _connection.Setup(x => x.SendRequestAndReceiveResponseAsync<InitializeRequest, InitializeResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.Initialize), - It.IsNotNull<InitializeRequest>(), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new InitializeResponse(MessageResponseCode.Success)); - - foreach (var expectation in expectations) - { - _connection.Setup(x => x.SendRequestAndReceiveResponseAsync<GetOperationClaimsRequest, GetOperationClaimsResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.GetOperationClaims), - It.Is<GetOperationClaimsRequest>( - g => g.PackageSourceRepository == expectation.SourceRepository.PackageSource.Source), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new GetOperationClaimsResponse(expectation.OperationClaims.ToArray())); - - if (expectation.OperationClaims.Any()) - { - _connection.Setup(x => x.SendRequestAndReceiveResponseAsync<SetCredentialsRequest, SetCredentialsResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.SetCredentials), - It.Is<SetCredentialsRequest>( - g => g.PackageSourceRepository == expectation.SourceRepository.PackageSource.Source), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new SetCredentialsResponse(MessageResponseCode.Success)); - } - } - - _plugin = new Mock<IPlugin>(MockBehavior.Strict); - - _plugin.Setup(x => x.Dispose()); - _plugin.SetupGet(x => x.Connection) - .Returns(_connection.Object); - _plugin.SetupGet(x => x.Id) - .Returns("id"); - - _factory = new Mock<IPluginFactory>(MockBehavior.Strict); - - _factory.Setup(x => x.Dispose()); - _factory.Setup(x => x.GetOrCreateAsync( - It.Is<string>(p => p == pluginFilePath), - It.IsNotNull<IEnumerable<string>>(), - It.IsNotNull<IRequestHandlers>(), - It.IsNotNull<ConnectionOptions>(), - It.IsAny<CancellationToken>())) - .ReturnsAsync(_plugin.Object); - - Provider = new PluginResourceProvider(); - - Provider.Reinitialize( - _reader.Object, - new Lazy<IPluginDiscoverer>(() => _pluginDiscoverer.Object), - _factory.Object); - } - - public void Dispose() - { - Provider.Dispose(); - GC.SuppressFinalize(this); - - _reader.Verify(); - _pluginDiscoverer.Verify(); - - foreach (var expectation in _expectations) - { - _connection.Verify(x => x.SendRequestAndReceiveResponseAsync<GetOperationClaimsRequest, GetOperationClaimsResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.GetOperationClaims), - It.Is<GetOperationClaimsRequest>( - g => g.PackageSourceRepository == expectation.SourceRepository.PackageSource.Source), - It.IsAny<CancellationToken>()), Times.Once()); - - var expectedSetCredentialsRequestCalls = expectation.OperationClaims.Any() - ? Times.Once() : Times.Never(); - - _connection.Verify(x => x.SendRequestAndReceiveResponseAsync<SetCredentialsRequest, SetCredentialsResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.SetCredentials), - It.Is<SetCredentialsRequest>( - g => g.PackageSourceRepository == expectation.SourceRepository.PackageSource.Source), - It.IsAny<CancellationToken>()), expectedSetCredentialsRequestCalls); - } - - _plugin.Verify(); - _factory.Verify(); - } - } - - private sealed class PositiveTestExpectation - { - internal IEnumerable<OperationClaim> OperationClaims { get; } - internal SourceRepository SourceRepository { get; } - - internal PositiveTestExpectation( - string serviceIndexJson, - string sourceUri, - IEnumerable<OperationClaim> operationClaims) - { - var serviceIndex = string.IsNullOrEmpty(serviceIndexJson) - ? null : new ServiceIndexResourceV3(JObject.Parse(serviceIndexJson), DateTime.UtcNow); - - OperationClaims = operationClaims; - SourceRepository = CreateSourceRepository(serviceIndex, sourceUri); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginResourceTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginResourceTests.cs deleted file mode 100644 index f688c99a702..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginResourceTests.cs +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Configuration; -using NuGet.Protocol.Core.Types; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginResourceTests - { - private static readonly PackageSource _packageSource = new PackageSource("https://unit.test"); - - [Fact] - public void Constructor_ThrowsForNullPluginCreationResults() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginResource( - pluginCreationResults: null, - packageSource: _packageSource, - credentialService: Mock.Of<ICredentialService>())); - - Assert.Equal("pluginCreationResults", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullPackageSource() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new PluginResource( - Enumerable.Empty<PluginCreationResult>(), - packageSource: null, - credentialService: Mock.Of<ICredentialService>())); - - Assert.Equal("packageSource", exception.ParamName); - } - - [Fact] - public void Constructor_AcceptsNullCredentialService() - { - new PluginResource( - Enumerable.Empty<PluginCreationResult>(), - _packageSource, - credentialService: null); - } - - [Fact] - public async Task GetPluginAsync_ThrowsIfCancelled() - { - var resource = new PluginResource( - Enumerable.Empty<PluginCreationResult>(), - _packageSource, - Mock.Of<ICredentialService>()); - - await Assert.ThrowsAsync<OperationCanceledException>( - () => resource.GetPluginAsync(OperationClaim.DownloadPackage, new CancellationToken(canceled: true))); - } - - [Fact] - public async Task GetPluginAsync_ReturnsNullIfNoPlugins() - { - var resource = new PluginResource( - Enumerable.Empty<PluginCreationResult>(), - _packageSource, - Mock.Of<ICredentialService>()); - - var result = await resource.GetPluginAsync(OperationClaim.DownloadPackage, CancellationToken.None); - - Assert.Null(result); - } - - [Fact] - public async Task GetPluginAsync_ReturnsNullIfNoPluginWithMatchingOperationClaim() - { - var resource = new PluginResource( - new[] { new PluginCreationResult( - Mock.Of<IPlugin>(), - Mock.Of<IPluginMulticlientUtilities>(), - new[] { OperationClaim.DownloadPackage }) }, - _packageSource, - Mock.Of<ICredentialService>()); - - var result = await resource.GetPluginAsync((OperationClaim)int.MaxValue, CancellationToken.None); - - Assert.Null(result); - } - - [Fact] - public async Task GetPluginAsync_ThrowsIfFirstPluginDiscoveryFailed() - { - var pluginCreationResults = new List<PluginCreationResult>() - { - new PluginCreationResult(message: "test"), - new PluginCreationResult( - Mock.Of<IPlugin>(), - Mock.Of<IPluginMulticlientUtilities>(), - new[] { OperationClaim.DownloadPackage }) - }; - var resource = new PluginResource( - pluginCreationResults, - _packageSource, - Mock.Of<ICredentialService>()); - - var exception = await Assert.ThrowsAsync<PluginException>( - () => resource.GetPluginAsync(OperationClaim.DownloadPackage, CancellationToken.None)); - - Assert.Equal("test", exception.Message); - } - - [Fact] - public async Task GetPluginAsync_ReturnsFirstPluginWithMatchingOperationClaim() - { - var plugin = new Mock<IPlugin>(MockBehavior.Strict); - var utilities = new Mock<IPluginMulticlientUtilities>(MockBehavior.Strict); - var connection = new Mock<IConnection>(MockBehavior.Strict); - - connection.Setup(x => x.SendRequestAndReceiveResponseAsync<SetCredentialsRequest, SetCredentialsResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.SetCredentials), - It.Is<SetCredentialsRequest>(s => s.PackageSourceRepository == _packageSource.Source - && s.ProxyUsername == null && s.ProxyPassword == null - && s.Username == null && s.Password == null), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new SetCredentialsResponse(MessageResponseCode.Success)); - - plugin.SetupGet(x => x.Connection) - .Returns(connection.Object); - - utilities.Setup(x => x.DoOncePerPluginLifetimeAsync( - It.IsNotNull<string>(), - It.IsNotNull<Func<Task>>(), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - var pluginCreationResults = new List<PluginCreationResult>() - { - new PluginCreationResult( - plugin.Object, - utilities.Object, - new[] { OperationClaim.DownloadPackage }), - new PluginCreationResult( - Mock.Of<IPlugin>(), - Mock.Of<IPluginMulticlientUtilities>(), - new[] { OperationClaim.DownloadPackage }) - }; - var resource = new PluginResource( - pluginCreationResults, - _packageSource, - credentialService: null); - - var result = await resource.GetPluginAsync(OperationClaim.DownloadPackage, CancellationToken.None); - - Assert.Same(pluginCreationResults[0].Plugin, result.Plugin); - Assert.Same(pluginCreationResults[0].PluginMulticlientUtilities, result.PluginMulticlientUtilities); - - connection.Verify(); - plugin.Verify(); - utilities.Verify(); - } - - [Fact] - public async Task GetPluginAsync_SendsLastKnownGoodCredentialsFromCredentialsCache() - { - var plugin = new Mock<IPlugin>(MockBehavior.Strict); - var utilities = new Mock<IPluginMulticlientUtilities>(MockBehavior.Strict); - var connection = new Mock<IConnection>(MockBehavior.Strict); - var credentialService = new Mock<ICredentialService>(MockBehavior.Strict); - var proxyCredentials = new NetworkCredential(userName: "a", password: "b"); - ICredentials proxyCredentialsOutResult = proxyCredentials; - var packageSourceCredentials = new NetworkCredential(userName: "c", password: "d"); - ICredentials packageSourceCredentialsOutResult = packageSourceCredentials; - - credentialService.Setup(x => x.TryGetLastKnownGoodCredentialsFromCache( - It.Is<Uri>(u => u == _packageSource.SourceUri), - It.Is<bool>(i => i), - out proxyCredentialsOutResult)) - .Returns(true); - - credentialService.Setup(x => x.TryGetLastKnownGoodCredentialsFromCache( - It.Is<Uri>(u => u == _packageSource.SourceUri), - It.Is<bool>(i => !i), - out packageSourceCredentialsOutResult)) - .Returns(true); - - connection.Setup(x => x.SendRequestAndReceiveResponseAsync<SetCredentialsRequest, SetCredentialsResponse>( - It.Is<MessageMethod>(m => m == MessageMethod.SetCredentials), - It.Is<SetCredentialsRequest>(s => s.PackageSourceRepository == _packageSource.Source - && s.ProxyUsername == proxyCredentials.UserName - && s.ProxyPassword == proxyCredentials.Password - && s.Username == packageSourceCredentials.UserName - && s.Password == packageSourceCredentials.Password), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new SetCredentialsResponse(MessageResponseCode.Success)); - - plugin.SetupGet(x => x.Connection) - .Returns(connection.Object); - - utilities.Setup(x => x.DoOncePerPluginLifetimeAsync( - It.IsNotNull<string>(), - It.IsNotNull<Func<Task>>(), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - var pluginCreationResults = new List<PluginCreationResult>() - { - new PluginCreationResult( - plugin.Object, - utilities.Object, - new[] { OperationClaim.DownloadPackage }), - }; - var resource = new PluginResource( - pluginCreationResults, - _packageSource, - credentialService.Object); - - var result = await resource.GetPluginAsync(OperationClaim.DownloadPackage, CancellationToken.None); - - Assert.Same(pluginCreationResults[0].Plugin, result.Plugin); - Assert.Same(pluginCreationResults[0].PluginMulticlientUtilities, result.PluginMulticlientUtilities); - - connection.Verify(); - plugin.Verify(); - utilities.Verify(); - credentialService.Verify(); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginTests.cs deleted file mode 100644 index 9da216cc4d8..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/PluginTests.cs +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; -using Moq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class PluginTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_ThrowsForNullOrEmptyFilePath(string filePath) - { - var exception = Assert.Throws<ArgumentException>( - () => new Plugin( - filePath, - Mock.Of<IConnection>(), - Mock.Of<IPluginProcess>(), - isOwnProcess: false, - idleTimeout: Timeout.InfiniteTimeSpan)); - - Assert.Equal("filePath", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullConnection() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new Plugin( - filePath: "a", - connection: null, - process: Mock.Of<IPluginProcess>(), - isOwnProcess: false, - idleTimeout: Timeout.InfiniteTimeSpan)); - - Assert.Equal("connection", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullProcess() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new Plugin( - filePath: "a", - connection: Mock.Of<IConnection>(), - process: null, - isOwnProcess: false, - idleTimeout: Timeout.InfiniteTimeSpan)); - - Assert.Equal("process", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForTooSmallIdleTimeout() - { - var idleTimeout = TimeSpan.FromMilliseconds(Timeout.InfiniteTimeSpan.TotalMilliseconds - 1); - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new Plugin( - filePath: "a", - connection: Mock.Of<IConnection>(), - process: Mock.Of<IPluginProcess>(), - isOwnProcess: false, - idleTimeout: idleTimeout)); - - Assert.Equal("idleTimeout", exception.ParamName); - Assert.Equal(idleTimeout, exception.ActualValue); - } - - [Fact] - public void Constructor_InitializesProperties() - { - var filePath = Path.Combine(".", "a", "b", "c.d"); - var connection = Mock.Of<IConnection>(); - var isOwnProcess = false; - var idleTimeout = Timeout.InfiniteTimeSpan; - - using (var plugin = new Plugin(filePath, connection, Mock.Of<IPluginProcess>(), isOwnProcess, idleTimeout)) - { - Assert.Same(connection, plugin.Connection); - Assert.Equal(filePath, plugin.FilePath); - Assert.Equal("c", plugin.Name); - } - } - - [Fact] - public void Close_FiresBeforeCloseThenClosedEvents() - { - var filePath = Path.Combine(".", "a"); - var connection = Mock.Of<IConnection>(); - var isOwnProcess = false; - var idleTimeout = Timeout.InfiniteTimeSpan; - - using (var plugin = new Plugin(filePath, connection, Mock.Of<IPluginProcess>(), isOwnProcess, idleTimeout)) - { - var wasBeforeCloseFired = false; - var wasClosedFired = false; - - plugin.BeforeClose += (sender, args) => - { - wasBeforeCloseFired = true; - - Assert.False(wasClosedFired); - }; - - plugin.Closed += (sender, args) => wasClosedFired = true; - - plugin.Close(); - - Assert.True(wasBeforeCloseFired); - Assert.True(wasClosedFired); - } - } - - [Fact] - public void Close_HandlesExceptionsInEventHandler() - { - var filePath = Path.Combine(".", "a"); - var connection = Mock.Of<IConnection>(); - var isOwnProcess = false; - var idleTimeout = Timeout.InfiniteTimeSpan; - - using (var plugin = new Plugin(filePath, connection, Mock.Of<IPluginProcess>(), isOwnProcess, idleTimeout)) - { - plugin.BeforeClose += (sender, args) => throw new Exception("thrown in event handler"); - plugin.Closed += (sender, args) => throw new Exception("thrown in event handler"); - - plugin.Close(); - } - } - - [Fact] - public void Close_ClosesConnection() - { - var filePath = Path.Combine(".", "a"); - var connection = new Mock<IConnection>(MockBehavior.Strict); - var isOwnProcess = false; - var idleTimeout = Timeout.InfiniteTimeSpan; - - connection.Setup(x => x.Close()); - - using (var plugin = new Plugin( - filePath, - connection.Object, - Mock.Of<IPluginProcess>(), - isOwnProcess, - idleTimeout)) - { - connection.Verify(); - - connection.Setup(x => x.Dispose()); - } - } - - [Fact] - public void Close_IsIdempotent() - { - var filePath = Path.Combine(".", "a"); - var connection = Mock.Of<IConnection>(); - var isOwnProcess = false; - var idleTimeout = Timeout.InfiniteTimeSpan; - - using (var plugin = new Plugin(filePath, connection, Mock.Of<IPluginProcess>(), isOwnProcess, idleTimeout)) - { - var beforeCloseEventCount = 0; - var closedEventCount = 0; - - plugin.BeforeClose += (sender, args) => ++beforeCloseEventCount; - plugin.Closed += (sender, args) => ++closedEventCount; - - plugin.Close(); - plugin.Close(); - - Assert.Equal(1, beforeCloseEventCount); - Assert.Equal(1, closedEventCount); - } - } - - [Fact] - public void Dispose_DisposesResources() - { - var connection = new Mock<IConnection>(MockBehavior.Strict); - var process = new Mock<IPluginProcess>(MockBehavior.Strict); - - connection.Setup(x => x.Dispose()); - connection.Setup(x => x.Close()); - process.Setup(x => x.Kill()); - process.Setup(x => x.Dispose()); - - using (var plugin = new Plugin( - filePath: @"C:\a\b\c.d", - connection: connection.Object, - process: process.Object, - isOwnProcess: false, - idleTimeout: Timeout.InfiniteTimeSpan)) - { - } - - connection.Verify(x => x.Dispose(), Times.Once); - connection.Verify(x => x.Close(), Times.Once); - process.Verify(x => x.Kill(), Times.Once); - process.Verify(x => x.Dispose(), Times.Once); - } - - [Fact] - public void Dispose_CallsClose() - { - var filePath = Path.Combine(".", "a"); - var connection = Mock.Of<IConnection>(); - var isOwnProcess = false; - var idleTimeout = Timeout.InfiniteTimeSpan; - var wasBeforeCloseFired = false; - var wasClosedFired = false; - - using (var plugin = new Plugin(filePath, connection, Mock.Of<IPluginProcess>(), isOwnProcess, idleTimeout)) - { - plugin.BeforeClose += (sender, args) => wasBeforeCloseFired = true; - plugin.Closed += (sender, args) => wasClosedFired = true; - } - - Assert.True(wasBeforeCloseFired); - Assert.True(wasClosedFired); - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var plugin = new Plugin( - filePath: @"C:\a\b\c.d", - connection: Mock.Of<IConnection>(), - process: Mock.Of<IPluginProcess>(), - isOwnProcess: false, - idleTimeout: Timeout.InfiniteTimeSpan)) - { - plugin.Dispose(); - plugin.Dispose(); - } - } - - [Fact] - public void Exited_RaisedOnProcessExited() - { - var process = new Mock<IPluginProcess>(); - - process.Setup(x => x.HasExited) - .Returns(true); - - using (var exitedEvent = new ManualResetEventSlim(initialState: false)) - using (var plugin = new Plugin( - filePath: @"C:\a\b\c.d", - connection: Mock.Of<IConnection>(), - process: process.Object, - isOwnProcess: false, - idleTimeout: Timeout.InfiniteTimeSpan)) - { - PluginEventArgs args = null; - - plugin.Exited += (object sender, PluginEventArgs e) => - { - args = e; - - exitedEvent.Set(); - }; - - process.Raise(x => x.Exited += null, EventArgs.Empty); - - exitedEvent.Wait(); - - Assert.NotNull(args); - Assert.Same(plugin, args.Plugin); - } - } - - [Fact] - public void Fault_RaisedOnIdleTimeout() - { - var connection = new Mock<IConnection>(); - - using (var faultedEvent = new ManualResetEventSlim(initialState: false)) - using (var plugin = new Plugin( - filePath: @"C:\a\b\c.d", - connection: connection.Object, - process: Mock.Of<IPluginProcess>(), - isOwnProcess: false, - idleTimeout: Timeout.InfiniteTimeSpan)) - { - PluginEventArgs args = null; - - plugin.Faulted += (object sender, PluginEventArgs e) => - { - args = e; - - faultedEvent.Set(); - }; - - var protocolErrorArgs = new ProtocolErrorEventArgs(new ProtocolException("test")); - - connection.Raise(x => x.Faulted += null, protocolErrorArgs); - - faultedEvent.Wait(); - - Assert.NotNull(args); - Assert.Same(plugin, args.Plugin); - } - } - - [Fact] - public void Idle_RaisedOnIdleTimeout() - { - using (var idleEvent = new ManualResetEventSlim(initialState: false)) - using (var plugin = new Plugin( - filePath: @"C:\a\b\c.d", - connection: Mock.Of<IConnection>(), - process: Mock.Of<IPluginProcess>(), - isOwnProcess: false, - idleTimeout: TimeSpan.FromSeconds(1))) - { - var wasFired = false; - - plugin.Idle += (object sender, PluginEventArgs e) => - { - wasFired = true; - - idleEvent.Set(); - }; - - idleEvent.Wait(); - - Assert.True(wasFired); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/ProtocolErrorEventArgsTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/ProtocolErrorEventArgsTests.cs deleted file mode 100644 index 522a4036f83..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/ProtocolErrorEventArgsTests.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class ProtocolErrorEventArgsTests - { - [Fact] - public void Constructor_ThrowsForNullException() - { - var exception = Assert.Throws<ArgumentNullException>(() => new ProtocolErrorEventArgs(exception: null)); - - Assert.Equal("exception", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesExceptionProperty() - { - var exception = new DivideByZeroException(); - var args = new ProtocolErrorEventArgs(exception); - - Assert.Same(exception, args.Exception); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/CloseRequestHandlerTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/CloseRequestHandlerTests.cs deleted file mode 100644 index 81199879334..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/CloseRequestHandlerTests.cs +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class CloseRequestHandlerTests - { - [Fact] - public void Constructor_ThrowsForNullPlugin() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new CloseRequestHandler(plugin: null)); - - Assert.Equal("plugin", exception.ParamName); - } - - [Fact] - public void CancellationToken_IsNone() - { - var handler = new CloseRequestHandler(Mock.Of<IPlugin>()); - - Assert.Equal(CancellationToken.None, handler.CancellationToken); - } - - [Fact] - public void Dispose_DisposesDisposables() - { - using (var test = new CloseRequestHandlerTest()) - { - } - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var test = new CloseRequestHandlerTest()) - { - test.Handler.Dispose(); - test.Handler.Dispose(); - } - } - - [Fact] - public async Task HandleCancelAsync_Throws() - { - using (var test = new CloseRequestHandlerTest()) - { - await Assert.ThrowsAsync<NotSupportedException>( - () => test.Handler.HandleCancelAsync( - Mock.Of<IConnection>(), - new Message( - requestId: "a", - type: MessageType.Cancel, - method: MessageMethod.Close, - payload: null), - Mock.Of<IResponseHandler>(), - CancellationToken.None)); - } - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullConnection() - { - using (var test = new CloseRequestHandlerTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Handler.HandleResponseAsync( - connection: null, - request: new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Close, - payload: null), - responseHandler: Mock.Of<IResponseHandler>(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("connection", exception.ParamName); - } - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullRequest() - { - using (var test = new CloseRequestHandlerTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Handler.HandleResponseAsync( - Mock.Of<IConnection>(), - request: null, - responseHandler: Mock.Of<IResponseHandler>(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("request", exception.ParamName); - } - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullResponseHandler() - { - using (var test = new CloseRequestHandlerTest()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Handler.HandleResponseAsync( - Mock.Of<IConnection>(), - new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Close, - payload: null), - responseHandler: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("responseHandler", exception.ParamName); - } - } - - [Fact] - public async Task HandleResponseAsync_ThrowsIfCancelled() - { - using (var test = new CloseRequestHandlerTest()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Handler.HandleResponseAsync( - Mock.Of<IConnection>(), - new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Close, - payload: null), - Mock.Of<IResponseHandler>(), - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task HandleResponseAsync_ClosesPlugin() - { - using (var test = new CloseRequestHandlerTest()) - { - test.Plugin.Setup(x => x.Close()); - - await test.Handler.HandleResponseAsync( - Mock.Of<IConnection>(), - new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Close, - payload: null), - Mock.Of<IResponseHandler>(), - CancellationToken.None); - - test.Plugin.Verify(x => x.Close(), Times.Once); - } - } - - private sealed class CloseRequestHandlerTest : IDisposable - { - internal CloseRequestHandler Handler { get; } - internal Mock<IPlugin> Plugin { get; } - - internal CloseRequestHandlerTest() - { - Plugin = new Mock<IPlugin>(MockBehavior.Strict); - - Plugin.Setup(x => x.Dispose()); - - Handler = new CloseRequestHandler(Plugin.Object); - } - - public void Dispose() - { - Handler.Dispose(); - - GC.SuppressFinalize(this); - - Plugin.Verify(x => x.Dispose(), Times.Once); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/GetCredentialsRequestHandlerTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/GetCredentialsRequestHandlerTests.cs deleted file mode 100644 index 8fe4d7e095d..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/GetCredentialsRequestHandlerTests.cs +++ /dev/null @@ -1,599 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Linq; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Configuration; -using NuGet.Protocol.Core.Types; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetCredentialsRequestHandlerTests - { - private readonly PackageSource _packageSource = new PackageSource("https://unit.test"); - - [Fact] - public void Constructor_ThrowsForNullPlugin() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new GetCredentialsRequestHandler( - plugin: null, - proxy: Mock.Of<IWebProxy>(), - credentialService: Mock.Of<ICredentialService>())); - - Assert.Equal("plugin", exception.ParamName); - } - - [Fact] - public void CancellationToken_IsNone() - { - using (var provider = CreateDefaultRequestHandler()) - { - Assert.Equal(CancellationToken.None, provider.CancellationToken); - } - } - - [Fact] - public void Dispose_DisposesDisposables() - { - var plugin = new Mock<IPlugin>(MockBehavior.Strict); - - plugin.Setup(x => x.Dispose()); - - var provider = new GetCredentialsRequestHandler( - plugin.Object, - Mock.Of<IWebProxy>(), - Mock.Of<ICredentialService>()); - - provider.Dispose(); - - plugin.Verify(x => x.Dispose(), Times.Once); - } - - [Fact] - public void Dispose_IsIdempotent() - { - var plugin = new Mock<IPlugin>(MockBehavior.Strict); - - plugin.Setup(x => x.Dispose()); - - var provider = new GetCredentialsRequestHandler( - plugin.Object, - Mock.Of<IWebProxy>(), - Mock.Of<ICredentialService>()); - - provider.Dispose(); - provider.Dispose(); - - plugin.Verify(x => x.Dispose(), Times.Once); - } - - [Fact] - public void AddOrUpdateSourceRepository_ThrowsForNullSourceRepository() - { - using (var provider = CreateDefaultRequestHandler()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => provider.AddOrUpdateSourceRepository(sourceRepository: null)); - - Assert.Equal("sourceRepository", exception.ParamName); - } - } - - [Fact] - public async Task HandleCancelAsync_Throws() - { - using (var provider = CreateDefaultRequestHandler()) - { - var request = CreateRequest(MessageType.Cancel); - - await Assert.ThrowsAsync<NotSupportedException>( - () => provider.HandleCancelAsync( - Mock.Of<IConnection>(), - request, - Mock.Of<IResponseHandler>(), - CancellationToken.None)); - } - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullConnection() - { - using (var provider = CreateDefaultRequestHandler()) - { - var request = CreateRequest(MessageType.Request); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => provider.HandleResponseAsync( - connection: null, - request: request, - responseHandler: Mock.Of<IResponseHandler>(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("connection", exception.ParamName); - } - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullRequest() - { - using (var provider = CreateDefaultRequestHandler()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request: null, - responseHandler: Mock.Of<IResponseHandler>(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("request", exception.ParamName); - } - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullResponseHandler() - { - using (var provider = CreateDefaultRequestHandler()) - { - var request = CreateRequest(MessageType.Request); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("responseHandler", exception.ParamName); - } - } - - [Fact] - public async Task HandleResponseAsync_ThrowsIfCancelled() - { - using (var provider = CreateDefaultRequestHandler()) - { - var request = CreateRequest(MessageType.Request); - - await Assert.ThrowsAsync<OperationCanceledException>( - () => provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - Mock.Of<IResponseHandler>(), - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsNotFoundForNonHttpPackageSource() - { - using (var provider = CreateDefaultRequestHandler()) - { - var request = CreateRequest( - MessageType.Request, - new GetCredentialsRequest("\\unit\test", HttpStatusCode.Unauthorized)); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetCredentialsResponse>(r => r.ResponseCode == MessageResponseCode.NotFound - && r.Username == null && r.Password == null), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsNotFoundIfPackageSourceNotFound() - { - var credentialService = new Mock<ICredentialService>(MockBehavior.Strict); - - credentialService.Setup(x => x.GetCredentialsAsync( - It.IsNotNull<Uri>(), - It.IsNotNull<IWebProxy>(), - It.Is<CredentialRequestType>(c => c == CredentialRequestType.Unauthorized), - It.IsNotNull<string>(), - It.IsAny<CancellationToken>())) - .ReturnsAsync((ICredentials)null); - - var plugin = CreateMockPlugin(); - - using (var provider = new GetCredentialsRequestHandler( - plugin, - Mock.Of<IWebProxy>(), - credentialService.Object)) - { - var request = CreateRequest( - MessageType.Request, - new GetCredentialsRequest("https://unit.test", HttpStatusCode.Unauthorized)); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetCredentialsResponse>(r => r.ResponseCode == MessageResponseCode.NotFound - && r.Username == null && r.Password == null), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsPackageSourceCredentialsFromPackageSourceIfValid() - { - _packageSource.Credentials = new PackageSourceCredential( - _packageSource.Source, - username: "a", - passwordText: "b", - isPasswordClearText: true); - - using (var provider = CreateDefaultRequestHandler()) - { - var sourceRepository = new SourceRepository(_packageSource, Enumerable.Empty<INuGetResourceProvider>()); - - provider.AddOrUpdateSourceRepository(sourceRepository); - - var request = CreateRequest( - MessageType.Request, - new GetCredentialsRequest(_packageSource.Source, HttpStatusCode.Unauthorized)); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetCredentialsResponse>(r => r.ResponseCode == MessageResponseCode.Success - && r.Username == "a" && r.Password == "b"), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsPackageSourceCredentialsFromCredentialServiceIfFound() - { - var networkCredential = new NetworkCredential(userName: "a", password: "b"); - var credentialService = new Mock<ICredentialService>(); - var credentials = new Mock<ICredentials>(); - var proxy = Mock.Of<IWebProxy>(); - - credentials.Setup(x => x.GetCredential( - It.Is<Uri>(u => u == _packageSource.SourceUri), - It.Is<string>(a => a == null))) - .Returns(networkCredential); - - credentialService.Setup(x => x.GetCredentialsAsync( - It.Is<Uri>(uri => uri == _packageSource.SourceUri), - It.Is<IWebProxy>(p => p == proxy), - It.Is<CredentialRequestType>(t => t == CredentialRequestType.Unauthorized), - It.IsNotNull<string>(), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(credentials.Object)); - - var plugin = CreateMockPlugin(); - - using (var provider = new GetCredentialsRequestHandler(plugin, proxy, credentialService.Object)) - { - var request = CreateRequest( - MessageType.Request, - new GetCredentialsRequest(_packageSource.Source, HttpStatusCode.Unauthorized)); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetCredentialsResponse>(r => r.ResponseCode == MessageResponseCode.Success - && r.Username == "a" && r.Password == "b"), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsNullPackageSourceCredentialsIfPackageSourceCredentialsAreInvalidAndCredentialServiceIsNull() - { - var plugin = CreateMockPlugin(); - - using (var provider = new GetCredentialsRequestHandler( - plugin, - Mock.Of<IWebProxy>(), - credentialService: null)) - { - var request = CreateRequest( - MessageType.Request, - new GetCredentialsRequest(_packageSource.Source, HttpStatusCode.Unauthorized)); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetCredentialsResponse>(r => r.ResponseCode == MessageResponseCode.NotFound - && r.Username == null && r.Password == null), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsNullPackageSourceCredentialsIfNoCredentials() - { - var credentialService = new Mock<ICredentialService>(); - var credentials = new Mock<ICredentials>(); - var proxy = Mock.Of<IWebProxy>(); - - credentials.Setup(x => x.GetCredential( - It.Is<Uri>(u => u == _packageSource.SourceUri), - It.Is<string>(a => a == null))) - .Returns<NetworkCredential>(null); - - credentialService.Setup(x => x.GetCredentialsAsync( - It.Is<Uri>(uri => uri == _packageSource.SourceUri), - It.Is<IWebProxy>(p => p == proxy), - It.Is<CredentialRequestType>(t => t == CredentialRequestType.Unauthorized), - It.IsNotNull<string>(), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(credentials.Object)); - - var plugin = CreateMockPlugin(); - - using (var provider = new GetCredentialsRequestHandler(plugin, proxy, credentialService.Object)) - { - var request = CreateRequest( - MessageType.Request, - new GetCredentialsRequest(_packageSource.Source, HttpStatusCode.Unauthorized)); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetCredentialsResponse>(r => r.ResponseCode == MessageResponseCode.NotFound - && r.Username == null && r.Password == null), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsProxyCredentialsFromCredentialServiceIfFound() - { - var proxyUri = new Uri("https://proxy.unit.test"); - var networkCredential = new NetworkCredential(userName: "a", password: "b"); - var credentialService = new Mock<ICredentialService>(); - var credentials = new Mock<ICredentials>(); - var proxy = new Mock<IWebProxy>(); - - proxy.Setup(x => x.GetProxy(It.IsAny<Uri>())) - .Returns(proxyUri); - - credentials.Setup(x => x.GetCredential( - It.Is<Uri>(u => u == proxyUri), - It.Is<string>(a => a == "Basic"))) - .Returns(networkCredential); - - credentialService.Setup(x => x.GetCredentialsAsync( - It.Is<Uri>(u => u == _packageSource.SourceUri), - It.Is<IWebProxy>(p => p == proxy.Object), - It.Is<CredentialRequestType>(t => t == CredentialRequestType.Proxy), - It.IsNotNull<string>(), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(credentials.Object)); - - var plugin = CreateMockPlugin(); - - using (var provider = new GetCredentialsRequestHandler(plugin, proxy.Object, credentialService.Object)) - { - var request = CreateRequest( - MessageType.Request, - new GetCredentialsRequest(_packageSource.Source, HttpStatusCode.ProxyAuthenticationRequired)); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetCredentialsResponse>(r => r.ResponseCode == MessageResponseCode.Success - && r.Username == "a" && r.Password == "b"), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsNullProxyCredentialsIfCredentialServiceIsNull() - { - var plugin = CreateMockPlugin(); - - using (var provider = new GetCredentialsRequestHandler( - plugin, - Mock.Of<IWebProxy>(), - credentialService: null)) - { - var request = CreateRequest( - MessageType.Request, - new GetCredentialsRequest(_packageSource.Source, HttpStatusCode.ProxyAuthenticationRequired)); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetCredentialsResponse>(r => r.ResponseCode == MessageResponseCode.NotFound - && r.Username == null && r.Password == null), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsNullProxyCredentialsIfNoCredentials() - { - var credentialService = new Mock<ICredentialService>(); - var credentials = new Mock<ICredentials>(); - var proxy = Mock.Of<IWebProxy>(); - - credentials.Setup(x => x.GetCredential( - It.Is<Uri>(u => u == _packageSource.SourceUri), - It.Is<string>(a => a == null))) - .Returns<NetworkCredential>(null); - - credentialService.Setup(x => x.GetCredentialsAsync( - It.Is<Uri>(uri => uri == _packageSource.SourceUri), - It.Is<IWebProxy>(p => p == proxy), - It.Is<CredentialRequestType>(t => t == CredentialRequestType.Proxy), - It.IsNotNull<string>(), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(credentials.Object)); - - var plugin = CreateMockPlugin(); - - using (var provider = new GetCredentialsRequestHandler(plugin, proxy, credentialService.Object)) - { - var request = CreateRequest( - MessageType.Request, - new GetCredentialsRequest(_packageSource.Source, HttpStatusCode.ProxyAuthenticationRequired)); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetCredentialsResponse>(r => r.ResponseCode == MessageResponseCode.NotFound - && r.Username == null && r.Password == null), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsNullProxyCredentialsIfNoProxy() - { - var plugin = CreateMockPlugin(); - - using (var provider = new GetCredentialsRequestHandler( - plugin, - proxy: null, - credentialService: Mock.Of<ICredentialService>())) - { - var request = CreateRequest( - MessageType.Request, - new GetCredentialsRequest(_packageSource.Source, HttpStatusCode.ProxyAuthenticationRequired)); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetCredentialsResponse>(r => r.ResponseCode == MessageResponseCode.NotFound - && r.Username == null && r.Password == null), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - private GetCredentialsRequestHandler CreateDefaultRequestHandler() - { - var plugin = CreateMockPlugin(); - - return new GetCredentialsRequestHandler(plugin, Mock.Of<IWebProxy>(), Mock.Of<ICredentialService>()); - } - - private static IPlugin CreateMockPlugin() - { - var plugin = new Mock<IPlugin>(); - - plugin.SetupGet(x => x.Connection) - .Returns(Mock.Of<IConnection>()); - - return plugin.Object; - } - - private static Message CreateRequest(MessageType type, GetCredentialsRequest payload = null) - { - if (payload == null) - { - return new Message( - requestId: "a", - type: type, - method: MessageMethod.GetCredentials, - payload: null); - } - - return MessageUtilities.Create( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.GetCredentials, - payload: payload); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/GetServiceIndexRequestHandlerTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/GetServiceIndexRequestHandlerTests.cs deleted file mode 100644 index 7b043e68898..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/GetServiceIndexRequestHandlerTests.cs +++ /dev/null @@ -1,312 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using NuGet.Configuration; -using NuGet.Protocol.Core.Types; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class GetServiceIndexRequestHandlerTests - { - [Fact] - public void Constructor_ThrowsForNullPlugin() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new GetServiceIndexRequestHandler(plugin: null)); - - Assert.Equal("plugin", exception.ParamName); - } - - [Fact] - public void CancellationToken_IsNone() - { - using (var provider = new GetServiceIndexRequestHandler(Mock.Of<IPlugin>())) - { - Assert.Equal(CancellationToken.None, provider.CancellationToken); - } - } - - [Fact] - public void Dispose_DisposesDisposables() - { - var plugin = new Mock<IPlugin>(MockBehavior.Strict); - - plugin.Setup(x => x.Dispose()); - - var provider = new GetServiceIndexRequestHandler(plugin.Object); - - provider.Dispose(); - - plugin.Verify(x => x.Dispose(), Times.Once); - } - - [Fact] - public void Dispose_IsIdempotent() - { - var plugin = new Mock<IPlugin>(MockBehavior.Strict); - - plugin.Setup(x => x.Dispose()); - - var provider = new GetServiceIndexRequestHandler(plugin.Object); - - provider.Dispose(); - provider.Dispose(); - - plugin.Verify(x => x.Dispose(), Times.Once); - } - - [Fact] - public void AddOrUpdateSourceRepository_ThrowsForNullSourceRepository() - { - using (var provider = new GetServiceIndexRequestHandler(Mock.Of<IPlugin>())) - { - var exception = Assert.Throws<ArgumentNullException>( - () => provider.AddOrUpdateSourceRepository(sourceRepository: null)); - - Assert.Equal("sourceRepository", exception.ParamName); - } - } - - [Fact] - public async Task HandleCancelAsync_Throws() - { - using (var provider = new GetServiceIndexRequestHandler(Mock.Of<IPlugin>())) - { - var request = CreateRequest(MessageType.Cancel); - - await Assert.ThrowsAsync<NotSupportedException>( - () => provider.HandleCancelAsync( - Mock.Of<IConnection>(), - request, - Mock.Of<IResponseHandler>(), - CancellationToken.None)); - } - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullConnection() - { - using (var provider = new GetServiceIndexRequestHandler(Mock.Of<IPlugin>())) - { - var request = CreateRequest(MessageType.Request); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => provider.HandleResponseAsync( - connection: null, - request: request, - responseHandler: Mock.Of<IResponseHandler>(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("connection", exception.ParamName); - } - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullRequest() - { - using (var provider = new GetServiceIndexRequestHandler(Mock.Of<IPlugin>())) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request: null, - responseHandler: Mock.Of<IResponseHandler>(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("request", exception.ParamName); - } - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullResponseHandler() - { - using (var provider = new GetServiceIndexRequestHandler(Mock.Of<IPlugin>())) - { - var request = CreateRequest(MessageType.Request); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("responseHandler", exception.ParamName); - } - } - - [Fact] - public async Task HandleResponseAsync_ThrowsIfCancelled() - { - using (var provider = new GetServiceIndexRequestHandler(Mock.Of<IPlugin>())) - { - var request = CreateRequest(MessageType.Request); - - await Assert.ThrowsAsync<OperationCanceledException>( - () => provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - Mock.Of<IResponseHandler>(), - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsNotFoundForNonHttpPackageSource() - { - using (var provider = new GetServiceIndexRequestHandler(Mock.Of<IPlugin>())) - { - var request = CreateRequest( - MessageType.Request, - new GetServiceIndexRequest("\\unit\test")); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetServiceIndexResponse>(r => r.ResponseCode == MessageResponseCode.NotFound), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsNotFoundIfPackageSourceNotFound() - { - using (var provider = new GetServiceIndexRequestHandler(Mock.Of<IPlugin>())) - { - var request = CreateRequest( - MessageType.Request, - new GetServiceIndexRequest("https://unit.test")); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetServiceIndexResponse>(r => r.ResponseCode == MessageResponseCode.NotFound), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsNotFoundSourceRepositoryReturnsNullServiceIndex() - { - using (var provider = new GetServiceIndexRequestHandler(Mock.Of<IPlugin>())) - { - var packageSource = new PackageSource("https://unit.test"); - var sourceRepository = new SourceRepository(packageSource, Enumerable.Empty<INuGetResourceProvider>()); - - provider.AddOrUpdateSourceRepository(sourceRepository); - - var request = CreateRequest( - MessageType.Request, - new GetServiceIndexRequest(packageSource.Source)); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetServiceIndexResponse>(r => r.ResponseCode == MessageResponseCode.NotFound), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - [Fact] - public async Task HandleResponseAsync_ReturnsSuccessIfServiceIndexIsFound() - { - using (var provider = new GetServiceIndexRequestHandler(Mock.Of<IPlugin>())) - { - var packageSource = new PackageSource("https://unit.test"); - var serviceIndex = JObject.Parse("{}"); - var serviceIndexResource = new ServiceIndexResourceV3(serviceIndex, DateTime.UtcNow); - var serviceIndexResourceProvider = new Mock<INuGetResourceProvider>(); - - serviceIndexResourceProvider.SetupGet(x => x.ResourceType) - .Returns(typeof(ServiceIndexResourceV3)); - - serviceIndexResourceProvider.SetupGet(x => x.Name) - .Returns(nameof(ServiceIndexResourceV3Provider)); - - serviceIndexResourceProvider.Setup(x => x.TryCreate( - It.IsNotNull<SourceRepository>(), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new Tuple<bool, INuGetResource>(true, serviceIndexResource)); - - var sourceRepository = new SourceRepository( - packageSource, - new INuGetResourceProvider[] { serviceIndexResourceProvider.Object }); - - provider.AddOrUpdateSourceRepository(sourceRepository); - - var request = CreateRequest( - MessageType.Request, - new GetServiceIndexRequest(packageSource.Source)); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<GetServiceIndexResponse>(r => r.ResponseCode == MessageResponseCode.Success - && r.ServiceIndex.ToString(Formatting.None) == serviceIndex.ToString(Formatting.None)), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await provider.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - responseHandler.Verify(); - } - } - - private static Message CreateRequest(MessageType type, GetServiceIndexRequest payload = null) - { - if (payload == null) - { - return new Message( - requestId: "a", - type: type, - method: MessageMethod.GetCredentials, - payload: null); - } - - return MessageUtilities.Create( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.GetCredentials, - payload: payload); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/LogRequestHandlerTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/LogRequestHandlerTests.cs deleted file mode 100644 index 5566a3edb07..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/LogRequestHandlerTests.cs +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Commands; -using NuGet.Common; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class LogRequestHandlerTests - { - [Fact] - public void Constructor_ThrowsForNullLogger() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new LogRequestHandler(logger: null)); - - Assert.Equal("logger", exception.ParamName); - } - - [Fact] - public void CancellationToken_IsNone() - { - var test = new LogRequestHandlerTest(); - - Assert.Equal(CancellationToken.None, test.Handler.CancellationToken); - } - - [Fact] - public async Task HandleCancelAsync_Throws() - { - var test = new LogRequestHandlerTest(); - - await Assert.ThrowsAsync<NotSupportedException>( - () => test.Handler.HandleCancelAsync( - Mock.Of<IConnection>(), - test.Request, - Mock.Of<IResponseHandler>(), - CancellationToken.None)); - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullConnection() - { - var test = new LogRequestHandlerTest(); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Handler.HandleResponseAsync( - connection: null, - request: test.Request, - responseHandler: Mock.Of<IResponseHandler>(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("connection", exception.ParamName); - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullRequest() - { - var test = new LogRequestHandlerTest(); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Handler.HandleResponseAsync( - Mock.Of<IConnection>(), - request: null, - responseHandler: Mock.Of<IResponseHandler>(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("request", exception.ParamName); - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullResponseHandler() - { - var test = new LogRequestHandlerTest(); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Handler.HandleResponseAsync( - Mock.Of<IConnection>(), - test.Request, - responseHandler: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("responseHandler", exception.ParamName); - } - - [Fact] - public async Task HandleResponseAsync_ThrowsIfCancelled() - { - var test = new LogRequestHandlerTest(); - - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Handler.HandleResponseAsync( - Mock.Of<IConnection>(), - test.Request, - Mock.Of<IResponseHandler>(), - new CancellationToken(canceled: true))); - } - - [Fact] - public async Task HandleResponseAsync_LogsDebug() - { - await HandleResponseAsync( - LogLevel.Debug, - LogLevel.Debug, - MessageResponseCode.Success, - expectLog: true); - } - - [Fact] - public async Task HandleResponseAsync_LogsVerbose() - { - await HandleResponseAsync( - LogLevel.Verbose, - LogLevel.Verbose, - MessageResponseCode.Success, - expectLog: true); - } - - [Fact] - public async Task HandleResponseAsync_LogsInformation() - { - await HandleResponseAsync( - LogLevel.Information, - LogLevel.Information, - MessageResponseCode.Success, - expectLog: true); - } - - [Fact] - public async Task HandleResponseAsync_LogsMinimal() - { - await HandleResponseAsync( - LogLevel.Minimal, - LogLevel.Minimal, - MessageResponseCode.Success, - expectLog: true); - } - - [Fact] - public async Task HandleResponseAsync_LogsWarning() - { - await HandleResponseAsync( - LogLevel.Warning, - LogLevel.Warning, - MessageResponseCode.Success, - expectLog: true); - } - - [Fact] - public async Task HandleResponseAsync_LogsError() - { - await HandleResponseAsync( - LogLevel.Error, - LogLevel.Error, - MessageResponseCode.Success, - expectLog: true); - } - - [Theory] - [InlineData(LogLevel.Verbose)] - [InlineData(LogLevel.Information)] - [InlineData(LogLevel.Minimal)] - [InlineData(LogLevel.Warning)] - [InlineData(LogLevel.Error)] - public async Task HandleResponseAsync_FailsOnRequestWithMoreDetailedLogLevel(LogLevel handlerLogLevel) - { - var requestedLogLevel = handlerLogLevel - 1; - - await HandleResponseAsync( - handlerLogLevel, - requestedLogLevel, - MessageResponseCode.Error, - expectLog: false); - } - - [Fact] - public void SetLogger_ThrowsForNullLogger() - { - var test = new LogRequestHandlerTest(); - var exception = Assert.Throws<ArgumentNullException>( - () => test.Handler.SetLogger(logger: null)); - - Assert.Equal("logger", exception.ParamName); - } - - [Fact] - public async Task SetLogger_UpdatesLogger() - { - var test = new LogRequestHandlerTest(); - var secondLogger = new Mock<ILogger>(MockBehavior.Strict); - - test.Handler.SetLogger(secondLogger.Object); - - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.IsNotNull<Message>(), - It.IsNotNull<LogResponse>(), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await test.Handler.HandleResponseAsync( - Mock.Of<IConnection>(), - test.Request, - responseHandler.Object, - CancellationToken.None); - - test.Logger.Verify(); - responseHandler.Verify(); - secondLogger.Verify(); - } - - [Fact] - public void GetLogLevel_ThrowsForNullLogger() - { - var exception = Assert.Throws<ArgumentNullException>( - () => LogRequestHandler.GetLogLevel(logger: null)); - - Assert.Equal("logger", exception.ParamName); - } - - [Theory] - [InlineData(LogLevel.Debug)] - [InlineData(LogLevel.Warning)] - public void GetLogLevel_ReturnsLoggerLogLevel(LogLevel expectedLogLevel) - { - var logger = new RestoreCollectorLogger(Mock.Of<ILogger>(), expectedLogLevel); - var actualLogLevel = LogRequestHandler.GetLogLevel(logger); - - Assert.Equal(expectedLogLevel, actualLogLevel); - } - - [Fact] - public void GetLogLevel_ReturnsInformationIfNotLoggerBase() - { - var logLevel = LogRequestHandler.GetLogLevel(Mock.Of<ILogger>()); - - Assert.Equal(LogLevel.Information, logLevel); - } - - private async Task HandleResponseAsync( - LogLevel handlerLogLevel, - LogLevel requestLogLevel, - MessageResponseCode responseCode, - bool expectLog) - { - var test = new LogRequestHandlerTest(handlerLogLevel); - var payload = new LogRequest(requestLogLevel, message: "a"); - var request = MessageUtilities.Create( - requestId: "b", - type: MessageType.Request, - method: MessageMethod.Log, - payload: payload); - - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(message => message == request), - It.Is<LogResponse>(response => response.ResponseCode == responseCode), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - if (expectLog) - { - test.Logger.Setup( - x => x.Log(It.Is<ILogMessage>(m => m.Message == payload.Message && m.Level == requestLogLevel))); - } - - await test.Handler.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - - test.Logger.Verify(); - } - - private sealed class LogRequestHandlerTest - { - internal LogRequestHandler Handler { get; } - internal Mock<ILogger> Logger { get; } - internal Message Request { get; } - - internal LogRequestHandlerTest(LogLevel logLevel = LogLevel.Debug) - { - Logger = new Mock<ILogger>(MockBehavior.Strict); - Handler = new LogRequestHandler(new RestoreCollectorLogger(Logger.Object, logLevel)); - Request = MessageUtilities.Create( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Log, - payload: new LogRequest(LogLevel.Debug, "b")); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/MonitorNuGetProcessExitRequestHandlerTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/MonitorNuGetProcessExitRequestHandlerTests.cs deleted file mode 100644 index 589aba72f48..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/MonitorNuGetProcessExitRequestHandlerTests.cs +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class MonitorNuGetProcessExitRequestHandlerTests : IDisposable - { - private readonly MonitorNuGetProcessExitRequestHandler _handler; - private readonly Mock<IPlugin> _plugin; - - public MonitorNuGetProcessExitRequestHandlerTests() - { - _plugin = new Mock<IPlugin>(MockBehavior.Strict); - _handler = new MonitorNuGetProcessExitRequestHandler(_plugin.Object); - } - - public void Dispose() - { - _handler.Dispose(); - GC.SuppressFinalize(this); - } - - [Fact] - public void Constructor_ThrowsForNullPlugin() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new MonitorNuGetProcessExitRequestHandler(plugin: null)); - - Assert.Equal("plugin", exception.ParamName); - } - - [Fact] - public void CancellationToken_IsNone() - { - var handler = new MonitorNuGetProcessExitRequestHandler(Mock.Of<IPlugin>()); - - Assert.Equal(CancellationToken.None, handler.CancellationToken); - } - - [Fact] - public async Task HandleCancelAsync_Throws() - { - var request = CreateRequest(MessageType.Cancel); - - await Assert.ThrowsAsync<NotSupportedException>( - () => _handler.HandleCancelAsync( - Mock.Of<IConnection>(), - request, - Mock.Of<IResponseHandler>(), - CancellationToken.None)); - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullConnection() - { - var request = CreateRequest(MessageType.Request); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => _handler.HandleResponseAsync( - connection: null, - request: request, - responseHandler: Mock.Of<IResponseHandler>(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("connection", exception.ParamName); - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullRequest() - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => _handler.HandleResponseAsync( - Mock.Of<IConnection>(), - request: null, - responseHandler: Mock.Of<IResponseHandler>(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("request", exception.ParamName); - } - - [Fact] - public async Task HandleResponseAsync_ThrowsForNullResponseHandler() - { - var request = CreateRequest(MessageType.Request); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => _handler.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("responseHandler", exception.ParamName); - } - - [Fact] - public async Task HandleResponseAsync_ThrowsIfCancelled() - { - var request = CreateRequest(MessageType.Request); - - await Assert.ThrowsAsync<OperationCanceledException>( - () => _handler.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - Mock.Of<IResponseHandler>(), - new CancellationToken(canceled: true))); - } - - [Fact] - public async Task HandleResponseAsync_RespondsWithNotFoundIfProcessNotFound() - { - var invalidProcessId = GetInvalidProcessId(); - var request = CreateRequest(MessageType.Request, invalidProcessId); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<MonitorNuGetProcessExitResponse>(r => r.ResponseCode == MessageResponseCode.NotFound), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await _handler.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - } - - [Fact] - public async Task HandleResponseAsync_RespondsWithSuccessIfProcessFound() - { - var request = CreateRequest(MessageType.Request, processId: GetCurrentProcessId()); - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.Is<Message>(r => r == request), - It.Is<MonitorNuGetProcessExitResponse>(r => r.ResponseCode == MessageResponseCode.Success), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - await _handler.HandleResponseAsync( - Mock.Of<IConnection>(), - request, - responseHandler.Object, - CancellationToken.None); - } - - private static Message CreateRequest(MessageType type, int? processId = null) - { - if (processId.HasValue) - { - var payload = new MonitorNuGetProcessExitRequest(processId.Value); - - return MessageUtilities.Create( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.MonitorNuGetProcessExit, - payload: payload); - } - - return new Message( - requestId: "a", - type: type, - method: MessageMethod.MonitorNuGetProcessExit, - payload: null); - } - - private static int GetCurrentProcessId() - { - using (var process = Process.GetCurrentProcess()) - { - return process.Id; - } - } - - private static int GetInvalidProcessId() - { - for (var processId = -1; processId > int.MinValue; --processId) - { - try - { - using (Process.GetProcessById(processId)) - { - } - } - catch (Exception) - { - return processId; - } - } - - throw new Exception("Unable to find an invalid process ID."); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/SymmetricHandshakeTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/SymmetricHandshakeTests.cs deleted file mode 100644 index 9b9d1913a81..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlers/SymmetricHandshakeTests.cs +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class SymmetricHandshakeTests - { - private static readonly SemanticVersion _version1_0_0 = new SemanticVersion(major: 1, minor: 0, patch: 0); - private static readonly SemanticVersion _version2_0_0 = new SemanticVersion(major: 2, minor: 0, patch: 0); - private static readonly SemanticVersion _version3_0_0 = new SemanticVersion(major: 3, minor: 0, patch: 0); - private static readonly SemanticVersion _version4_0_0 = new SemanticVersion(major: 4, minor: 0, patch: 0); - - private readonly Mock<IConnection> _connection; - private readonly Mock<IMessageDispatcher> _messageDispatcher; - private readonly RequestHandlers _handlers; - - public SymmetricHandshakeTests() - { - _connection = new Mock<IConnection>(); - _messageDispatcher = new Mock<IMessageDispatcher>(); - _handlers = new RequestHandlers(); - } - - [Fact] - public void Constructor_ThrowsForNullConnection() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new SymmetricHandshake( - connection: null, - handshakeTimeout: TimeSpan.FromSeconds(10), - protocolVersion: _version1_0_0, - minimumProtocolVersion: _version1_0_0)); - - Assert.Equal("connection", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullProtocolVersion() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new SymmetricHandshake( - Mock.Of<IConnection>(), - TimeSpan.FromSeconds(10), - protocolVersion: null, - minimumProtocolVersion: _version1_0_0)); - - Assert.Equal("protocolVersion", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForZeroHandshakeTimeout() - { - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new SymmetricHandshake(Mock.Of<IConnection>(), TimeSpan.Zero, _version1_0_0, _version1_0_0)); - - Assert.Equal("handshakeTimeout", exception.ParamName); - Assert.Equal(TimeSpan.Zero, exception.ActualValue); - } - - [Fact] - public void Constructor_ThrowsForNegativeHandshakeTimeout() - { - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new SymmetricHandshake( - Mock.Of<IConnection>(), - TimeSpan.FromSeconds(-1), - _version1_0_0, - _version1_0_0)); - - Assert.Equal("handshakeTimeout", exception.ParamName); - Assert.Equal(TimeSpan.FromSeconds(-1), exception.ActualValue); - } - - [Fact] - public void Constructor_ThrowsForTooLargeHandshakeTimeout() - { - var milliseconds = int.MaxValue + 1L; - - var exception = Assert.Throws<ArgumentOutOfRangeException>( - () => new SymmetricHandshake( - Mock.Of<IConnection>(), - TimeSpan.FromMilliseconds(milliseconds), - _version1_0_0, - _version1_0_0)); - - Assert.Equal("handshakeTimeout", exception.ParamName); - Assert.Equal(TimeSpan.FromMilliseconds(milliseconds), exception.ActualValue); - } - - [Fact] - public void Constructor_ThrowsForNullMinimumProtocolVersion() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new SymmetricHandshake( - Mock.Of<IConnection>(), - TimeSpan.FromSeconds(10), - protocolVersion: ProtocolConstants.CurrentVersion, - minimumProtocolVersion: null)); - - Assert.Equal("minimumProtocolVersion", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsIfHandshakeRequestHandlerAlreadyExists() - { - Assert.True(_handlers.TryAdd(MessageMethod.Handshake, Mock.Of<IRequestHandler>())); - - var exception = Assert.Throws<ArgumentException>(() => CreateHandshake()); - - Assert.Equal("connection", exception.ParamName); - } - - [Fact] - public void Constructor_AddsItselfAsResponseHandler() - { - IRequestHandler handler; - - Assert.False(_handlers.TryGet(MessageMethod.Handshake, out handler)); - - using (var handshake = CreateHandshake()) - { - Assert.True(_handlers.TryGet(MessageMethod.Handshake, out handler)); - Assert.Same(handshake, handler); - } - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var handshake = CreateHandshake()) - { - handshake.Dispose(); - handshake.Dispose(); - } - } - - [Fact] - public void Dispose_RemovesItselfAsResponseHandler() - { - using (var handshake = CreateHandshake()) - { - } - - IRequestHandler handler; - - Assert.False(_handlers.TryGet(MessageMethod.Handshake, out handler)); - } - - [Fact] - public async Task HandleCancelAsync_Throws() - { - using (var handshake = CreateHandshake()) - { - await Assert.ThrowsAsync<ProtocolException>( - () => handshake.HandleCancelAsync( - Mock.Of<IConnection>(), - request: null, - responseHandler: Mock.Of<IResponseHandler>(), - cancellationToken: CancellationToken.None)); - } - } - - [Fact] - public async Task HandleRequestAsync_ThrowsForNullConnection() - { - using (var handshake = CreateHandshake()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => handshake.HandleResponseAsync( - connection: null, - request: new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Handshake), - responseHandler: Mock.Of<IResponseHandler>(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("connection", exception.ParamName); - } - } - - [Fact] - public async Task HandleRequestAsync_ThrowsForNullRequest() - { - using (var handshake = CreateHandshake()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => handshake.HandleResponseAsync( - Mock.Of<IConnection>(), - request: null, - responseHandler: Mock.Of<IResponseHandler>(), - cancellationToken: CancellationToken.None)); - - Assert.Equal("request", exception.ParamName); - } - } - - [Fact] - public async Task HandleRequestAsync_ThrowsForNullResponseHandler() - { - using (var handshake = CreateHandshake()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => handshake.HandleResponseAsync( - Mock.Of<IConnection>(), - new Message(requestId: "a", type: MessageType.Request, method: MessageMethod.Handshake), - responseHandler: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("responseHandler", exception.ParamName); - } - } - - [Fact] - public async Task HandleRequestAsync_ThrowsIfCancelled() - { - using (var handshake = CreateHandshake()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => handshake.HandleResponseAsync( - Mock.Of<IConnection>(), - new Message(requestId: "a", type: MessageType.Request, method: MessageMethod.Initialize), - Mock.Of<IResponseHandler>(), - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task HandleRequestAsync_SucceedsIfProtocolVersionIsSame() - { - await Verify(_version4_0_0, _version3_0_0, _version4_0_0); - } - - [Fact] - public async Task HandleRequestAsync_SucceedsIfHighestCommonDenominatorVersionExists() - { - await Verify(_version3_0_0, _version2_0_0, _version3_0_0); - } - - [Fact] - public async Task HandleRequestAsync_FailsIfNoCompatibleVersionExists() - { - await Verify(_version1_0_0, _version1_0_0, negotiatedProtocolVersion: null); - } - - private async Task Verify( - SemanticVersion requestedProtocolVersion, - SemanticVersion requestedMinimumProtocolVersion, - SemanticVersion negotiatedProtocolVersion) - { - using (var handshake = CreateHandshake()) - { - var responseHandler = new Mock<IResponseHandler>(MockBehavior.Strict); - - responseHandler.Setup(x => x.SendResponseAsync( - It.IsNotNull<Message>(), - It.IsNotNull<HandshakeResponse>(), - It.IsAny<CancellationToken>())) - .Returns(Task.FromResult(0)); - - var request = new HandshakeRequest(requestedProtocolVersion, requestedMinimumProtocolVersion); - var inboundMessage = new Message( - requestId: "a", - type: MessageType.Request, - method: MessageMethod.Handshake, - payload: JsonSerializationUtilities.FromObject(request)); - - await handshake.HandleResponseAsync( - Mock.Of<IConnection>(), - inboundMessage, - responseHandler.Object, - CancellationToken.None); - - var expectedResponseCode = negotiatedProtocolVersion == null - ? MessageResponseCode.Error : MessageResponseCode.Success; - - responseHandler.Verify(x => x.SendResponseAsync( - It.Is<Message>(message => message == inboundMessage), - It.Is<HandshakeResponse>(response => response.ResponseCode == expectedResponseCode && - response.ProtocolVersion == negotiatedProtocolVersion), - It.Is<CancellationToken>(token => !token.IsCancellationRequested)), - Times.Once); - } - } - - private SymmetricHandshake CreateHandshake() - { - _messageDispatcher.Setup(x => x.RequestHandlers) - .Returns(_handlers); - - _connection.Setup(x => x.MessageDispatcher) - .Returns(_messageDispatcher.Object); - - return new SymmetricHandshake(_connection.Object, TimeSpan.FromSeconds(1), _version4_0_0, _version3_0_0); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlersTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlersTests.cs deleted file mode 100644 index a297dfa4c64..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestHandlersTests.cs +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Moq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class RequestHandlersTests - { - private readonly IRequestHandler _handler; - private readonly RequestHandlers _handlers; - - public RequestHandlersTests() - { - _handler = Mock.Of<IRequestHandler>(); - _handlers = new RequestHandlers(); - } - - [Fact] - public void AddOrUpdate_ThrowsForNullAddHandlerFunc() - { - var exception = Assert.Throws<ArgumentNullException>( - () => _handlers.AddOrUpdate( - MessageMethod.Handshake, - addHandlerFunc: null, - updateHandlerFunc: oldHandler => oldHandler)); - - Assert.Equal("addHandlerFunc", exception.ParamName); - } - - [Fact] - public void AddOrUpdate_ThrowsForNullUpdateHandlerFunc() - { - var exception = Assert.Throws<ArgumentNullException>( - () => _handlers.AddOrUpdate( - MessageMethod.Handshake, - () => Mock.Of<IRequestHandler>(), - updateHandlerFunc: null)); - - Assert.Equal("updateHandlerFunc", exception.ParamName); - } - - [Fact] - public void AddOrUpdate_AddsIfDoesNotAlreadyExist() - { - var handler = Mock.Of<IRequestHandler>(); - - _handlers.AddOrUpdate(MessageMethod.Handshake, () => handler, oldHandler => handler); - - IRequestHandler actualHandler; - var wasAdded = _handlers.TryGet(MessageMethod.Handshake, out actualHandler); - - Assert.True(wasAdded); - Assert.Same(handler, actualHandler); - } - - [Fact] - public void AddOrUpdate_UpdatesIfAlreadyExists() - { - var firstHandler = Mock.Of<IRequestHandler>(); - var secondHandler = Mock.Of<IRequestHandler>(); - - _handlers.AddOrUpdate(MessageMethod.Handshake, () => firstHandler, h => firstHandler); - _handlers.AddOrUpdate(MessageMethod.Handshake, () => secondHandler, h => secondHandler); - - IRequestHandler actualHandler; - var wasUpdated = _handlers.TryGet(MessageMethod.Handshake, out actualHandler); - - Assert.True(wasUpdated); - Assert.Same(secondHandler, actualHandler); - } - - [Fact] - public void TryAdd_ThrowsForNullHandler() - { - var exception = Assert.Throws<ArgumentNullException>( - () => _handlers.TryAdd(MessageMethod.Handshake, handler: null)); - - Assert.Equal("handler", exception.ParamName); - } - - [Fact] - public void TryAdd_ReturnsTrueIfAdded() - { - var wasAdded = _handlers.TryAdd(MessageMethod.Handshake, _handler); - - Assert.True(wasAdded); - } - - [Fact] - public void TryAdd_ReturnsFalseIfNotAdded() - { - _handlers.TryAdd(MessageMethod.Handshake, _handler); - var wasAdded = _handlers.TryAdd(MessageMethod.Handshake, _handler); - - Assert.False(wasAdded); - } - - [Fact] - public void TryGet_ReturnsTrueIfGotten() - { - _handlers.TryAdd(MessageMethod.Handshake, _handler); - - IRequestHandler handler; - var wasGotten = _handlers.TryGet(MessageMethod.Handshake, out handler); - - Assert.True(wasGotten); - Assert.Same(_handler, handler); - } - - [Fact] - public void TryGet_ReturnsFalseIfNotGotten() - { - IRequestHandler handler; - var wasGotten = _handlers.TryGet(MessageMethod.Handshake, out handler); - - Assert.False(wasGotten); - Assert.Null(handler); - } - - [Fact] - public void TryRemove_ReturnsTrueIfRemoved() - { - _handlers.TryAdd(MessageMethod.Handshake, _handler); - - var wasRemoved = _handlers.TryRemove(MessageMethod.Handshake); - - Assert.True(wasRemoved); - } - - [Fact] - public void TryRemove_ReturnsFalseIfNotRemoved() - { - var wasRemoved = _handlers.TryRemove(MessageMethod.Handshake); - - Assert.False(wasRemoved); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestIdGeneratorTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestIdGeneratorTests.cs deleted file mode 100644 index 7b0e071ed0b..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/RequestIdGeneratorTests.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class RequestIdGeneratorTests - { - [Fact] - public void GenerateUniqueId() - { - const int iterations = 10; - - var ids = new HashSet<string>(); - var generator = new RequestIdGenerator(); - - for (var i = 0; i < iterations; ++i) - { - ids.Add(generator.GenerateUniqueId()); - } - - Assert.Equal(iterations, ids.Count); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/SenderTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/SenderTests.cs deleted file mode 100644 index dfe5e41a644..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/SenderTests.cs +++ /dev/null @@ -1,246 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class SenderTests - { - private readonly Message _message = new Message(requestId: "a", type: MessageType.Request, method: MessageMethod.None); - - [Fact] - public void Constructor_ThrowsForNull() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new Sender(writer: null)); - - Assert.Equal("writer", exception.ParamName); - } - - [Fact] - public void Constructor_AllowsTextWriterNull() - { - new Sender(TextWriter.Null); - } - - [Fact] - public void Dispose_ClosesUnderlyingStream() - { - using (var stream = new MemoryStream()) - using (var writer = new StreamWriter(stream)) - { - Assert.True(stream.CanSeek); - Assert.True(stream.CanRead); - Assert.True(stream.CanWrite); - - var sender = new Sender(writer); - - sender.Dispose(); - - Assert.False(stream.CanSeek); - Assert.False(stream.CanRead); - Assert.False(stream.CanWrite); - } - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var sender = new Sender(TextWriter.Null)) - { - sender.Dispose(); - sender.Dispose(); - } - } - - [Fact] - public void Connect_ThrowsIfDisposed() - { - var sender = new Sender(TextWriter.Null); - - sender.Dispose(); - - var exception = Assert.Throws<ObjectDisposedException>(() => sender.Connect()); - - Assert.Equal(nameof(Sender), exception.ObjectName); - } - - [Fact] - public void Connect_ThrowsIfClosed() - { - using (var sender = new Sender(TextWriter.Null)) - { - sender.Close(); - - Assert.Throws<InvalidOperationException>(() => sender.Connect()); - } - } - - [Fact] - public void Connect_ThrowsIfAlreadyConnected() - { - using (var sender = new Sender(TextWriter.Null)) - { - sender.Connect(); - - Assert.Throws<InvalidOperationException>(() => sender.Connect()); - } - } - - [Fact] - public async Task SendAsync_ThrowsForNull() - { - using (var sender = new Sender(TextWriter.Null)) - { - sender.Connect(); - - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => sender.SendAsync(message: null, cancellationToken: CancellationToken.None)); - - Assert.Equal("message", exception.ParamName); - } - } - - [Fact] - public async Task SendAsync_ThrowsIfDisposed() - { - var sender = new Sender(TextWriter.Null); - - sender.Dispose(); - - var exception = await Assert.ThrowsAsync<ObjectDisposedException>( - () => sender.SendAsync(_message, CancellationToken.None)); - - Assert.Equal(nameof(Sender), exception.ObjectName); - } - - [Fact] - public async Task SendAsync_ThrowsIfCancelled() - { - using (var sender = new Sender(TextWriter.Null)) - { - sender.Connect(); - - await Assert.ThrowsAsync<OperationCanceledException>( - () => sender.SendAsync(_message, new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task SendAsync_ThrowsForDisposedWriter() - { - using (var writer = new StringWriter()) - { - writer.Dispose(); - - using (var sender = new Sender(writer)) - { - sender.Connect(); - - await Assert.ThrowsAsync<ObjectDisposedException>( - () => sender.SendAsync(_message, CancellationToken.None)); - } - } - } - - [Fact] - public async Task SendAsync_ThrowsIfNotConnected() - { - using (var sender = new Sender(TextWriter.Null)) - { - await Assert.ThrowsAsync<InvalidOperationException>( - () => sender.SendAsync(_message, CancellationToken.None)); - } - } - - [Fact] - public async Task SendAsync_NoOpsIfClosed() - { - using (var writer = new StringWriter()) - using (var sender = new Sender(writer)) - { - sender.Connect(); - sender.Close(); - - await sender.SendAsync(_message, CancellationToken.None); - - var actualResult = writer.ToString(); - - Assert.Equal(string.Empty, actualResult); - } - } - - [Fact] - public async Task SendAsync_WritesMessageToWriter() - { - using (var writer = new StringWriter()) - using (var sender = new Sender(writer)) - { - sender.Connect(); - - await sender.SendAsync(_message, CancellationToken.None); - - var actualResult = writer.ToString(); - - Assert.Equal($"{{\"RequestId\":\"a\",\"Type\":\"Request\",\"Method\":\"None\"}}{Environment.NewLine}", actualResult); - } - } - - [Fact] - public void Close_DoesNotThrowIfDisposed() - { - using (var writer = new StringWriter()) - { - var sender = new Sender(TextWriter.Null); - - sender.Dispose(); - - sender.Close(); - } - } - - [Fact] - public void Close_IsIdempotent() - { - using (var sender = new Sender(TextWriter.Null)) - { - sender.Connect(); - - sender.Close(); - sender.Close(); - } - } - - [Fact] - public void Close_CanBeCalledWithoutConnectAsync() - { - using (var sender = new Sender(TextWriter.Null)) - { - sender.Close(); - } - } - - [Fact] - public async Task Close_DoesNotCloseUnderlyingStream() - { - using (var stream = new MemoryStream()) - using (var writer = new StreamWriter(stream)) - using (var sender = new Sender(writer)) - { - sender.Connect(); - await sender.SendAsync(_message, CancellationToken.None); - - sender.Close(); - - Assert.True(stream.CanSeek); - Assert.True(stream.CanRead); - Assert.True(stream.CanWrite); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/StandardInputReceiverTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/StandardInputReceiverTests.cs deleted file mode 100644 index c26b2d25610..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/StandardInputReceiverTests.cs +++ /dev/null @@ -1,438 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Threading; -using Newtonsoft.Json; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class StandardInputReceiverTests - { - [Fact] - public void Constructor_ThrowsForNullReader() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new StandardInputReceiver( - reader: null)); - - Assert.Equal("reader", exception.ParamName); - } - - [Fact] - public void Constructor_AllowsTextReaderNull() - { - using (new StandardInputReceiver(TextReader.Null)) - { - } - } - - [Fact] - public void Dispose_ClosesUnderlyingStream() - { - using (var stream = new MemoryStream()) - using (var reader = new StreamReader(stream)) - { - Assert.True(stream.CanSeek); - Assert.True(stream.CanRead); - Assert.True(stream.CanWrite); - - var receiver = new StandardInputReceiver(reader); - - receiver.Dispose(); - - Assert.False(stream.CanSeek); - Assert.False(stream.CanRead); - Assert.False(stream.CanWrite); - } - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var receiver = new StandardInputReceiver(TextReader.Null)) - { - receiver.Dispose(); - receiver.Dispose(); - } - } - - [Fact] - public void Connect_ThrowsIfDisposed() - { - var receiver = new StandardInputReceiver(TextReader.Null); - - receiver.Dispose(); - - var exception = Assert.Throws<ObjectDisposedException>(() => receiver.Connect()); - - Assert.Equal(nameof(StandardInputReceiver), exception.ObjectName); - } - - [Fact] - public void Connect_ThrowsIfClosed() - { - using (var receiver = new StandardInputReceiver(TextReader.Null)) - { - receiver.Close(); - - Assert.Throws<InvalidOperationException>(() => receiver.Connect()); - } - } - - [Fact] - public void Connect_ThrowsIfAlreadyConnected() - { - using (var receiver = new StandardInputReceiver(TextReader.Null)) - { - receiver.Connect(); - - Assert.Throws<InvalidOperationException>(() => receiver.Connect()); - } - } - - [Fact] - public void MessageReceived_RaisedForSingleMessageWithNonBlockingStream() - { - var json = "{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":\"None\"}"; - var requestId = "a"; - var type = MessageType.Response; - var method = MessageMethod.None; - - using (var receivedEvent = new ManualResetEventSlim(initialState: false)) - using (var reader = new StringReader(json)) - using (var receiver = new StandardInputReceiver(reader)) - { - Message message = null; - - receiver.MessageReceived += (object sender, MessageEventArgs e) => - { - message = e.Message; - - receivedEvent.Set(); - }; - - receiver.Connect(); - - receivedEvent.Wait(); - - Assert.Equal(requestId, message.RequestId); - Assert.Equal(type, message.Type); - Assert.Equal(method, message.Method); - Assert.Null(message.Payload); - } - } - - [Theory] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":\"None\"}\r\n", "a", MessageType.Response, MessageMethod.None, null)] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":\"None\",\"Payload\":null}\r\n", "a", MessageType.Response, MessageMethod.None, null)] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":\"None\",\"Payload\":{\"d\":\"e\"}}\r\n", "a", MessageType.Response, MessageMethod.None, "{\"d\":\"e\"}")] - public void MessageReceived_RaisedForSingleMessageWithBlockingStream(string json, string requestId, MessageType type, MessageMethod method, string payload) - { - using (var receivedEvent = new ManualResetEventSlim(initialState: false)) - using (var cancellationTokenSource = new CancellationTokenSource()) - using (var stream = new MemoryStream()) - using (var readWriteSemaphore = new SemaphoreSlim(initialCount: 1, maxCount: 1)) - using (var dataWrittenEvent = new ManualResetEventSlim(initialState: false)) - using (var outboundStream = new SimulatedWriteOnlyFileStream(stream, readWriteSemaphore, dataWrittenEvent, cancellationTokenSource.Token)) - using (var inboundStream = new SimulatedReadOnlyFileStream(stream, readWriteSemaphore, dataWrittenEvent, cancellationTokenSource.Token)) - using (var reader = new SimulatedStreamReader(inboundStream)) - using (var receiver = new StandardInputReceiver(reader)) - { - Message message = null; - - receiver.MessageReceived += (object sender, MessageEventArgs e) => - { - message = e.Message; - - receivedEvent.Set(); - }; - - var bytes = Encoding.UTF8.GetBytes(json); - - outboundStream.Write(bytes, offset: 0, count: bytes.Length); - - receiver.Connect(); - - receivedEvent.Wait(); - - Assert.Equal(requestId, message.RequestId); - Assert.Equal(type, message.Type); - Assert.Equal(method, message.Method); - Assert.Equal(payload, message.Payload?.ToString(Formatting.None)); - } - } - - [Fact] - public void MessageReceived_RaisedForSingleMessageInChunksWithBlockingStream() - { - var json = "{\"RequestId\":\"a\",\"Type\":\"Progress\",\"Method\":\"None\",\"Payload\":{\"d\":\"e\"}}\r\n"; - var requestId = "a"; - var type = MessageType.Progress; - var method = MessageMethod.None; - var payload = "{\"d\":\"e\"}"; - - using (var receivedEvent = new ManualResetEventSlim(initialState: false)) - using (var cancellationTokenSource = new CancellationTokenSource()) - using (var stream = new MemoryStream()) - using (var readWriteSemaphore = new SemaphoreSlim(initialCount: 1, maxCount: 1)) - using (var dataWrittenEvent = new ManualResetEventSlim(initialState: false)) - using (var outboundStream = new SimulatedWriteOnlyFileStream(stream, readWriteSemaphore, dataWrittenEvent, cancellationTokenSource.Token)) - using (var inboundStream = new SimulatedReadOnlyFileStream(stream, readWriteSemaphore, dataWrittenEvent, cancellationTokenSource.Token)) - using (var reader = new SimulatedStreamReader(inboundStream)) - using (var receiver = new StandardInputReceiver(reader)) - { - Message message = null; - - receiver.MessageReceived += (object sender, MessageEventArgs e) => - { - message = e.Message; - - receivedEvent.Set(); - }; - - var bytes = Encoding.UTF8.GetBytes(json); - - for (var offset = 0; offset < bytes.Length; offset += 10) - { - var count = Math.Min(bytes.Length - offset, 10); - - outboundStream.Write(bytes, offset, count); - } - - receiver.Connect(); - - receivedEvent.Wait(); - - Assert.Equal(requestId, message.RequestId); - Assert.Equal(type, message.Type); - Assert.Equal(method, message.Method); - Assert.Equal(payload, message.Payload.ToString(Formatting.None)); - } - } - - [Fact] - public void MessageReceived_RaisedForMultipleMessagesWithNonBlockingStream() - { - var json = "{\"RequestId\":\"de08f561-50c1-4816-adc3-73d2c283d8cf\",\"Type\":\"Request\",\"Method\":\"Handshake\",\"Payload\":{\"ProtocolVersion\":\"3.0.0\",\"MinimumProtocolVersion\":\"1.0.0\"}}\r\n{\"RequestId\":\"e2db1e2d-0282-45c4-9004-b096e221230d\",\"Type\":\"Response\",\"Method\":\"Handshake\",\"Payload\":{\"ResponseCode\":0,\"ProtocolVersion\":\"2.0.0\"}}\r\n"; - - using (var receivedEvent = new ManualResetEventSlim(initialState: false)) - using (var reader = new StringReader(json)) - using (var receiver = new StandardInputReceiver(reader)) - { - var messages = new List<Message>(); - - receiver.MessageReceived += (object sender, MessageEventArgs e) => - { - messages.Add(e.Message); - - if (messages.Count == 2) - { - receivedEvent.Set(); - } - }; - - receiver.Connect(); - - receivedEvent.Wait(); - } - } - - [Fact] - public void MessageReceived_RaisedForMultipleMessagesWithBlockingStream() - { - var json = "{\"RequestId\":\"de08f561-50c1-4816-adc3-73d2c283d8cf\",\"Type\":\"Request\",\"Method\":\"Handshake\",\"Payload\":{\"ProtocolVersion\":\"3.0.0\",\"MinimumProtocolVersion\":\"1.0.0\"}}\r\n{\"RequestId\":\"e2db1e2d-0282-45c4-9004-b096e221230d\",\"Type\":\"Response\",\"Method\":\"Handshake\",\"Payload\":{\"ResponseCode\":0,\"ProtocolVersion\":\"2.0.0\"}}\r\n"; - - using (var receivedEvent = new ManualResetEventSlim(initialState: false)) - using (var cancellationTokenSource = new CancellationTokenSource()) - using (var stream = new MemoryStream()) - using (var readWriteSemaphore = new SemaphoreSlim(initialCount: 1, maxCount: 1)) - using (var dataWrittenEvent = new ManualResetEventSlim(initialState: false)) - using (var outboundStream = new SimulatedWriteOnlyFileStream(stream, readWriteSemaphore, dataWrittenEvent, cancellationTokenSource.Token)) - using (var inboundStream = new SimulatedReadOnlyFileStream(stream, readWriteSemaphore, dataWrittenEvent, cancellationTokenSource.Token)) - using (var reader = new SimulatedStreamReader(inboundStream)) - using (var receiver = new StandardInputReceiver(reader)) - { - var messages = new List<Message>(); - - receiver.MessageReceived += (object sender, MessageEventArgs e) => - { - messages.Add(e.Message); - - if (messages.Count == 2) - { - receivedEvent.Set(); - } - }; - - var bytes = Encoding.UTF8.GetBytes(json); - - outboundStream.Write(bytes, offset: 0, count: bytes.Length); - - receiver.Connect(); - - receivedEvent.Wait(); - } - } - - [Fact] - public void Faulted_RaisedForParseError() - { - var invalidJson = "text\r\n"; - - using (var faultedEvent = new ManualResetEventSlim(initialState: false)) - using (var reader = new StringReader(invalidJson)) - using (var receiver = new StandardInputReceiver(reader)) - { - ProtocolErrorEventArgs args = null; - - receiver.Faulted += (object sender, ProtocolErrorEventArgs e) => - { - args = e; - - faultedEvent.Set(); - }; - - receiver.Connect(); - - faultedEvent.Wait(); - - Assert.NotNull(args); - Assert.IsType<ProtocolException>(args.Exception); - } - } - - [Theory] - [InlineData("1")] - [InlineData("[]")] - public void Faulted_RaisedForDeserializationOfInvalidJson(string invalidJson) - { - using (var faultedEvent = new ManualResetEventSlim(initialState: false)) - using (var reader = new StringReader(invalidJson)) - using (var receiver = new StandardInputReceiver(reader)) - { - ProtocolErrorEventArgs args = null; - - receiver.Faulted += (object sender, ProtocolErrorEventArgs e) => - { - args = e; - - faultedEvent.Set(); - }; - - receiver.Connect(); - - faultedEvent.Wait(); - - Assert.NotNull(args); - Assert.IsType<ProtocolException>(args.Exception); - } - } - - [Fact] - public void Faulted_RaisedForDeserializationError() - { - var json = "{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":\"None\",\"Payload\":\"{\\\"d\\\":\\\"e\\\"}\"}\r\n"; - - using (var faultedEvent = new ManualResetEventSlim(initialState: false)) - using (var reader = new StringReader(json)) - using (var receiver = new StandardInputReceiver(reader)) - { - ProtocolErrorEventArgs args = null; - - receiver.Faulted += (object sender, ProtocolErrorEventArgs e) => - { - args = e; - - faultedEvent.Set(); - }; - - receiver.Connect(); - - faultedEvent.Wait(); - - Assert.NotNull(args); - Assert.IsType<ProtocolException>(args.Exception); - } - } - - [Theory] - [InlineData("{\"Type\":\"Response\",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":null,\"Type\":\"Response\",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"\",\"Type\":\"Response\",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":null,\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"\",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\" \",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"abc\",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Response\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":null}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":\"\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":\"abc\"}\r\n")] - public void Faulted_RaisedForInvalidMessage(string json) - { - using (var faultedEvent = new ManualResetEventSlim(initialState: false)) - using (var reader = new StringReader(json)) - using (var receiver = new StandardInputReceiver(reader)) - { - ProtocolErrorEventArgs args = null; - - receiver.Faulted += (object sender, ProtocolErrorEventArgs e) => - { - args = e; - - faultedEvent.Set(); - }; - - receiver.Connect(); - - faultedEvent.Wait(); - - Assert.NotNull(args); - Assert.IsType<ProtocolException>(args.Exception); - } - } - - [Fact] - public void Close_IsIdempotent() - { - using (var receiver = new StandardInputReceiver(TextReader.Null)) - { - receiver.Connect(); - - receiver.Close(); - receiver.Close(); - } - } - - [Fact] - public void Close_CanBeCalledWithoutConnectAsync() - { - using (var receiver = new StandardInputReceiver(TextReader.Null)) - { - receiver.Close(); - } - } - - [Fact] - public void Close_DoesNotCloseUnderlyingStream() - { - using (var stream = new MemoryStream()) - using (var reader = new StreamReader(stream)) - using (var receiver = new StandardInputReceiver(reader)) - { - receiver.Connect(); - - receiver.Close(); - - Assert.True(stream.CanSeek); - Assert.True(stream.CanRead); - Assert.True(stream.CanWrite); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/StandardOutputReceiverTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/StandardOutputReceiverTests.cs deleted file mode 100644 index b20647d9131..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/StandardOutputReceiverTests.cs +++ /dev/null @@ -1,339 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using Moq; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class StandardOutputReceiverTests - { - [Fact] - public void Constructor_ThrowsForNullProcess() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new StandardOutputReceiver( - process: null)); - - Assert.Equal("process", exception.ParamName); - } - - [Fact] - public void Dispose_CancelsReading() - { - var process = new Mock<IPluginProcess>(MockBehavior.Strict); - - process.Setup(x => x.CancelRead()); - - using (var receiver = new StandardOutputReceiver(process.Object)) - { - } - - process.Verify(x => x.CancelRead(), Times.Once); - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var receiver = new StandardOutputReceiver(Mock.Of<IPluginProcess>())) - { - receiver.Dispose(); - receiver.Dispose(); - } - } - - [Fact] - public void Connect_ThrowsIfDisposed() - { - var receiver = new StandardOutputReceiver(Mock.Of<IPluginProcess>()); - - receiver.Dispose(); - - var exception = Assert.Throws<ObjectDisposedException>(() => receiver.Connect()); - - Assert.Equal(nameof(StandardOutputReceiver), exception.ObjectName); - } - - [Fact] - public void Connect_ThrowsIfClosed() - { - using (var receiver = new StandardOutputReceiver(Mock.Of<IPluginProcess>())) - { - receiver.Close(); - - Assert.Throws<InvalidOperationException>(() => receiver.Connect()); - } - } - - [Fact] - public void Connect_ThrowsIfAlreadyConnected() - { - using (var receiver = new StandardOutputReceiver(Mock.Of<IPluginProcess>())) - { - receiver.Connect(); - - Assert.Throws<InvalidOperationException>(() => receiver.Connect()); - } - } - - [Fact] - public void MessageReceived_RaisedForSingleMessage() - { - var json = "{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":\"None\"}"; - var requestId = "a"; - var type = MessageType.Response; - var method = MessageMethod.None; - var process = new Mock<IPluginProcess>(); - - process.Setup(x => x.BeginReadLine()) - .Callback(() => process.Raise(x => x.LineRead += null, new LineReadEventArgs(json))); - - using (var receivedEvent = new ManualResetEventSlim(initialState: false)) - using (var receiver = new StandardOutputReceiver(process.Object)) - { - MessageEventArgs args = null; - - receiver.MessageReceived += (object sender, MessageEventArgs e) => - { - args = e; - - receivedEvent.Set(); - }; - - receiver.Connect(); - - receivedEvent.Wait(); - - Assert.NotNull(args); - Assert.NotNull(args.Message); - Assert.Equal(requestId, args.Message.RequestId); - Assert.Equal(type, args.Message.Type); - Assert.Equal(method, args.Message.Method); - Assert.Null(args.Message.Payload); - } - } - - [Fact] - public void MessageReceived_HandlesNullAndEmptyString() - { - var json = "{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":\"None\"}"; - var requestId = "a"; - var type = MessageType.Response; - var method = MessageMethod.None; - var process = new Mock<IPluginProcess>(); - - process.Setup(x => x.BeginReadLine()) - .Callback(() => - { - // We can't directly verify handling of null and empty string except by - // passing a valid line after them and ensuring it gets processed correctly. - process.Raise(x => x.LineRead += null, new LineReadEventArgs(null)); - process.Raise(x => x.LineRead += null, new LineReadEventArgs("")); - process.Raise(x => x.LineRead += null, new LineReadEventArgs(json)); - }); - - using (var receivedEvent = new ManualResetEventSlim(initialState: false)) - using (var receiver = new StandardOutputReceiver(process.Object)) - { - MessageEventArgs args = null; - - receiver.MessageReceived += (object sender, MessageEventArgs e) => - { - args = e; - - receivedEvent.Set(); - }; - - receiver.Connect(); - - receivedEvent.Wait(); - - Assert.NotNull(args); - Assert.NotNull(args.Message); - Assert.Equal(requestId, args.Message.RequestId); - Assert.Equal(type, args.Message.Type); - Assert.Equal(method, args.Message.Method); - Assert.Null(args.Message.Payload); - } - } - - [Fact] - public void Faulted_RaisedForParseError() - { - var invalidJson = "text"; - var process = new Mock<IPluginProcess>(); - - process.Setup(x => x.BeginReadLine()) - .Callback(() => process.Raise(x => x.LineRead += null, new LineReadEventArgs(invalidJson))); - - using (var faultedEvent = new ManualResetEventSlim(initialState: false)) - using (var receiver = new StandardOutputReceiver(process.Object)) - { - ProtocolErrorEventArgs args = null; - - receiver.Faulted += (object sender, ProtocolErrorEventArgs e) => - { - args = e; - - faultedEvent.Set(); - }; - - receiver.Connect(); - - faultedEvent.Wait(); - - Assert.NotNull(args); - Assert.NotNull(args.Exception); - Assert.IsType<ProtocolException>(args.Exception); - Assert.Null(args.Message); - } - } - - [Theory] - [InlineData("1")] - [InlineData("[]")] - public void Faulted_RaisedForDeserializationOfInvalidJson(string invalidJson) - { - var process = new Mock<IPluginProcess>(); - - process.Setup(x => x.BeginReadLine()) - .Callback(() => process.Raise(x => x.LineRead += null, new LineReadEventArgs(invalidJson))); - - using (var faultedEvent = new ManualResetEventSlim(initialState: false)) - using (var receiver = new StandardOutputReceiver(process.Object)) - { - ProtocolErrorEventArgs args = null; - - receiver.Faulted += (object sender, ProtocolErrorEventArgs e) => - { - args = e; - - faultedEvent.Set(); - }; - - receiver.Connect(); - - faultedEvent.Wait(); - - Assert.NotNull(args); - Assert.NotNull(args.Exception); - Assert.IsType<ProtocolException>(args.Exception); - Assert.Null(args.Message); - } - } - - [Fact] - public void Faulted_RaisedForDeserializationError() - { - var json = "{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":\"None\",\"Payload\":\"{\\\"d\\\":\\\"e\\\"}\"}\r\n"; - - var process = new Mock<IPluginProcess>(); - - process.Setup(x => x.BeginReadLine()) - .Callback(() => process.Raise(x => x.LineRead += null, new LineReadEventArgs(json))); - - using (var faultedEvent = new ManualResetEventSlim(initialState: false)) - using (var receiver = new StandardOutputReceiver(process.Object)) - { - ProtocolErrorEventArgs args = null; - - receiver.Faulted += (object sender, ProtocolErrorEventArgs e) => - { - args = e; - - faultedEvent.Set(); - }; - - receiver.Connect(); - - faultedEvent.Wait(); - - Assert.NotNull(args); - Assert.NotNull(args.Exception); - Assert.IsType<ProtocolException>(args.Exception); - Assert.Null(args.Message); - } - } - - [Theory] - [InlineData("{\"Type\":\"Response\",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":null,\"Type\":\"Response\",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"\",\"Type\":\"Response\",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":null,\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"\",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\" \",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"abc\",\"Method\":\"None\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Response\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":null}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":\"\"}\r\n")] - [InlineData("{\"RequestId\":\"a\",\"Type\":\"Response\",\"Method\":\"abc\"}\r\n")] - public void Faulted_RaisedForInvalidMessage(string json) - { - var process = new Mock<IPluginProcess>(); - - process.Setup(x => x.BeginReadLine()) - .Callback(() => process.Raise(x => x.LineRead += null, new LineReadEventArgs(json))); - - using (var faultedEvent = new ManualResetEventSlim(initialState: false)) - using (var receiver = new StandardOutputReceiver(process.Object)) - { - ProtocolErrorEventArgs args = null; - - receiver.Faulted += (object sender, ProtocolErrorEventArgs e) => - { - args = e; - - faultedEvent.Set(); - }; - - receiver.Connect(); - - faultedEvent.Wait(); - - Assert.NotNull(args); - Assert.IsType<ProtocolException>(args.Exception); - } - } - - [Fact] - public void Close_IsIdempotent() - { - using (var receiver = new StandardOutputReceiver(Mock.Of<IPluginProcess>())) - { - receiver.Connect(); - - receiver.Close(); - receiver.Close(); - } - } - - [Fact] - public void Close_CanBeCalledWithoutConnectAsync() - { - using (var receiver = new StandardOutputReceiver(Mock.Of<IPluginProcess>())) - { - receiver.Close(); - } - } - - [Fact] - public void Close_CancelsReading() - { - var process = new Mock<IPluginProcess>(MockBehavior.Strict); - - process.Setup(x => x.BeginReadLine()); - process.Setup(x => x.CancelRead()); - - using (var receiver = new StandardOutputReceiver(process.Object)) - { - receiver.Connect(); - receiver.Close(); - } - - process.Verify(x => x.CancelRead(), Times.Once); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/TimeoutUtilitiesTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/TimeoutUtilitiesTests.cs deleted file mode 100644 index ea4f307a54c..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/TimeoutUtilitiesTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class TimeoutUtilitiesTests - { - [Fact] - public void IsValid_ReturnsFalseForTimeSpanZero() - { - Assert.False(TimeoutUtilities.IsValid(TimeSpan.Zero)); - } - - [Fact] - public void IsValid_ReturnsFalseForNegativeTimeSpan() - { - Assert.False(TimeoutUtilities.IsValid(TimeSpan.FromSeconds(-1))); - } - - [Fact] - public void IsValid_ReturnsFalseForTooLargeTimeSpan() - { - var milliseconds = int.MaxValue + 1L; - - Assert.False(TimeoutUtilities.IsValid(TimeSpan.FromMilliseconds(milliseconds))); - } - - [Fact] - public void IsValid_ReturnsTrueForMinimumAcceptableTimeSpan() - { - Assert.True(TimeoutUtilities.IsValid(ProtocolConstants.MinTimeout)); - } - - [Fact] - public void IsValid_ReturnsTrueForMaximumAcceptableTimeSpan() - { - Assert.True(TimeoutUtilities.IsValid(ProtocolConstants.MaxTimeout)); - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/WindowsEmbeddedSignatureVerifierTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/WindowsEmbeddedSignatureVerifierTests.cs deleted file mode 100644 index d8d68d30f84..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/WindowsEmbeddedSignatureVerifierTests.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using NuGet.Test.Utility; -using Xunit; - -namespace NuGet.Protocol.Plugins.Tests -{ - public class WindowsEmbeddedSignatureVerifierTests - { - private readonly WindowsEmbeddedSignatureVerifier _verifier; - - public WindowsEmbeddedSignatureVerifierTests() - { - _verifier = new WindowsEmbeddedSignatureVerifier(); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void IsValid_ThrowsForNullOrEmpty(string filePath) - { - var expectedMessage = $"Argument cannot be null or empty.{Environment.NewLine}Parameter name: filePath"; - var exception = Assert.Throws<ArgumentException>(() => _verifier.IsValid(filePath)); - - Assert.Equal(expectedMessage, exception.Message); - } - - [PlatformFact(Platform.Windows)] - public void IsValid_ReturnsTrueForValidFile() - { - var filePath = Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "System32", "wintrust.dll"); - - var actualResult = _verifier.IsValid(filePath); - - Assert.True(actualResult); - } - - [PlatformFact(Platform.Windows)] - public void IsValid_ReturnsFalseForNonExistentFilePath() - { - var filePath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); - var actualResult = _verifier.IsValid(filePath); - - Assert.False(actualResult); - } - - [PlatformFact(Platform.Windows)] - public void IsValid_ReturnsFalseForInvalidFile() - { - using (var testDirectory = TestDirectory.Create()) - { - // This is the build output from a default class library project. - // There is nothing special about it; any unsigned DLL would work just as well. - // This is a better test than an arbitrary file (e.g.: file.txt) because - // this is a portable executable (PE) file. Authenticode signatures are - // expected in PE files. - var fileName = "DefaultClassLibrary.dll"; - var resourceName = $"NuGet.Protocol.Tests.compiler.resources.{fileName}"; - var filePath = Path.Combine(testDirectory.Path, fileName); - - ResourceTestUtility.CopyResourceToFile(resourceName, GetType(), filePath); - - var actualResult = _verifier.IsValid(filePath); - - Assert.False(actualResult); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemotePackageArchiveDownloaderTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemotePackageArchiveDownloaderTests.cs deleted file mode 100644 index 77d8e9bc66a..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemotePackageArchiveDownloaderTests.cs +++ /dev/null @@ -1,403 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Common; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; -using NuGet.Test.Utility; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Tests -{ - public class RemotePackageArchiveDownloaderTests - { - private static readonly PackageIdentity _packageIdentity; - - static RemotePackageArchiveDownloaderTests() - { - _packageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); - } - - [Fact] - public void Constructor_ThrowsForNullFindPackageByIdResource() - { - using (var sourceCacheContext = new SourceCacheContext()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => new RemotePackageArchiveDownloader( - resource: null, - packageIdentity: _packageIdentity, - cacheContext: sourceCacheContext, - logger: NullLogger.Instance)); - - Assert.Equal("resource", exception.ParamName); - } - } - - [Fact] - public void Constructor_ThrowsForNullPackageIdentity() - { - using (var sourceCacheContext = new SourceCacheContext()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => new RemotePackageArchiveDownloader( - Mock.Of<FindPackageByIdResource>(), - packageIdentity: null, - cacheContext: sourceCacheContext, - logger: NullLogger.Instance)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public void Constructor_ThrowsForNullSourceCacheContext() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new RemotePackageArchiveDownloader( - Mock.Of<FindPackageByIdResource>(), - _packageIdentity, - cacheContext: null, - logger: NullLogger.Instance)); - - Assert.Equal("cacheContext", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullLogger() - { - using (var sourceCacheContext = new SourceCacheContext()) - { - var exception = Assert.Throws<ArgumentNullException>( - () => new RemotePackageArchiveDownloader( - Mock.Of<FindPackageByIdResource>(), - _packageIdentity, - sourceCacheContext, - logger: null)); - - Assert.Equal("logger", exception.ParamName); - } - - } - - [Fact] - public async Task Constructor_InitializesProperties() - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - test.Resource.Setup(x => x.CopyNupkgToStreamAsync( - It.IsNotNull<string>(), - It.IsNotNull<NuGetVersion>(), - It.IsNotNull<Stream>(), - It.IsNotNull<SourceCacheContext>(), - It.IsNotNull<ILogger>(), - It.IsAny<CancellationToken>())) - .Callback<string, NuGetVersion, Stream, SourceCacheContext, ILogger, CancellationToken>( - (id, version, stream, cacheContext, logger, cancellationToken) => - { - var remoteDirectoryPath = Path.Combine(test.TestDirectory.Path, "remote"); - - Directory.CreateDirectory(remoteDirectoryPath); - - var packageContext = new SimpleTestPackageContext() - { - Id = test.PackageIdentity.Id, - Version = test.PackageIdentity.Version.ToNormalizedString() - }; - - packageContext.AddFile($"lib/net45/{test.PackageIdentity.Id}.dll"); - - SimpleTestPackageUtility.CreatePackages(remoteDirectoryPath, packageContext); - - var sourcePackageFilePath = Path.Combine( - remoteDirectoryPath, - $"{test.PackageIdentity.Id}.{test.PackageIdentity.Version.ToNormalizedString()}.nupkg"); - - using (var remoteStream = File.OpenRead(sourcePackageFilePath)) - { - remoteStream.CopyTo(stream); - } - }) - .ReturnsAsync(true); - - var destinationFilePath = Path.Combine(test.TestDirectory.Path, "a"); - - await test.Downloader.CopyNupkgFileToAsync( - destinationFilePath, - CancellationToken.None); - - Assert.IsType<PackageArchiveReader>(test.Downloader.ContentReader); - Assert.IsType<PackageArchiveReader>(test.Downloader.CoreReader); - } - } - - [Fact] - public void Dispose_IsIdempotent() - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - test.Downloader.Dispose(); - test.Downloader.Dispose(); - } - } - - [Fact] - public void ContentReader_ThrowsIfCopyNupkgFileToAsyncNotCalledFirst() - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - Assert.Throws<InvalidOperationException>(() => test.Downloader.ContentReader); - } - } - - [Fact] - public void ContentReader_ThrowsIfDisposed() - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - test.Downloader.Dispose(); - - var exception = Assert.Throws<ObjectDisposedException>(() => test.Downloader.ContentReader); - - Assert.Equal(nameof(RemotePackageArchiveDownloader), exception.ObjectName); - } - } - - [Fact] - public void CoreReader_ThrowsIfCopyNupkgFileToAsyncNotCalledFirst() - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - Assert.Throws<InvalidOperationException>(() => test.Downloader.CoreReader); - } - } - - [Fact] - public void CoreReader_ThrowsIfDisposed() - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - test.Downloader.Dispose(); - - var exception = Assert.Throws<ObjectDisposedException>(() => test.Downloader.CoreReader); - - Assert.Equal(nameof(RemotePackageArchiveDownloader), exception.ObjectName); - } - } - - [Fact] - public async Task CopyNupkgFileToAsync_ThrowsIfDisposed() - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - test.Downloader.Dispose(); - - var exception = await Assert.ThrowsAsync<ObjectDisposedException>( - () => test.Downloader.CopyNupkgFileToAsync( - destinationFilePath: "a", - cancellationToken: CancellationToken.None)); - - Assert.Equal(nameof(RemotePackageArchiveDownloader), exception.ObjectName); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task CopyNupkgFileToAsync_ThrowsForNullOrEmptyDestinationFilePath(string destinationFilePath) - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Downloader.CopyNupkgFileToAsync( - destinationFilePath, - CancellationToken.None)); - - Assert.Equal("destinationFilePath", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgFileToAsync_ThrowsIfCancelled() - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Downloader.CopyNupkgFileToAsync( - destinationFilePath: "a", - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public async Task CopyNupkgFileToAsync_ReturnsResultFromFindPackageByIdResource(bool expectedResult) - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - test.Resource.Setup(x => x.CopyNupkgToStreamAsync( - It.IsNotNull<string>(), - It.IsNotNull<NuGetVersion>(), - It.IsNotNull<Stream>(), - It.IsNotNull<SourceCacheContext>(), - It.IsNotNull<ILogger>(), - It.IsAny<CancellationToken>())) - .ReturnsAsync(expectedResult); - - var destinationFilePath = Path.Combine(test.TestDirectory.Path, "a"); - - var actualResult = await test.Downloader.CopyNupkgFileToAsync( - destinationFilePath, - CancellationToken.None); - - Assert.Equal(expectedResult, actualResult); - } - } - - [Fact] - public async Task GetPackageHashAsync_ThrowsIfDisposed() - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - test.Downloader.Dispose(); - - var exception = await Assert.ThrowsAsync<ObjectDisposedException>( - () => test.Downloader.GetPackageHashAsync( - hashAlgorithm: "SHA512", - cancellationToken: CancellationToken.None)); - - Assert.Equal(nameof(RemotePackageArchiveDownloader), exception.ObjectName); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetPackageHashAsync_ThrowsForNullOrEmptyHashAlgorithm(string hashAlgorithm) - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Downloader.GetPackageHashAsync( - hashAlgorithm, - CancellationToken.None)); - - Assert.Equal("hashAlgorithm", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageHashAsync_ThrowsIfCancelled() - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Downloader.GetPackageHashAsync( - hashAlgorithm: "a", - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetPackageHashAsync_ReturnsPackageHash() - { - using (var test = RemotePackageArchiveDownloaderTest.Create()) - { - var destinationFilePath = Path.Combine(test.TestDirectory.Path, "a"); - - test.Resource.Setup(x => x.CopyNupkgToStreamAsync( - It.IsNotNull<string>(), - It.IsNotNull<NuGetVersion>(), - It.IsNotNull<Stream>(), - It.IsNotNull<SourceCacheContext>(), - It.IsNotNull<ILogger>(), - It.IsAny<CancellationToken>())) - .ReturnsAsync(true); - - await test.Downloader.CopyNupkgFileToAsync( - destinationFilePath, - CancellationToken.None); - - var actualResult = await test.Downloader.GetPackageHashAsync( - hashAlgorithm: "SHA512", - cancellationToken: CancellationToken.None); - - Assert.Equal("z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXcg/SpIdNs6c5H0NE8XYXysP+DGNKHfuwvY7kxvUdBeoGlODJ6+SfaPg==", actualResult); - } - } - - private sealed class RemotePackageArchiveDownloaderTest : IDisposable - { - internal RemotePackageArchiveDownloader Downloader { get; } - internal PackageIdentity PackageIdentity { get; } - internal Mock<FindPackageByIdResource> Resource { get; } - internal SourceCacheContext SourceCacheContext { get; } - internal TestDirectory TestDirectory { get; } - - private RemotePackageArchiveDownloaderTest( - TestDirectory testDirectory, - PackageIdentity packageIdentity, - Mock<FindPackageByIdResource> resource, - SourceCacheContext sourceCacheContext, - RemotePackageArchiveDownloader downloader) - { - TestDirectory = testDirectory; - PackageIdentity = packageIdentity; - Resource = resource; - SourceCacheContext = sourceCacheContext; - Downloader = downloader; - } - - public void Dispose() - { - Downloader.Dispose(); - SourceCacheContext.Dispose(); - TestDirectory.Dispose(); - - GC.SuppressFinalize(this); - } - - internal static RemotePackageArchiveDownloaderTest Create() - { - var testDirectory = TestDirectory.Create(); - var sourceCacheContext = new SourceCacheContext(); - var packageContext = new SimpleTestPackageContext() - { - Id = _packageIdentity.Id, - Version = _packageIdentity.Version.ToNormalizedString() - }; - - packageContext.AddFile($"lib/net45/{_packageIdentity.Id}.dll"); - - SimpleTestPackageUtility.CreatePackages(testDirectory.Path, packageContext); - - var packageFilePath = Path.Combine( - testDirectory.Path, - $"{_packageIdentity.Id}.{_packageIdentity.Version.ToNormalizedString()}.nupkg"); - - var resource = new Mock<FindPackageByIdResource>(MockBehavior.Strict); - - var downloader = new RemotePackageArchiveDownloader( - resource.Object, - _packageIdentity, - sourceCacheContext, - NullLogger.Instance); - - return new RemotePackageArchiveDownloaderTest( - testDirectory, - _packageIdentity, - resource, - sourceCacheContext, - downloader); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteRepositories/HttpFileSystemBasedFindPackageByIdResourceTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteRepositories/HttpFileSystemBasedFindPackageByIdResourceTests.cs deleted file mode 100644 index b1ee2420058..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteRepositories/HttpFileSystemBasedFindPackageByIdResourceTests.cs +++ /dev/null @@ -1,663 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; -using NuGet.Test.Utility; -using NuGet.Versioning; -using Test.Utility; -using Xunit; - -namespace NuGet.Protocol.Tests -{ - public class HttpFileSystemBasedFindPackageByIdResourceTests - { - [Fact] - public void Constructor_ThrowsForNullBaseUris() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new HttpFileSystemBasedFindPackageByIdResource( - baseUris: null, - httpSource: CreateDummyHttpSource())); - - Assert.Equal("baseUris", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForEmptyBaseUris() - { - var exception = Assert.Throws<ArgumentException>( - () => new HttpFileSystemBasedFindPackageByIdResource( - new List<Uri>(), - CreateDummyHttpSource())); - - Assert.Equal("baseUris", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullHttpSource() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new HttpFileSystemBasedFindPackageByIdResource( - new List<Uri>() { new Uri("https://unit.test") }, - httpSource: null)); - - Assert.Equal("httpSource", exception.ParamName); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetAllVersionsAsync_ThrowsForNullOrEmptyId(string id) - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.GetAllVersionsAsync( - id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowsForNullSourceCacheContext() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetAllVersionsAsync( - id: "a", - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowsForNullLogger() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetAllVersionsAsync( - id: "a", - cacheContext: test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowIfCancelled() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetAllVersionsAsync( - id: "a", - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ReturnsEmptyEnumerableIfPackageIdNotFound() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var versions = await test.Resource.GetAllVersionsAsync( - id: "a", - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.Empty(versions); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ReturnsAllVersions() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var versions = await test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Equal(new[] - { - NuGetVersion.Parse("0.1.0"), - NuGetVersion.Parse("0.2.0"), - NuGetVersion.Parse("0.3.0"), - NuGetVersion.Parse("0.4.0"), - NuGetVersion.Parse("0.5.0"), - NuGetVersion.Parse("0.6.0"), - NuGetVersion.Parse("0.7.0"), - NuGetVersion.Parse("0.8.0"), - NuGetVersion.Parse("0.9.0"), - NuGetVersion.Parse("0.10.0"), - NuGetVersion.Parse("0.11.0"), - NuGetVersion.Parse("0.12.0"), - NuGetVersion.Parse("1.0.0"), - NuGetVersion.Parse("1.1.0"), - NuGetVersion.Parse("1.1.1"), - NuGetVersion.Parse("1.2.0"), - NuGetVersion.Parse("1.3.0"), - NuGetVersion.Parse("1.4.0"), - NuGetVersion.Parse("1.4.0.1-rc") - }, versions); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetDependencyInfoAsync_ThrowsForNullOrEmptyId(string id) - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.GetDependencyInfoAsync( - id, - NuGetVersion.Parse("1.0.0"), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullVersion() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - id: "a", - version: null, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("version", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullSourceCacheContext() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullLogger() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowIfCancelled() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetDependencyInfoAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ReturnsNullIfPackageNotFound() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var dependencyInfo = await test.Resource.GetDependencyInfoAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.Null(dependencyInfo); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_GetsOriginalIdentity() - { - // Arrange - using (var workingDir = TestDirectory.Create()) - { - var source = "http://unit.test/v3-with-flat-container/index.json"; - var package = SimpleTestPackageUtility.CreateFullPackage(workingDir, "DeepEqual", "1.4.0.1-rc"); - var packageBytes = File.ReadAllBytes(package.FullName); - - var responses = new Dictionary<string, Func<HttpRequestMessage, Task<HttpResponseMessage>>> - { - { - source, - _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent(JsonData.IndexWithFlatContainer) - }) - }, - { - "https://api.nuget.org/v3-flatcontainer/deepequal/index.json", - _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent(JsonData.DeepEqualFlatContainerIndex) - }) - }, - { - "https://api.nuget.org/v3-flatcontainer/deepequal/1.4.0.1-rc/deepequal.1.4.0.1-rc.nupkg", - _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new ByteArrayContent(packageBytes) - }) - } - }; - - var repo = StaticHttpHandler.CreateSource(source, Repository.Provider.GetCoreV3(), responses); - var logger = new TestLogger(); - - using (var cacheContext = new SourceCacheContext()) - { - var resource = await repo.GetResourceAsync<FindPackageByIdResource>(); - - // Act - var info = await resource.GetDependencyInfoAsync( - "DEEPEQUAL", - new NuGetVersion("1.4.0.1-RC"), - cacheContext, - logger, - CancellationToken.None); - - // Assert - Assert.IsType<HttpFileSystemBasedFindPackageByIdResource>(resource); - Assert.Equal("DeepEqual", info.PackageIdentity.Id); - Assert.Equal("1.4.0.1-rc", info.PackageIdentity.Version.ToNormalizedString()); - } - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task CopyNupkgToStreamAsync_ThrowsForNullId(string id) - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.CopyNupkgToStreamAsync( - id, - NuGetVersion.Parse("1.0.0"), - Stream.Null, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullVersion() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: null, - destination: Stream.Null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("version", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullDestination() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("destination", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullSourceCacheContext() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: Stream.Null, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullLogger() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: Stream.Null, - cacheContext: test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsIfCancelled() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: Stream.Null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ReturnsFalseIfNotCopied() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - using (var stream = new MemoryStream()) - { - var wasCopied = await test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: stream, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.False(wasCopied); - Assert.Equal(0, stream.Length); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ReturnsTrueIfCopied() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - using (var stream = new MemoryStream()) - { - var wasCopied = await test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - stream, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.True(wasCopied); - Assert.Equal(test.Package.Length, stream.Length); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullPackageIdentity() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - packageIdentity: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullSourceCacheContext() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullLogger() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsIfCancelled() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsNullIfPackageNotFound() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var downloader = await test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Null(downloader); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsPackageDownloaderIfPackageFound() - { - using (var test = HttpFileSystemBasedFindPackageByIdResourceTest.Create()) - { - var downloader = await test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.IsType<RemotePackageArchiveDownloader>(downloader); - } - } - - private static HttpSource CreateDummyHttpSource() - { - var packageSource = new PackageSource("https://unit.test"); - Func<Task<HttpHandlerResource>> messageHandlerFactory = - () => Task.FromResult<HttpHandlerResource>(null); - - return new HttpSource(packageSource, messageHandlerFactory, Mock.Of<IThrottle>()); - } - - private sealed class HttpFileSystemBasedFindPackageByIdResourceTest : IDisposable - { - private readonly TestHttpSource _httpSource; - - internal FileInfo Package { get; } - internal PackageIdentity PackageIdentity { get; } - internal HttpFileSystemBasedFindPackageByIdResource Resource { get; } - internal SourceCacheContext SourceCacheContext { get; } - internal TestDirectory TestDirectory { get; } - - private HttpFileSystemBasedFindPackageByIdResourceTest( - HttpFileSystemBasedFindPackageByIdResource resource, - FileInfo package, - PackageIdentity packageIdentity, - SourceCacheContext sourceCacheContext, - TestHttpSource httpSource, - TestDirectory testDirectory) - { - Resource = resource; - Package = package; - PackageIdentity = packageIdentity; - SourceCacheContext = sourceCacheContext; - _httpSource = httpSource; - TestDirectory = testDirectory; - } - - public void Dispose() - { - SourceCacheContext.Dispose(); - _httpSource.Dispose(); - TestDirectory.Dispose(); - - GC.SuppressFinalize(this); - } - - internal static HttpFileSystemBasedFindPackageByIdResourceTest Create() - { - var packageIdentity = new PackageIdentity(id: "DeepEqual", version: NuGetVersion.Parse("1.4.0")); - var testDirectory = TestDirectory.Create(); - var packageSource = new PackageSource("http://unit.test/v3-flatcontainer"); - var package = SimpleTestPackageUtility.CreateFullPackage( - testDirectory.Path, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); - var packageBytes = File.ReadAllBytes(package.FullName); - - var responses = new Dictionary<string, Func<HttpRequestMessage, Task<HttpResponseMessage>>> - { - { - $"{packageSource.Source}/deepequal/index.json", - request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent(JsonData.DeepEqualFlatContainerIndex) - }) - }, - { - $"{packageSource.Source}/deepequal/1.4.0/deepequal.1.4.0.nupkg", - _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new ByteArrayContent(packageBytes) - }) - }, - { - $"{packageSource.Source}/a/index.json", - request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound)) - } - }; - - var baseUris = new List<Uri>() { packageSource.SourceUri }; - var httpSource = new TestHttpSource(packageSource, responses); - var resource = new HttpFileSystemBasedFindPackageByIdResource( - baseUris, - httpSource); - - return new HttpFileSystemBasedFindPackageByIdResourceTest( - resource, - package, - packageIdentity, - new SourceCacheContext(), - httpSource, - testDirectory); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteRepositories/RemoteV2FindPackageByIdResourceTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteRepositories/RemoteV2FindPackageByIdResourceTests.cs deleted file mode 100644 index 0f925b6d914..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteRepositories/RemoteV2FindPackageByIdResourceTests.cs +++ /dev/null @@ -1,800 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; -using NuGet.Test.Utility; -using NuGet.Versioning; -using Test.Utility; -using Xunit; - -namespace NuGet.Protocol.Tests -{ - public class RemoteV2FindPackageByIdResourceTests - { - [Fact] - public void Constructor_ThrowsForNullPackageSource() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new RemoteV2FindPackageByIdResource( - packageSource: null, - httpSource: CreateDummyHttpSource())); - - Assert.Equal("packageSource", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullHttpSource() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new RemoteV2FindPackageByIdResource( - new PackageSource("https://unit.test"), - httpSource: null)); - - Assert.Equal("httpSource", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperty() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - Assert.Same(test.PackageSource, test.Resource.PackageSource); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetAllVersionsAsync_ThrowsForNullOrEmptyId(string id) - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.GetAllVersionsAsync( - id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowsForNullSourceCacheContext() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetAllVersionsAsync( - id: "a", - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowsForNullLogger() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetAllVersionsAsync( - id: "a", - cacheContext: test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowIfCancelled() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetAllVersionsAsync( - id: "a", - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ReturnsEmptyEnumerableIfPackageIdNotFound() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var versions = await test.Resource.GetAllVersionsAsync( - id: "a", - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.Empty(versions); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ReturnsAllVersions() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var versions = await test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Equal(new[] - { - NuGetVersion.Parse("2.0.0-alpha-build1624"), - NuGetVersion.Parse("2.2.0-beta1-build3239"), - NuGetVersion.Parse("2.1.0"), - NuGetVersion.Parse("1.7.0.1540"), - NuGetVersion.Parse("1.8.0.1545"), - NuGetVersion.Parse("1.8.0.1549"), - NuGetVersion.Parse("2.0.0-alpha-build1611"), - NuGetVersion.Parse("2.0.0-alpha-build1631"), - NuGetVersion.Parse("2.0.0-alpha-build1644"), - NuGetVersion.Parse("2.0.0-alpha-build1648"), - NuGetVersion.Parse("2.0.0-alpha-build1650"), - NuGetVersion.Parse("2.0.0-alpha-build1654"), - NuGetVersion.Parse("2.0.0-alpha-build1657"), - NuGetVersion.Parse("2.0.0-alpha-build2503"), - NuGetVersion.Parse("1.9.1"), - NuGetVersion.Parse("2.0.0-alpha-build2510"), - NuGetVersion.Parse("2.0.0-alpha-build2521"), - NuGetVersion.Parse("2.0.0-alpha-build2529"), - NuGetVersion.Parse("2.0.0-alpha-build2533"), - NuGetVersion.Parse("2.0.0-alpha-build2548"), - NuGetVersion.Parse("2.0.0-alpha-build2552"), - NuGetVersion.Parse("2.0.0-alpha-build2562"), - NuGetVersion.Parse("2.0.0-alpha-build2569"), - NuGetVersion.Parse("2.0.0-alpha-build2576"), - NuGetVersion.Parse("2.0.0-alpha-build2595"), - NuGetVersion.Parse("2.0.0-alpha-build2606"), - NuGetVersion.Parse("2.0.0-beta-build2616"), - NuGetVersion.Parse("2.0.0-beta-build2650"), - NuGetVersion.Parse("2.0.0-beta-build2700"), - NuGetVersion.Parse("2.0.0-beta4-build2738"), - NuGetVersion.Parse("2.0.0-beta5-build2785"), - NuGetVersion.Parse("2.0.0-rc1-build2826"), - NuGetVersion.Parse("2.0.0-rc2-build2857"), - NuGetVersion.Parse("2.0.0-rc3-build2880"), - NuGetVersion.Parse("1.9.0.1566"), - NuGetVersion.Parse("1.9.2"), - NuGetVersion.Parse("2.0.0-rc4-build2924"), - NuGetVersion.Parse("2.1.0-beta1-build2945"), - NuGetVersion.Parse("2.1.0-beta2-build2981"), - NuGetVersion.Parse("2.1.0-beta3-build3029"), - NuGetVersion.Parse("2.1.0-beta4-build3109"), - NuGetVersion.Parse("2.1.0-rc1-build3168"), - NuGetVersion.Parse("2.0.0"), - NuGetVersion.Parse("2.1.0-rc2-build3176") - }, versions); - } - } - - [Fact] - public async Task GetAllVersionsAsync_NoErrorsOnNoContent() - { - // Arrange - var serviceAddress = TestUtility.CreateServiceAddress(); - - var responses = new Dictionary<string, string>(); - responses.Add(serviceAddress + "FindPackagesById()?id='a'", "204"); - - var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses); - var logger = new TestLogger(); - - using (var cacheContext = new SourceCacheContext()) - { - var resource = await repo.GetResourceAsync<FindPackageByIdResource>(); - - // Act - var versions = await resource.GetAllVersionsAsync( - "a", - cacheContext, - logger, - CancellationToken.None); - - // Assert - // Verify no items returned, and no exceptions were thrown above - Assert.Equal(0, versions.Count()); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetDependencyInfoAsync_ThrowsForNullOrEmptyId(string id) - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.GetDependencyInfoAsync( - id, - NuGetVersion.Parse("1.0.0"), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullVersion() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - id: "a", - version: null, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("version", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullSourceCacheContext() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullLogger() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowIfCancelled() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetDependencyInfoAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ReturnsNullIfPackageNotFound() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var dependencyInfo = await test.Resource.GetDependencyInfoAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.Null(dependencyInfo); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_GetOriginalIdentity_IdInResponse() - { - // Arrange - using (var workingDir = TestDirectory.Create()) - { - var serviceAddress = TestUtility.CreateServiceAddress(); - var package = SimpleTestPackageUtility.CreateFullPackage(workingDir, "xunit", "2.2.0-beta1-build3239"); - var packageBytes = File.ReadAllBytes(package.FullName); - - var responses = new Dictionary<string, Func<HttpRequestMessage, Task<HttpResponseMessage>>> - { - { - serviceAddress, - _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent(string.Empty) - }) - }, - { - serviceAddress + "FindPackagesById()?id='XUNIT'", - _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent(TestUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml", GetType())) - }) - }, - { - "https://www.nuget.org/api/v2/package/xunit/2.2.0-beta1-build3239", - _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new ByteArrayContent(packageBytes) - }) - } - }; - - var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses); - var logger = new TestLogger(); - - using (var cacheContext = new SourceCacheContext()) - { - var resource = await repo.GetResourceAsync<FindPackageByIdResource>(); - - // Act - var info = await resource.GetDependencyInfoAsync( - "XUNIT", - new NuGetVersion("2.2.0-BETA1-build3239"), - cacheContext, - logger, - CancellationToken.None); - - // Assert - Assert.IsType<RemoteV2FindPackageByIdResource>(resource); - Assert.Equal("xunit", info.PackageIdentity.Id); - Assert.Equal("2.2.0-beta1-build3239", info.PackageIdentity.Version.ToNormalizedString()); - } - } - } - - [Fact] - public async Task GetDependencyInfoAsync_GetOriginalIdentity_IdNotInResponse() - { - // Arrange - using (var workingDir = TestDirectory.Create()) - { - var serviceAddress = TestUtility.CreateServiceAddress(); - var package = SimpleTestPackageUtility.CreateFullPackage(workingDir, "WindowsAzure.Storage", "6.2.2-preview"); - var packageBytes = File.ReadAllBytes(package.FullName); - - var responses = new Dictionary<string, Func<HttpRequestMessage, Task<HttpResponseMessage>>> - { - { - serviceAddress, - _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent(string.Empty) - }) - }, - { - serviceAddress + "FindPackagesById()?id='WINDOWSAZURE.STORAGE'", - _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent(TestUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.WindowsAzureStorageFindPackagesById.xml", GetType())) - }) - }, - { - "https://www.nuget.org/api/v2/package/WindowsAzure.Storage/6.2.2-preview", - _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new ByteArrayContent(packageBytes) - }) - } - }; - - var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses); - var logger = new TestLogger(); - - using (var cacheContext = new SourceCacheContext()) - { - var resource = await repo.GetResourceAsync<FindPackageByIdResource>(); - - // Act - var info = await resource.GetDependencyInfoAsync( - "WINDOWSAZURE.STORAGE", - new NuGetVersion("6.2.2-PREVIEW"), - cacheContext, - logger, - CancellationToken.None); - - // Assert - Assert.IsType<RemoteV2FindPackageByIdResource>(resource); - Assert.Equal("WindowsAzure.Storage", info.PackageIdentity.Id); - Assert.Equal("6.2.2-preview", info.PackageIdentity.Version.ToNormalizedString()); - } - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task CopyNupkgToStreamAsync_ThrowsForNullId(string id) - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.CopyNupkgToStreamAsync( - id, - NuGetVersion.Parse("1.0.0"), - Stream.Null, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullVersion() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: null, - destination: Stream.Null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("version", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullDestination() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("destination", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullSourceCacheContext() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: Stream.Null, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullLogger() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: Stream.Null, - cacheContext: test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsIfCancelled() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: Stream.Null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ReturnsFalseIfNotCopied() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - using (var stream = new MemoryStream()) - { - var wasCopied = await test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: stream, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.False(wasCopied); - Assert.Equal(0, stream.Length); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ReturnsTrueIfCopied() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - using (var stream = new MemoryStream()) - { - var wasCopied = await test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - stream, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.True(wasCopied); - Assert.Equal(test.Package.Length, stream.Length); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullPackageIdentity() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - packageIdentity: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullSourceCacheContext() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullLogger() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsIfCancelled() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsNullIfPackageNotFound() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var downloader = await test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Null(downloader); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsPackageDownloaderIfPackageFound() - { - using (var test = RemoteV2FindPackageByIdResourceTest.Create()) - { - var downloader = await test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.IsType<RemotePackageArchiveDownloader>(downloader); - } - } - - private static HttpSource CreateDummyHttpSource() - { - var packageSource = new PackageSource("https://unit.test"); - Func<Task<HttpHandlerResource>> messageHandlerFactory = - () => Task.FromResult<HttpHandlerResource>(null); - - return new HttpSource(packageSource, messageHandlerFactory, Mock.Of<IThrottle>()); - } - - private sealed class RemoteV2FindPackageByIdResourceTest : IDisposable - { - private readonly TestHttpSource _httpSource; - - internal FileInfo Package { get; } - internal PackageIdentity PackageIdentity { get; } - internal PackageSource PackageSource { get; } - internal RemoteV2FindPackageByIdResource Resource { get; } - internal SourceCacheContext SourceCacheContext { get; } - internal TestDirectory TestDirectory { get; } - - private RemoteV2FindPackageByIdResourceTest( - RemoteV2FindPackageByIdResource resource, - PackageSource packageSource, - FileInfo package, - PackageIdentity packageIdentity, - SourceCacheContext sourceCacheContext, - TestHttpSource httpSource, - TestDirectory testDirectory) - { - Resource = resource; - PackageSource = packageSource; - Package = package; - PackageIdentity = packageIdentity; - SourceCacheContext = sourceCacheContext; - _httpSource = httpSource; - TestDirectory = testDirectory; - } - - public void Dispose() - { - SourceCacheContext.Dispose(); - _httpSource.Dispose(); - TestDirectory.Dispose(); - - GC.SuppressFinalize(this); - } - - internal static RemoteV2FindPackageByIdResourceTest Create() - { - var serviceAddress = TestUtility.CreateServiceAddress(); - var packageIdentity = new PackageIdentity( - id: "xunit", - version: NuGetVersion.Parse("2.2.0-beta1-build3239")); - var testDirectory = TestDirectory.Create(); - var packageSource = new PackageSource(serviceAddress); - var package = SimpleTestPackageUtility.CreateFullPackage( - testDirectory.Path, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); - var packageBytes = File.ReadAllBytes(package.FullName); - - var responses = new Dictionary<string, Func<HttpRequestMessage, Task<HttpResponseMessage>>> - { - { - serviceAddress, - request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent(string.Empty) - }) - }, - { - serviceAddress + $"FindPackagesById()?id='{packageIdentity.Id}'", - request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent( - TestUtility.GetResource( - "NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml", - typeof(RemoteV2FindPackageByIdResourceTest))) - }) - }, - { - serviceAddress + $"FindPackagesById()?id='{packageIdentity.Id.ToUpper()}'", - request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent( - TestUtility.GetResource( - "NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml", - typeof(RemoteV2FindPackageByIdResourceTest))) - }) - }, - { - "https://www.nuget.org/api/v2/package/xunit/2.2.0-beta1-build3239", - request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new ByteArrayContent(packageBytes) - }) - }, - { - serviceAddress + $"FindPackagesById()?id='a'", - request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.NoContent)) - } - }; - - var httpSource = new TestHttpSource(packageSource, responses); - var resource = new RemoteV2FindPackageByIdResource( - packageSource, - httpSource); - - return new RemoteV2FindPackageByIdResourceTest( - resource, - packageSource, - package, - packageIdentity, - new SourceCacheContext(), - httpSource, - testDirectory); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteRepositories/RemoteV3FindPackageByIdResourceTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteRepositories/RemoteV3FindPackageByIdResourceTests.cs deleted file mode 100644 index b87304306aa..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteRepositories/RemoteV3FindPackageByIdResourceTests.cs +++ /dev/null @@ -1,727 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; -using NuGet.Test.Utility; -using NuGet.Versioning; -using Test.Utility; -using Xunit; - -namespace NuGet.Protocol.Tests -{ - public class RemoteV3FindPackageByIdResourceTests - { - [Fact] - public void Constructor_ThrowsForNullSourceRepository() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new RemoteV3FindPackageByIdResource( - sourceRepository: null, - httpSource: CreateDummyHttpSource())); - - Assert.Equal("sourceRepository", exception.ParamName); - } - - [Fact] - public void Constructor_ThrowsForNullHttpSource() - { - var exception = Assert.Throws<ArgumentNullException>( - () => new RemoteV3FindPackageByIdResource( - new SourceRepository( - new PackageSource("https://unit.test"), - Enumerable.Empty<INuGetResourceProvider>()), - httpSource: null)); - - Assert.Equal("httpSource", exception.ParamName); - } - - [Fact] - public void Constructor_InitializesProperty() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - Assert.Same(test.SourceRepository, test.Resource.SourceRepository); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetAllVersionsAsync_ThrowsForNullOrEmptyId(string id) - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.GetAllVersionsAsync( - id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowsForNullSourceCacheContext() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetAllVersionsAsync( - id: "a", - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowsForNullLogger() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetAllVersionsAsync( - id: "a", - cacheContext: test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ThrowIfCancelled() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetAllVersionsAsync( - id: "a", - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ReturnsEmptyEnumerableIfPackageIdNotFound() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var versions = await test.Resource.GetAllVersionsAsync( - id: "a", - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.Empty(versions); - } - } - - [Fact] - public async Task GetAllVersionsAsync_ReturnsAllVersions() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var versions = await test.Resource.GetAllVersionsAsync( - test.PackageIdentity.Id, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Equal(new[] { NuGetVersion.Parse("2.2.0-beta1-build3239") }, versions); - } - } - - [Fact] - public async Task GetAllVersionsAsync_NoErrorsOnNoContent() - { - // Arrange - var serviceAddress = TestUtility.CreateServiceAddress(); - - var responses = new Dictionary<string, string>(); - responses.Add(serviceAddress + "FindPackagesById()?id='a'", "204"); - - var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses); - var logger = new TestLogger(); - - using (var cacheContext = new SourceCacheContext()) - { - var resource = await repo.GetResourceAsync<FindPackageByIdResource>(); - - // Act - var versions = await resource.GetAllVersionsAsync( - "a", - cacheContext, - logger, - CancellationToken.None); - - // Assert - // Verify no items returned, and no exceptions were thrown above - Assert.Equal(0, versions.Count()); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task GetDependencyInfoAsync_ThrowsForNullOrEmptyId(string id) - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.GetDependencyInfoAsync( - id, - NuGetVersion.Parse("1.0.0"), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullVersion() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - id: "a", - version: null, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("version", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullSourceCacheContext() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowsForNullLogger() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetDependencyInfoAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ThrowIfCancelled() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetDependencyInfoAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_ReturnsNullIfPackageNotFound() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var dependencyInfo = await test.Resource.GetDependencyInfoAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.Null(dependencyInfo); - } - } - - [Fact] - public async Task GetDependencyInfoAsync_GetOriginalIdentity_IdInResponse() - { - // Arrange - using (var cacheContext = new SourceCacheContext()) - using (var workingDir = TestDirectory.Create()) - { - var source = "http://testsource.com/v3/index.json"; - var package = SimpleTestPackageUtility.CreateFullPackage(workingDir, "DeepEqual", "1.4.0.1-rc"); - var packageBytes = File.ReadAllBytes(package.FullName); - - var responses = new Dictionary<string, Func<HttpRequestMessage, Task<HttpResponseMessage>>> - { - { - source, - _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent(JsonData.IndexWithoutFlatContainer) - }) - }, - { - "https://api.nuget.org/v3/registration0/deepequal/index.json", - _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent(JsonData.DeepEqualRegistationIndex) - }) - }, - { - "https://api.nuget.org/packages/deepequal.1.4.0.1-rc.nupkg", - _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new ByteArrayContent(packageBytes) - }) - } - }; - - var repo = StaticHttpHandler.CreateSource(source, Repository.Provider.GetCoreV3(), responses); - - var logger = new TestLogger(); - - // Act - var resource = await repo.GetResourceAsync<FindPackageByIdResource>(); - var info = await resource.GetDependencyInfoAsync( - "DEEPEQUAL", - new NuGetVersion("1.4.0.1-RC"), - cacheContext, - logger, - CancellationToken.None); - - // Assert - Assert.IsType<RemoteV3FindPackageByIdResource>(resource); - Assert.Equal("DeepEqual", info.PackageIdentity.Id); - Assert.Equal("1.4.0.1-rc", info.PackageIdentity.Version.ToNormalizedString()); - } - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task CopyNupkgToStreamAsync_ThrowsForNullId(string id) - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentException>( - () => test.Resource.CopyNupkgToStreamAsync( - id, - NuGetVersion.Parse("1.0.0"), - Stream.Null, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None)); - - Assert.Equal("id", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullVersion() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: null, - destination: Stream.Null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("version", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullDestination() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("destination", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullSourceCacheContext() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: Stream.Null, - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsForNullLogger() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: Stream.Null, - cacheContext: test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ThrowsIfCancelled() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: Stream.Null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ReturnsFalseIfNotCopied() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - using (var stream = new MemoryStream()) - { - var wasCopied = await test.Resource.CopyNupkgToStreamAsync( - id: "a", - version: NuGetVersion.Parse("1.0.0"), - destination: stream, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None); - - Assert.False(wasCopied); - Assert.Equal(0, stream.Length); - } - } - - [Fact] - public async Task CopyNupkgToStreamAsync_ReturnsTrueIfCopied() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - using (var stream = new MemoryStream()) - { - var wasCopied = await test.Resource.CopyNupkgToStreamAsync( - test.PackageIdentity.Id, - test.PackageIdentity.Version, - stream, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.True(wasCopied); - Assert.Equal(test.Package.Length, stream.Length); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullPackageIdentity() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - packageIdentity: null, - cacheContext: test.SourceCacheContext, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("packageIdentity", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullSourceCacheContext() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - cacheContext: null, - logger: NullLogger.Instance, - cancellationToken: CancellationToken.None)); - - Assert.Equal("cacheContext", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsForNullLogger() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - logger: null, - cancellationToken: CancellationToken.None)); - - Assert.Equal("logger", exception.ParamName); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ThrowsIfCancelled() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - new CancellationToken(canceled: true))); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsNullIfPackageNotFound() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var downloader = await test.Resource.GetPackageDownloaderAsync( - new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")), - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.Null(downloader); - } - } - - [Fact] - public async Task GetPackageDownloaderAsync_ReturnsPackageDownloaderIfPackageFound() - { - using (var test = RemoteV3FindPackageByIdResourceTest.Create()) - { - var downloader = await test.Resource.GetPackageDownloaderAsync( - test.PackageIdentity, - test.SourceCacheContext, - NullLogger.Instance, - CancellationToken.None); - - Assert.IsType<RemotePackageArchiveDownloader>(downloader); - } - } - - private static HttpSource CreateDummyHttpSource() - { - var packageSource = new PackageSource("https://unit.test"); - Func<Task<HttpHandlerResource>> messageHandlerFactory = - () => Task.FromResult<HttpHandlerResource>(null); - - return new HttpSource(packageSource, messageHandlerFactory, Mock.Of<IThrottle>()); - } - - private sealed class RemoteV3FindPackageByIdResourceTest : IDisposable - { - private readonly TestHttpSource _httpSource; - - internal FileInfo Package { get; } - internal PackageIdentity PackageIdentity { get; } - internal RemoteV3FindPackageByIdResource Resource { get; } - internal SourceCacheContext SourceCacheContext { get; } - internal SourceRepository SourceRepository { get; } - internal TestDirectory TestDirectory { get; } - - private RemoteV3FindPackageByIdResourceTest( - RemoteV3FindPackageByIdResource resource, - SourceRepository sourceRepository, - FileInfo package, - PackageIdentity packageIdentity, - SourceCacheContext sourceCacheContext, - TestHttpSource httpSource, - TestDirectory testDirectory) - { - Resource = resource; - SourceRepository = sourceRepository; - Package = package; - PackageIdentity = packageIdentity; - SourceCacheContext = sourceCacheContext; - _httpSource = httpSource; - TestDirectory = testDirectory; - } - - public void Dispose() - { - SourceCacheContext.Dispose(); - _httpSource.Dispose(); - TestDirectory.Dispose(); - - GC.SuppressFinalize(this); - } - - internal static RemoteV3FindPackageByIdResourceTest Create() - { - var serviceAddress = TestUtility.CreateServiceAddress(); - var packageIdentity = new PackageIdentity( - id: "xunit", - version: NuGetVersion.Parse("2.2.0-beta1-build3239")); - var testDirectory = TestDirectory.Create(); - var packageSource = new PackageSource(serviceAddress); - - var dependencyInfoResourceProvider = new Mock<INuGetResourceProvider>(); - var dependencyInfoResource = new Mock<DependencyInfoResource>(); - var remoteSourceDependencyInfo = new RemoteSourceDependencyInfo( - packageIdentity, - listed: true, - dependencyGroups: Enumerable.Empty<PackageDependencyGroup>(), - contentUri: serviceAddress + "api/v2/package/xunit/2.2.0-beta1-build3239"); - - dependencyInfoResource.Setup(x => x.ResolvePackages( - It.Is<string>(id => id == packageIdentity.Id), - It.IsNotNull<ILogger>(), - It.IsAny<CancellationToken>())) - .ReturnsAsync(new[] { remoteSourceDependencyInfo }); - - dependencyInfoResourceProvider.SetupGet(x => x.Before) - .Returns(Enumerable.Empty<string>()); - dependencyInfoResourceProvider.SetupGet(x => x.After) - .Returns(Enumerable.Empty<string>()); - dependencyInfoResourceProvider.SetupGet(x => x.ResourceType) - .Returns(typeof(DependencyInfoResource)); - dependencyInfoResourceProvider.SetupGet(x => x.Name) - .Returns("DependencyInfoResourceProvider"); - dependencyInfoResourceProvider.Setup( - x => x.TryCreate(It.IsNotIn<SourceRepository>(), It.IsAny<CancellationToken>())) - .ReturnsAsync(new Tuple<bool, INuGetResource>(true, dependencyInfoResource.Object)); - - var sourceRepository = new SourceRepository( - packageSource, - new[] { dependencyInfoResourceProvider.Object }); - var package = SimpleTestPackageUtility.CreateFullPackage( - testDirectory.Path, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); - var packageBytes = File.ReadAllBytes(package.FullName); - - var responses = new Dictionary<string, Func<HttpRequestMessage, Task<HttpResponseMessage>>> - { - { - serviceAddress, - request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent(string.Empty) - }) - }, - { - serviceAddress + $"FindPackagesById()?id='{packageIdentity.Id}'", - request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent( - TestUtility.GetResource( - "NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml", - typeof(RemoteV3FindPackageByIdResourceTest))) - }) - }, - { - serviceAddress + $"FindPackagesById()?id='{packageIdentity.Id.ToUpper()}'", - request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new TestContent( - TestUtility.GetResource( - "NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml", - typeof(RemoteV3FindPackageByIdResourceTest))) - }) - }, - { - serviceAddress + "api/v2/package/xunit/2.2.0-beta1-build3239", - request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new ByteArrayContent(packageBytes) - }) - }, - { - serviceAddress + $"FindPackagesById()?id='a'", - request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.NoContent)) - } - }; - - var httpSource = new TestHttpSource(packageSource, responses); - var resource = new RemoteV3FindPackageByIdResource( - sourceRepository, - httpSource); - - return new RemoteV3FindPackageByIdResourceTest( - resource, - sourceRepository, - package, - packageIdentity, - new SourceCacheContext(), - httpSource, - testDirectory); - } - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteV2FindPackageByIdResourceTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteV2FindPackageByIdResourceTests.cs new file mode 100644 index 00000000000..cad96ee9f9b --- /dev/null +++ b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteV2FindPackageByIdResourceTests.cs @@ -0,0 +1,169 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using NuGet.Common; +using NuGet.Protocol.Core.Types; +using NuGet.Test.Utility; +using NuGet.Versioning; +using Test.Utility; +using Xunit; + +namespace NuGet.Protocol.Tests +{ + public class RemoteV2FindPackageByIdResourceTests + { + [Fact] + public async Task RemoteV2FindPackageById_VerifyNoErrorsOnNoContent() + { + // Arrange + var serviceAddress = TestUtility.CreateServiceAddress(); + + var responses = new Dictionary<string, string>(); + responses.Add(serviceAddress + "FindPackagesById()?id='a'", "204"); + + var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses); + var logger = new TestLogger(); + + using (var cacheContext = new SourceCacheContext()) + { + var resource = await repo.GetResourceAsync<FindPackageByIdResource>(); + + // Act + var versions = await resource.GetAllVersionsAsync( + "a", + cacheContext, + logger, + CancellationToken.None); + + // Assert + // Verify no items returned, and no exceptions were thrown above + Assert.Equal(0, versions.Count()); + } + } + + [Fact] + public async Task RemoteV2FindPackageById_GetOriginalIdentity_IdInResponse() + { + // Arrange + using (var workingDir = TestDirectory.Create()) + { + var serviceAddress = TestUtility.CreateServiceAddress(); + var package = SimpleTestPackageUtility.CreateFullPackage(workingDir, "xunit", "2.2.0-beta1-build3239"); + var packageBytes = File.ReadAllBytes(package.FullName); + + var responses = new Dictionary<string, Func<HttpRequestMessage, Task<HttpResponseMessage>>> + { + { + serviceAddress, + _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new TestContent(string.Empty) + }) + }, + { + serviceAddress + "FindPackagesById()?id='XUNIT'", + _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new TestContent(TestUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml", GetType())) + }) + }, + { + "https://www.nuget.org/api/v2/package/xunit/2.2.0-beta1-build3239", + _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new ByteArrayContent(packageBytes) + }) + } + }; + + var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses); + var logger = new TestLogger(); + + using (var cacheContext = new SourceCacheContext()) + { + var resource = await repo.GetResourceAsync<FindPackageByIdResource>(); + + // Act + var info = await resource.GetDependencyInfoAsync( + "XUNIT", + new NuGetVersion("2.2.0-BETA1-build3239"), + cacheContext, + logger, + CancellationToken.None); + + // Assert + Assert.IsType<RemoteV2FindPackageByIdResource>(resource); + Assert.Equal("xunit", info.PackageIdentity.Id); + Assert.Equal("2.2.0-beta1-build3239", info.PackageIdentity.Version.ToNormalizedString()); + } + } + } + + [Fact] + public async Task RemoteV2FindPackageById_GetOriginalIdentity_IdNotInResponse() + { + // Arrange + using (var workingDir = TestDirectory.Create()) + { + var serviceAddress = TestUtility.CreateServiceAddress(); + var package = SimpleTestPackageUtility.CreateFullPackage(workingDir, "WindowsAzure.Storage", "6.2.2-preview"); + var packageBytes = File.ReadAllBytes(package.FullName); + + var responses = new Dictionary<string, Func<HttpRequestMessage, Task<HttpResponseMessage>>> + { + { + serviceAddress, + _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new TestContent(string.Empty) + }) + }, + { + serviceAddress + "FindPackagesById()?id='WINDOWSAZURE.STORAGE'", + _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new TestContent(TestUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.WindowsAzureStorageFindPackagesById.xml", GetType())) + }) + }, + { + "https://www.nuget.org/api/v2/package/WindowsAzure.Storage/6.2.2-preview", + _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new ByteArrayContent(packageBytes) + }) + } + }; + + var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses); + var logger = new TestLogger(); + + using (var cacheContext = new SourceCacheContext()) + { + var resource = await repo.GetResourceAsync<FindPackageByIdResource>(); + + // Act + var info = await resource.GetDependencyInfoAsync( + "WINDOWSAZURE.STORAGE", + new NuGetVersion("6.2.2-PREVIEW"), + cacheContext, + logger, + CancellationToken.None); + + // Assert + Assert.IsType<RemoteV2FindPackageByIdResource>(resource); + Assert.Equal("WindowsAzure.Storage", info.PackageIdentity.Id); + Assert.Equal("6.2.2-preview", info.PackageIdentity.Version.ToNormalizedString()); + } + } + } + } +} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteV3FindPackageByIdResourceTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteV3FindPackageByIdResourceTests.cs new file mode 100644 index 00000000000..edea228cfb7 --- /dev/null +++ b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/RemoteV3FindPackageByIdResourceTests.cs @@ -0,0 +1,77 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using NuGet.Protocol.Core.Types; +using NuGet.Test.Utility; +using NuGet.Versioning; +using Test.Utility; +using Xunit; + +namespace NuGet.Protocol.Tests +{ + public class RemoteV3FindPackageByIdResourceTests + { + [Fact] + public async Task RemoteV3FindPackageById_GetOriginalIdentity_IdInResponse() + { + // Arrange + using (var cacheContext = new SourceCacheContext()) + using (var workingDir = TestDirectory.Create()) + { + var source = "http://testsource.com/v3/index.json"; + var package = SimpleTestPackageUtility.CreateFullPackage(workingDir, "DeepEqual", "1.4.0.1-rc"); + var packageBytes = File.ReadAllBytes(package.FullName); + + var responses = new Dictionary<string, Func<HttpRequestMessage, Task<HttpResponseMessage>>> + { + { + source, + _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new TestContent(JsonData.IndexWithoutFlatContainer) + }) + }, + { + "https://api.nuget.org/v3/registration0/deepequal/index.json", + _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new TestContent(JsonData.DeepEqualRegistationIndex) + }) + }, + { + "https://api.nuget.org/packages/deepequal.1.4.0.1-rc.nupkg", + _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new ByteArrayContent(packageBytes) + }) + } + }; + + var repo = StaticHttpHandler.CreateSource(source, Repository.Provider.GetCoreV3(), responses); + + var logger = new TestLogger(); + + // Act + var resource = await repo.GetResourceAsync<FindPackageByIdResource>(); + var info = await resource.GetDependencyInfoAsync( + "DEEPEQUAL", + new NuGetVersion("1.4.0.1-RC"), + cacheContext, + logger, + CancellationToken.None); + + // Assert + Assert.IsType<RemoteV3FindPackageByIdResource>(resource); + Assert.Equal("DeepEqual", info.PackageIdentity.Id); + Assert.Equal("1.4.0.1-rc", info.PackageIdentity.Version.ToNormalizedString()); + } + } + } +} diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/ServiceIndexResourceV3Tests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/ServiceIndexResourceV3Tests.cs deleted file mode 100644 index 257aa06ff9f..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/ServiceIndexResourceV3Tests.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json.Linq; -using Xunit; - -namespace NuGet.Protocol.Tests -{ - public class ServiceIndexResourceV3Tests - { - [Fact] - public void Constructor_InitializesProperties() - { - var serviceIndex = CreateServiceIndex(); - var expectedJson = serviceIndex.ToString(); - var expectedRequestTime = DateTime.UtcNow; - var resource = new ServiceIndexResourceV3(serviceIndex, expectedRequestTime); - - Assert.Equal(expectedJson, resource.Json); - Assert.Equal(expectedRequestTime, resource.RequestTime); - Assert.Equal(1, resource.Entries.Count); - Assert.Equal("a", resource.Entries[0].Type); - Assert.Equal("http://unit.test/b", resource.Entries[0].Uri.ToString()); - } - - private static JObject CreateServiceIndex() - { - return new JObject - { - { "version", "1.2.3" }, - { "resources", new JArray - { - new JObject - { - { "@type", "a" }, - { "@id", "http://unit.test/b" } - } - } - } - }; - } - } -} \ No newline at end of file diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Utility/OfflineFeedUtilityTests.cs b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Utility/OfflineFeedUtilityTests.cs deleted file mode 100644 index c8e3ed1b8a7..00000000000 --- a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/Utility/OfflineFeedUtilityTests.cs +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using System.Xml.Linq; -using NuGet.Common; -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; -using NuGet.Test.Utility; -using NuGet.Versioning; -using Xunit; - -namespace NuGet.Protocol.Tests -{ - // Negative tests here won't run well on *nix because bad test data used will trigger new exceptions - // TODO: we can revisit to catch them if there is value. - -#if !IS_CORECLR - public class OfflineFeedUtilityTests - { - [Theory] - [InlineData("c:\\foo|<>|bar")] - [InlineData("c:\\foo|<>|bar.nupkg")] - public void ThrowIfInvalid_ThrowsForInvalidPath(string path) - { - // Act & Assert - var expectedMessage = string.Format("'{0}' is not a valid path.", path); - - var exception = Assert.Throws<ArgumentException>(() => OfflineFeedUtility.ThrowIfInvalid(path)); - - Assert.Equal(expectedMessage, exception.Message); - } - - [Theory] - [InlineData("http://foonugetbar.org")] - [InlineData("http://foonugetbar.org/A.nupkg")] - public void ThrowIfInvalid_ThrowsIfPathNotFileOrUncPath(string path) - { - // Act & Assert - var expectedMessage = string.Format("'{0}' should be a local path or a UNC share path.", path); - - var exception - = Assert.Throws<ArgumentException>(() => OfflineFeedUtility.ThrowIfInvalid(path)); - - Assert.Equal(expectedMessage, exception.Message); - } - - [Theory] - [InlineData("foo\\bar")] - [InlineData("c:\\foo\\bar")] - [InlineData("\\foouncshare\\bar")] - public void ThrowIfInvalid_DoesNotThrowForValidPath(string path) - { - // Act & Assert that the following call does not throw - OfflineFeedUtility.ThrowIfInvalid(path); - } - - [Theory] - [InlineData("c:\\foobardoesnotexist", true)] - [InlineData("foobardoesnotexist\\A.nupkg", false)] - public void ThrowIfInvalidOrNotFound_ThrowsForInvalidOrNonexistentPath(string path, bool isDirectory) - { - // Act & Assert - var exception - = Assert.Throws<ArgumentException>(() - => OfflineFeedUtility.ThrowIfInvalidOrNotFound( - path, - isDirectory, - "some exception message")); - } - - [Fact] - public async Task AddPackageToSource_ThrowsForNullOfflineFeedAddContext() - { - var exception = await Assert.ThrowsAsync<ArgumentNullException>( - () => OfflineFeedUtility.AddPackageToSource( - offlineFeedAddContext: null, - token: CancellationToken.None)); - - Assert.Equal("offlineFeedAddContext", exception.ParamName); - } - - [Fact] - public async Task AddPackageToSource_ThrowsIfCancelled() - { - await Assert.ThrowsAsync<OperationCanceledException>( - () => OfflineFeedUtility.AddPackageToSource( - new OfflineFeedAddContext( - "a", - "b", - NullLogger.Instance, - throwIfSourcePackageIsInvalid: false, - throwIfPackageExistsAndInvalid: false, - throwIfPackageExists: false, - expand: true), - new CancellationToken(canceled: true))); - } - - [Fact] - public async Task AddPackageToSource_InstallsPackage() - { - using (var testDirectory = TestDirectory.Create()) - { - var packageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); - var packageContext = new SimpleTestPackageContext() - { - Id = packageIdentity.Id, - Version = packageIdentity.Version.ToNormalizedString(), - Nuspec = XDocument.Parse($@"<?xml version=""1.0"" encoding=""utf-8""?> - <package> - <metadata> - <id>{packageIdentity.Id}</id> - <version>{packageIdentity.Version.ToNormalizedString()}</version> - <title /> - <frameworkAssemblies> - <frameworkAssembly assemblyName=""System.Runtime"" /> - </frameworkAssemblies> - <contentFiles> - <files include=""lib/net45/{packageIdentity.Id}.dll"" copyToOutput=""true"" flatten=""false"" /> - </contentFiles> - </metadata> - </package>") - }; - - packageContext.AddFile($"lib/net45/{packageIdentity.Id}.dll"); - - var sourcePackageDirectoryPath = Path.Combine(testDirectory.Path, "source"); - var destinationDirectoryPath = Path.Combine(testDirectory.Path, "destination"); - - Directory.CreateDirectory(destinationDirectoryPath); - - SimpleTestPackageUtility.CreatePackages(sourcePackageDirectoryPath, packageContext); - - var sourcePackageFilePath = Path.Combine( - sourcePackageDirectoryPath, - $"{packageIdentity.Id}.{packageIdentity.Version.ToNormalizedString()}.nupkg"); - - var destinationPackageDirectoryPath = Path.Combine( - destinationDirectoryPath, - packageIdentity.Id, - packageIdentity.Version.ToNormalizedString()); - - var context = new OfflineFeedAddContext( - sourcePackageFilePath, - destinationDirectoryPath, - NullLogger.Instance, - throwIfSourcePackageIsInvalid: false, - throwIfPackageExistsAndInvalid: false, - throwIfPackageExists: false, - expand: true); - - await OfflineFeedUtility.AddPackageToSource(context, CancellationToken.None); - - Assert.True(File.Exists(Path.Combine(destinationPackageDirectoryPath, $"{packageIdentity.Id}.{packageIdentity.Version.ToNormalizedString()}.nupkg"))); - Assert.True(File.Exists(Path.Combine(destinationPackageDirectoryPath, $"{packageIdentity.Id}.{packageIdentity.Version.ToNormalizedString()}.nupkg.sha512"))); - Assert.True(File.Exists(Path.Combine(destinationPackageDirectoryPath, $"{packageIdentity.Id}.nuspec"))); - Assert.True(File.Exists(Path.Combine(destinationPackageDirectoryPath, "lib", "net45", $"{packageIdentity.Id}.dll"))); - } - } - } -#endif -} diff --git a/test/NuGet.Core.Tests/NuGet.Protocol.Tests/compiler/resources/DefaultClassLibrary.dll b/test/NuGet.Core.Tests/NuGet.Protocol.Tests/compiler/resources/DefaultClassLibrary.dll deleted file mode 100644 index 82aee00043a82255a61489812bad73085ae18eeb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4096 zcmeHK-ES0C6hG5$ODR%l_(+Wg1`3EuCcCt#pu)D@7ApN%y9<hLpfj_#+kx4c$;@nF zU$h4CNfZA9f{D@Six@Q$jfo+~_#nZ=7+-iG(dY~4ix0*J@pta*uuHd)#_*sCXM2D5 z-gC}9U-!=3>G%t8QY#T9&~Dryx`3W3E%DAU4{_JV&${U2<(D>HP{uB8%FkMX>iKTT z*UPG@JB}NwhEV;AqgsxdnartWw<xrgD?7K;OlOCQ#*|jNvN7>%?CmOTR#zxVq7HD{ zBks{{=vA~d8qsPwZi(V%2FEXH9tb{DE2Yn{D*x5{+LT$KPS~B~L7M1GF2q8bCb|#2 z9b1W>SSY*GT#dqyRXQ*~5Kqu+p*R(yFLHh=8s}Pz8zV_7(X{3VzKNNPEsX&u+KJXc zX+*F2!gis^vC=de+v-AVpfu57!&DCUa$P|jTMM;OK_&VQJ``sD3)<YW9U*kmBUn3_ zduC9nS>m|n`n9Cim+VXJX2We{13ftEeTnD_`UGO`&4s?@lmgbciv8epdk^L4XN-9p zd-oq2&7l7S^D8_bv|R%|6P7Fc*Agw~$zMtzt&j3p8OdZM9LEYY&M(TbtVDe~{Y0NC z?X*i_ROxMH75xZNI~}API1ehX1K%aauO${Gz9O+zO8e#b7v+pJ$y>@^__rGEy0S}- zvnumn>p2Tc3ZgxW2)cpobU(0@9tN(al*HW<2PBS4d{*KSiMm7!*iIVq+5lWb4*?&b z5nwOQwnmTA8DJls1wKjd0f*=!@E~0V=A`sRU}8S53Br?f9eE@WV@&H1XN`tzJqS|t z)VN!$*kUi`szE5q+Em2}t+JquFe;^zZrEZV#Eu%3P|!dSh_Yc<^H$i%&g*_jgd=!m zh?A~=qFH~$vc+NH2bSwJ3rC$9*DvcKgt~oOts&Q$u}T$R>NOk5h`{tMkB!uYLvGo# zY`J1e*!n3s3hMGWove=%m|?Sk4d_m_E~php@<Yq8Y%6S#-daJemJ1#R6mv$e*r6=> zm}U67U)74XU90)c(u)~en4AM?X6X7cKV#`7#|=Wu3}RL-5G_hk_&MRvS*8eT+XkQ5 zR!k?2<FL4x|M(bu`)b#b%iFdb{OH=}8&1FR{x_6R6{Vw9C8Z66?rxrTb)4UK?B(ts zI`?!a@;yhifuD(d%lhYh-J5Wo;ZvrN)z8oR?#V!b-ZFXWb}7`OO$_IUTwe@$-i}&P zo}No-DH!Nld-K?2tiZGN>I6;^^(eGvk(%MXq)?kYnIv_xx_Lq`3AJJS@dkzO6kb&L zMGNF4&iDI^zg;6`Jd1Y?y@OW7y--{hOQT+1Hw~<*TqbvV#q5WFt~+|*+*_*-ebDiV z;Oxvjg-U>PT_}duoUjW;*Q}I<69$DjE2!wU8ibXi<*GZAsmBXAWxN+bVUffZ<+;Xj z@bMHD91)tRpYD06+G4tzS2Sp6?Iz&B$9SyrsF~s$Ba$4$&SY$RT(=x52kb`3qZvtW zY=xDD<!Cl}kMkd?0N+!1G>GPJ4Jf+B@jNu~S&zRRo=@XBz?~dZv9%w=!?<0J0f%V{ zqfy*O6PS+zN20GT`XcfB-_fljpLeW@`h7J+eE;*a)<}H+E3m4Q4?7mVBLr+ZG()ab z+akXj@{sD_29WC%LeIr4qVtKb_+tSvh0wCVFD+u}oYYBD{OczJW1=*z#o8g*E8{1y zI)oRZEc}>s0$2i9r3^3thdp==5gce(@5vaesE96YaeTaP2J;Fc58;R75AYj<9Ybd2 zQ&sxoIN}Q2&fC)MCGm2u+dGUXe0Z(bErqXz<juzU_CTL2A4**ZaoP=;EG-X>ide<p zg4?mv3bGWaA6w!Id&rdQSE5;XAygG-P5Paz@p<=HJFWxIcvqI1cin%qFIm`i5mN;_ z7dB+GRC|OP@ps*=b{1B%UQ7PJg6lpY_gEly1KCuO>Fw9>KHMczqyHJEAG=HT?wR>t GRp1}mX*>M@ diff --git a/test/TestExtensions/TestablePlugin/Arguments.cs b/test/TestExtensions/TestablePlugin/Arguments.cs deleted file mode 100644 index ebfa3e37a16..00000000000 --- a/test/TestExtensions/TestablePlugin/Arguments.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; - -namespace NuGet.Test.TestExtensions.TestablePlugin -{ - internal sealed class Arguments - { - internal ushort PortNumber { get; private set; } - internal int TestRunnerProcessId { get; private set; } - - private Arguments() { } - - internal static bool TryParse(IReadOnlyList<string> args, out Arguments arguments) - { - arguments = null; - - ushort portNumber = 0; - var testRunnerProcessId = 0; - var isPlugin = false; - - for (var i = 0; i < args.Count; ++i) - { - var flag = args[i]; - - switch (flag.ToLower()) - { - case "-portnumber": - if (i + 1 == args.Count) - { - return false; - } - - ++i; - - if (!ushort.TryParse(args[i], out portNumber)) - { - return false; - } - break; - - case "-plugin": - isPlugin = true; - break; - - case "-testrunnerprocessid": - if (i + 1 == args.Count) - { - return false; - } - - ++i; - - if (!int.TryParse(args[i], out testRunnerProcessId)) - { - return false; - } - break; - - default: - return false; - } - } - - if (!isPlugin) - { - return false; - } - - arguments = new Arguments() - { - PortNumber = portNumber, - TestRunnerProcessId = testRunnerProcessId - }; - - return true; - } - } -} \ No newline at end of file diff --git a/test/TestExtensions/TestablePlugin/Program.cs b/test/TestExtensions/TestablePlugin/Program.cs deleted file mode 100644 index e873b8271bf..00000000000 --- a/test/TestExtensions/TestablePlugin/Program.cs +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Diagnostics; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace NuGet.Test.TestExtensions.TestablePlugin -{ - internal static class Program - { - private const int _success = 0; - private const int _error = 1; - - private static int Main(string[] args) - { - try - { - Console.OutputEncoding = Encoding.UTF8; - - DebugBreakIfPluginDebuggingIsEnabled(); - - Arguments parsedArgs; - - if (!Arguments.TryParse(args, out parsedArgs)) - { - return _error; - } - - Start(parsedArgs); - } - catch (Exception ex) - { - Console.Error.WriteLine(ex.ToString()); - - return _error; - } - - return _success; - } - - private static void Start(Arguments arguments) - { - using (var cancellationTokenSource = new CancellationTokenSource()) - using (var responses = new BlockingCollection<Response>()) - { - Process process; - - if (!TryGetProcess(arguments.TestRunnerProcessId, out process)) - { - return; - } - - using (process) - { - process.Exited += (sender, args) => - { - try - { - cancellationTokenSource.Cancel(); - } - catch (Exception) - { - } - }; - - process.EnableRaisingEvents = true; - - var responseReceiver = new ResponseReceiver(arguments.PortNumber, responses); - - using (var testablePlugin = new TestablePlugin(responses)) - { - var tasks = new[] - { - Task.Factory.StartNew( - () => responseReceiver.StartListeningAsync(cancellationTokenSource.Token), - TaskCreationOptions.LongRunning | TaskCreationOptions.DenyChildAttach), - testablePlugin.StartAsync(cancellationTokenSource.Token) - }; - - Task.WaitAny(tasks); - - try - { - cancellationTokenSource.Cancel(); - } - catch (Exception) - { - } - } - } - } - } - - private static void DebugBreakIfPluginDebuggingIsEnabled() - { - if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("NUGET_PLUGIN_DEBUG"))) - { - Debugger.Break(); - } - } - - private static bool TryGetProcess(int processId, out Process process) - { - try - { - process = Process.GetProcessById(processId); - - return true; - } - catch (Exception) - { - } - - process = null; - - return false; - } - } -} \ No newline at end of file diff --git a/test/TestExtensions/TestablePlugin/Response.cs b/test/TestExtensions/TestablePlugin/Response.cs deleted file mode 100644 index 6c324d1e151..00000000000 --- a/test/TestExtensions/TestablePlugin/Response.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using NuGet.Protocol.Plugins; - -namespace NuGet.Test.TestExtensions.TestablePlugin -{ - internal sealed class Response - { - [JsonRequired] - public MessageType Type { get; set; } - - [JsonRequired] - public MessageMethod Method { get; set; } - - public JObject Payload { get; set; } - } -} \ No newline at end of file diff --git a/test/TestExtensions/TestablePlugin/ResponseReceiver.cs b/test/TestExtensions/TestablePlugin/ResponseReceiver.cs deleted file mode 100644 index cdf8768be87..00000000000 --- a/test/TestExtensions/TestablePlugin/ResponseReceiver.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Concurrent; -using System.IO; -using System.Net; -using System.Net.Sockets; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Protocol.Plugins; - -namespace NuGet.Test.TestExtensions.TestablePlugin -{ - internal sealed class ResponseReceiver - { - private readonly ushort _portNumber; - private readonly BlockingCollection<Response> _responses; - - internal ResponseReceiver(ushort portNumber, BlockingCollection<Response> responses) - { - _portNumber = portNumber; - _responses = responses; - } - - internal Task StartListeningAsync(CancellationToken cancellationToken) - { - var localEndPoint = new IPEndPoint(IPAddress.Loopback, _portNumber); - - using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - { - listener.Bind(localEndPoint); - listener.Listen(10); - - var socket = listener.Accept(); - - using (var stream = new NetworkStream(socket, ownsSocket: true)) - using (var streamReader = new StreamReader(stream)) - { - string text; - - while ((text = streamReader.ReadLine()) != null) - { - cancellationToken.ThrowIfCancellationRequested(); - - var response = JsonSerializationUtilities.Deserialize<Response>(text); - - _responses.Add(response); - } - } - } - - return Task.FromResult(0); - } - } -} \ No newline at end of file diff --git a/test/TestExtensions/TestablePlugin/TestablePlugin.cs b/test/TestExtensions/TestablePlugin/TestablePlugin.cs deleted file mode 100644 index aea74bf8906..00000000000 --- a/test/TestExtensions/TestablePlugin/TestablePlugin.cs +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Protocol.Plugins; - -namespace NuGet.Test.TestExtensions.TestablePlugin -{ - internal sealed class TestablePlugin : IRequestHandler, IDisposable - { - private CancellationTokenSource _cancellationTokenSource; - private bool _isDisposed; - private IPlugin _plugin; - private readonly BlockingCollection<Response> _responses; - - public CancellationToken CancellationToken { get; private set; } - - internal TestablePlugin(BlockingCollection<Response> responses) - { - _responses = responses; - } - - public void Dispose() - { - if (!_isDisposed) - { - if (_plugin != null) - { - _plugin.Dispose(); - } - - if (_cancellationTokenSource != null) - { - using (_cancellationTokenSource) - { - _cancellationTokenSource.Cancel(); - } - } - - GC.SuppressFinalize(this); - - _isDisposed = true; - } - } - - internal async Task StartAsync(CancellationToken cancellationToken) - { - _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - CancellationToken = _cancellationTokenSource.Token; - - var requestHandlers = CreateRequestHandlers(); - var options = ConnectionOptions.CreateDefault(); - - _plugin = await PluginFactory.CreateFromCurrentProcessAsync(requestHandlers, options, CancellationToken); - - if (_plugin.Connection.ProtocolVersion != ProtocolConstants.CurrentVersion) - { - throw new NotSupportedException(); - } - - await Task.Delay(Timeout.InfiniteTimeSpan, CancellationToken); - } - - public Task HandleCancelAsync( - IConnection connection, - Message message, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - throw new NotImplementedException(); - } - - public async Task HandleResponseAsync( - IConnection connection, - Message message, - IResponseHandler responseHandler, - CancellationToken cancellationToken) - { - var response = _responses.Take(); - - if (message.Type == MessageType.Request) - { - switch (message.Method) - { - case MessageMethod.Initialize: - { - var initializeRequest = JsonSerializationUtilities.ToObject<InitializeRequest>(message.Payload); - - _plugin.Connection.Options.SetRequestTimeout(initializeRequest.RequestTimeout); - } - break; - - case MessageMethod.Close: - _cancellationTokenSource.Cancel(); - break; - - default: - break; - } - } - - await responseHandler.SendResponseAsync(message, response.Payload, cancellationToken); - } - - private IRequestHandlers CreateRequestHandlers() - { - var handlers = new RequestHandlers(); - - handlers.TryAdd(MessageMethod.Initialize, this); - handlers.TryAdd(MessageMethod.GetOperationClaims, this); - - return handlers; - } - - private void OnShuttingDown(object sender, EventArgs e) - { - _cancellationTokenSource.Cancel(); - } - } -} \ No newline at end of file diff --git a/test/TestExtensions/TestablePlugin/TestablePlugin.csproj b/test/TestExtensions/TestablePlugin/TestablePlugin.csproj deleted file mode 100644 index c09f14934e1..00000000000 --- a/test/TestExtensions/TestablePlugin/TestablePlugin.csproj +++ /dev/null @@ -1,18 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<Project Sdk="Microsoft.NET.Sdk"> - <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), 'README.md'))\build\common.props" /> - - <PropertyGroup> - <TargetFrameworks>netcoreapp1.0;net46</TargetFrameworks> - <RuntimeIdentifier>win7-x64</RuntimeIdentifier> - <OutputType>Exe</OutputType> - <AssemblyName>Plugin.Testable</AssemblyName> - </PropertyGroup> - - <Import Project="$(BuildCommonDirectory)common.targets" /> - - <ItemGroup> - <ProjectReference Include="..\..\..\src\NuGet.Core\NuGet.Protocol\NuGet.Protocol.csproj" /> - <ProjectReference Include="..\..\..\src\NuGet.Core\NuGet.Versioning\NuGet.Versioning.csproj" /> - </ItemGroup> -</Project> \ No newline at end of file diff --git a/test/TestUtilities/Test.Utility/ResourceTestUtility.cs b/test/TestUtilities/Test.Utility/ResourceTestUtility.cs index fb015851516..80e86a65b5a 100644 --- a/test/TestUtilities/Test.Utility/ResourceTestUtility.cs +++ b/test/TestUtilities/Test.Utility/ResourceTestUtility.cs @@ -16,20 +16,5 @@ public static string GetResource(string name, Type type) return reader.ReadToEnd(); } } - - public static void CopyResourceToFile(string resourceName, Type type, string filePath) - { - var bytes = GetResourceBytes(resourceName, type); - - File.WriteAllBytes(filePath, bytes); - } - - private static byte[] GetResourceBytes(string name, Type type) - { - using (var reader = new BinaryReader(type.GetTypeInfo().Assembly.GetManifestResourceStream(name))) - { - return reader.ReadBytes((int)reader.BaseStream.Length); - } - } } -} \ No newline at end of file +}