From 5f074c62a1636ccd77cea5e6af78f9d762cc14db Mon Sep 17 00:00:00 2001 From: Abhijeet Shah Date: Sun, 29 Jul 2018 14:08:47 -0700 Subject: [PATCH] LRO retries makes the recorded file size bigger, that results in failing to open on CI machine when CI machines are running low on resources. Adding feature to http recorder to compress LRO recorded files. This will eliminate LRO retries during playback. The current iteration of optimization resulted in eliminating ~40% LRO payload out of recorded files. During compacting of the files, it creates a backup of original file incase the test author decides to have both recordings (uncompressed as well as compressed) Added additional key-vaule pair to trigger compressing recorded file in testFx. The new Key-Value pair is OptimizeRecordedFiles=true/false Added unit tests. Recorded full E2E tests and compressed the recorded file. Refactored test project to minimize redundant files, refactored namespaces in test projects. Rearranged project files to comply building with multiple target frameworks. Added additional meta data that will allow to query recorded data on multiple pivots (operation type, header type etc.) --- ...est.ClientRuntime.Azure.Authentication.sln | 37 + .../ClientRuntime.Azure/LRO/Base/AzureLRO.cs | 123 +- .../ClientRuntime.Azure/LRO/LROPollState.cs | 9 +- .../LRO/Operations/DeleteLro.cs | 3 + .../LRO/Operations/PATCHLro.cs | 3 + .../LRO/Operations/POSTLro.cs | 3 + .../LRO/Operations/PUTLro.cs | 3 + src/SdkCommon/ClientRuntime.sln | 7 - .../ClientRuntime.E2E.Tests.csproj | 9 +- .../ClientRuntime.E2E.Tests.sln | 9 + .../UpdateVM_DoNotSerializeProtected.json | 3627 +++-------------- .../ConnectionString.cs | 24 +- .../ConnectionStringKeys.cs | 3 + ...t.ClientRuntime.Azure.TestFramework.csproj | 26 +- .../MockContext.cs | 35 +- .../TestEnvironment.cs | 5 + .../TestEnvironmentFactory.cs | 2 +- ...erTests.cs => BinaryDataMoqServerTests.cs} | 4 +- .../DelegatingHandlers/LroResponseHandler.cs | 48 + .../HttpRecorder.Tests.csproj | 4 +- .../MockResponse/LROOpertionTestResponses.cs | 2362 ----------- .../MockResponse/LroRulesResponses.cs | 2936 ------------- .../MoqServerTests/BinaryDataTests.cs | 76 + .../MoqServerTestBase.cs} | 26 +- .../RecordProcessTests.cs | 162 + .../ResponseData/LroResponseData.cs | 1022 +++++ .../TestClients/RedisManagementClient.cs | 2398 +++++++++++ .../HttpMockServer.cs | 42 +- .../Microsoft.Azure.Test.HttpRecorder.csproj | 5 +- .../Model/RequestResponseInfo.cs | 273 ++ .../ProcessRecordings/ProcessRecordedFiles.cs | 60 + .../Processors/CompactLroEntries.cs | 113 + .../ProcessRecordings/Startup.cs | 16 + .../ProcessRecordings/Utilities/Logger.cs | 187 + .../Properties/AssemblyInfo.cs | 38 +- .../RecordEntry.cs | 8 +- .../RecordEntryPack.cs | 18 + .../RecorderUtilities.cs | 5 +- .../Records.cs | 1 - .../ConnectionStringParseTests.cs | 13 + .../TestFramework/TestRecordAndFramework.sln | 41 +- 41 files changed, 5376 insertions(+), 8410 deletions(-) create mode 100644 src/SdkCommon/Auth/Az.Auth/Microsoft.Rest.ClientRuntime.Azure.Authentication.sln rename src/SdkCommon/TestFramework/HttpRecorder.Tests/{BinaryDataMockServerTests.cs => BinaryDataMoqServerTests.cs} (97%) create mode 100644 src/SdkCommon/TestFramework/HttpRecorder.Tests/DelegatingHandlers/LroResponseHandler.cs delete mode 100644 src/SdkCommon/TestFramework/HttpRecorder.Tests/MockResponse/LROOpertionTestResponses.cs delete mode 100644 src/SdkCommon/TestFramework/HttpRecorder.Tests/MockResponse/LroRulesResponses.cs create mode 100644 src/SdkCommon/TestFramework/HttpRecorder.Tests/MoqServerTests/BinaryDataTests.cs rename src/SdkCommon/TestFramework/HttpRecorder.Tests/{BaseMockServerTest.cs => MoqServerTests/MoqServerTestBase.cs} (81%) create mode 100644 src/SdkCommon/TestFramework/HttpRecorder.Tests/ProcessRecordedTests/RecordProcessTests.cs create mode 100644 src/SdkCommon/TestFramework/HttpRecorder.Tests/ResponseData/LroResponseData.cs create mode 100644 src/SdkCommon/TestFramework/HttpRecorder.Tests/TestClients/RedisManagementClient.cs create mode 100644 src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Model/RequestResponseInfo.cs create mode 100644 src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/ProcessRecordedFiles.cs create mode 100644 src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Processors/CompactLroEntries.cs create mode 100644 src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Startup.cs create mode 100644 src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Utilities/Logger.cs diff --git a/src/SdkCommon/Auth/Az.Auth/Microsoft.Rest.ClientRuntime.Azure.Authentication.sln b/src/SdkCommon/Auth/Az.Auth/Microsoft.Rest.ClientRuntime.Azure.Authentication.sln new file mode 100644 index 000000000000..ee220b313c4d --- /dev/null +++ b/src/SdkCommon/Auth/Az.Auth/Microsoft.Rest.ClientRuntime.Azure.Authentication.sln @@ -0,0 +1,37 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2026 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Rest.ClientRuntime.Azure.Authentication", "Az.Authentication\Microsoft.Rest.ClientRuntime.Azure.Authentication.csproj", "{EE15BED1-9C29-4A8F-9FAC-99EEAEEF6F31}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Az.Auth.NetCore.Test", "Az.Auth.Tests\Az.Auth.NetCore.Test\Az.Auth.NetCore.Test.csproj", "{6CFB9119-B192-44D1-8249-DD85172ABB00}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Az.Auth.Net452.Test", "Az.Auth.Tests\Az.Auth.Net452.Test\Az.Auth.Net452.Test.csproj", "{ACACDA67-5693-40B4-BA2B-6099A38C1562}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EE15BED1-9C29-4A8F-9FAC-99EEAEEF6F31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EE15BED1-9C29-4A8F-9FAC-99EEAEEF6F31}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EE15BED1-9C29-4A8F-9FAC-99EEAEEF6F31}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EE15BED1-9C29-4A8F-9FAC-99EEAEEF6F31}.Release|Any CPU.Build.0 = Release|Any CPU + {6CFB9119-B192-44D1-8249-DD85172ABB00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6CFB9119-B192-44D1-8249-DD85172ABB00}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6CFB9119-B192-44D1-8249-DD85172ABB00}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6CFB9119-B192-44D1-8249-DD85172ABB00}.Release|Any CPU.Build.0 = Release|Any CPU + {ACACDA67-5693-40B4-BA2B-6099A38C1562}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ACACDA67-5693-40B4-BA2B-6099A38C1562}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ACACDA67-5693-40B4-BA2B-6099A38C1562}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ACACDA67-5693-40B4-BA2B-6099A38C1562}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B8405D09-BF11-4B8C-87CB-E79B47CFA938} + EndGlobalSection +EndGlobal diff --git a/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Base/AzureLRO.cs b/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Base/AzureLRO.cs index 6a20257b3744..090a3dd1ab9f 100644 --- a/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Base/AzureLRO.cs +++ b/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Base/AzureLRO.cs @@ -7,6 +7,7 @@ namespace Microsoft.Rest.ClientRuntime.Azure.LRO using Microsoft.Rest.ClientRuntime.Azure.Properties; using System; using System.Collections.Generic; + using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; @@ -26,7 +27,7 @@ internal abstract class AzureLRO : IAzureLRO InitialResponse; protected CancellationToken CancelToken; - protected Dictionary> CustomHeaders; + protected Dictionary> _customHeaders; protected LROPollState CurrentPollingState; protected IAzureClient SdkClient; protected bool IsLROTaskCompleted { get; set; } @@ -51,9 +52,28 @@ protected AzureLRO(IAzureClient client, CancelToken = cancellationToken; SdkClient = client; ValidateInitialResponse(); +#if DEBUG + lroPollingCount = 1; +#endif } #endregion + protected Dictionary> CustomHeaders + { + get + { + if (_customHeaders == null) + _customHeaders = new Dictionary>(); + + return _customHeaders; + } + + set + { + _customHeaders = value; + } + } + #region Public functions /// /// Begin polling @@ -146,6 +166,9 @@ protected virtual void InitializeAsyncHeadersToUse() if (CurrentPollingState == null) { CurrentPollingState = new LROPollState(InitialResponse, SdkClient); +#if DEBUG + InitLroSession(); +#endif if (!string.IsNullOrEmpty(CurrentPollingState.AzureAsyncOperationHeaderLink)) { @@ -177,14 +200,23 @@ protected virtual void InitializeAsyncHeadersToUse() /// protected virtual async Task StartPollingAsync() { +#if DEBUG + InitPollingSession(); +#endif while (!AzureAsyncOperation.TerminalStatuses.Any(s => s.Equals(CurrentPollingState.Status, StringComparison.OrdinalIgnoreCase))) { await Task.Delay(CurrentPollingState.DelayBetweenPolling, CancelToken); +#if DEBUG + UpdatePollingSessionIds(); +#endif await CurrentPollingState.Poll(CustomHeaders, CancelToken); UpdatePollingState(); CheckForErrors(); InitializeAsyncHeadersToUse(); } +#if DEBUG + RemoveLroHeaders(removePerfImapact: true); +#endif } /// @@ -342,6 +374,95 @@ protected virtual string GetValidAbsoluteUri(string url, bool throwForInvalidUri #endregion #region Private functions + +#if DEBUG + const string Header_LroSessionId = "LroSessionId"; + const string Header_LroPollingId = "LroPollingId"; + const string Header_RecordPlaybackPerfImpact = "RecordPlaybackPerfImpact"; + const string Header_LroOperation = "LroOperation"; + const int perfImpactCount = 3; + + private long lroSessionId { get; set; } + + private long lroPollingId { get; set; } + + private long lroPollingCount { get; set; } + + private string lroSessionPollingId { get; set; } + + + private void InitLroSession() + { + this.lroPollingCount = 1; + this.lroSessionId = DateTime.Now.Ticks; + this.CustomHeaders.Add(Header_LroOperation, new List() { this.RESTOperationVerb }); + } + + private void InitPollingSession() + { + this.lroPollingId = DateTime.Now.Ticks; + } + + private void UpdatePollingSessionIds() + { + RemoveLroHeaders(); + this.lroSessionPollingId = string.Format("{0}.{1}.{2}", this.lroSessionId.ToString(), this.lroPollingId.ToString(), this.lroPollingCount.ToString()); + this.CustomHeaders.Add(Header_LroSessionId, new List() { this.lroSessionId.ToString() }); + this.CustomHeaders.Add(Header_LroPollingId, new List() { this.lroSessionPollingId.ToString() }); + if(this.lroPollingCount >= perfImpactCount) + { + if(!this.CustomHeaders.TryGetValue(Header_RecordPlaybackPerfImpact, out List playBackImpact)) + { + this.CustomHeaders.Add(Header_RecordPlaybackPerfImpact, new List() { "true" }); + } + } + + this.lroPollingCount = this.lroPollingCount + 1; + } + + protected void RemoveLroHeaders(bool removePerfImapact = false, bool removeOperation = false) + { + if(this.CustomHeaders.TryGetValue(Header_LroSessionId, out List lroSessionIdList)) + { + if(lroSessionIdList.Any()) + { + this.CustomHeaders.Remove(Header_LroSessionId); + } + } + + if (this.CustomHeaders.TryGetValue(Header_LroPollingId, out List lroPollingIdList)) + { + if (lroPollingIdList.Any()) + { + this.CustomHeaders.Remove(Header_LroPollingId); + } + } + + if (removePerfImapact) + { + if (this.CustomHeaders.TryGetValue(Header_RecordPlaybackPerfImpact, out List recPerfImpactList)) + { + if (recPerfImpactList.Any()) + { + this.CustomHeaders.Remove(Header_RecordPlaybackPerfImpact); + } + } + } + + if(removeOperation) + { + if (this.CustomHeaders.TryGetValue(Header_LroOperation, out List restOperation)) + { + if (restOperation.Any()) + { + this.CustomHeaders.Remove(Header_LroOperation); + } + } + } + } + +#endif + /// /// Get Valid status /// There are cases where there is an error sent from the service and in that case, the status should be one of the valid FailedStatuses diff --git a/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/LROPollState.cs b/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/LROPollState.cs index 86e504b18d5b..88d298958afc 100644 --- a/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/LROPollState.cs +++ b/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/LROPollState.cs @@ -11,6 +11,7 @@ namespace Microsoft.Rest.ClientRuntime.Azure.LRO using System; using System.Collections.Generic; using System.Globalization; + using System.Linq; using System.Net; using System.Net.Http; using System.Threading; @@ -46,7 +47,8 @@ internal class LROPollState : PollingState response, IAzureClient client) : base(response, client.LongRunningOperationRetryTimeout) + internal LROPollState(HttpOperationResponse response, IAzureClient client) + : base(response, client.LongRunningOperationRetryTimeout) { SdkClient = client; InitialResponse = response; @@ -57,7 +59,7 @@ internal LROPollState(HttpOperationResponse resp internal async Task Poll(Dictionary> customHeaders, CancellationToken cancellationToken) - { + { await UpdateResourceFromPollingUri(customHeaders, cancellationToken); #region Error response returned while polling on AsyncOperationHeader @@ -136,8 +138,6 @@ private TDeserializedBodyType DeserializeToObject(Func /// Gets a resource from the specified URL. /// - /// IAzureClient - /// URL of the resource. /// Headers that will be added to request /// Cancellation token /// @@ -193,6 +193,7 @@ internal async Task> GetRawAsync( ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); + HttpResponseMessage httpResponse = await SdkClient.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { diff --git a/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/DeleteLro.cs b/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/DeleteLro.cs index 6ac36cbaba4f..7b66b6fd312e 100644 --- a/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/DeleteLro.cs +++ b/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/DeleteLro.cs @@ -143,6 +143,9 @@ protected override async Task PostPollingAsync() } } } +#if DEBUG + RemoveLroHeaders(removeOperation: true); +#endif } /// diff --git a/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/PATCHLro.cs b/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/PATCHLro.cs index 09b7c8e5bcf3..9213ed4209ef 100644 --- a/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/PATCHLro.cs +++ b/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/PATCHLro.cs @@ -126,6 +126,9 @@ protected override async Task PostPollingAsync() await CurrentPollingState.UpdateResourceFromPollingUri(CustomHeaders, CancelToken); } } +#if DEBUG + RemoveLroHeaders(removeOperation: true); +#endif } } } diff --git a/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/POSTLro.cs b/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/POSTLro.cs index 12132c2d21fb..117fbd3e4993 100644 --- a/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/POSTLro.cs +++ b/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/POSTLro.cs @@ -120,6 +120,9 @@ protected override async Task PostPollingAsync() } } } +#if DEBUG + RemoveLroHeaders(removeOperation: true); +#endif } } } diff --git a/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/PUTLro.cs b/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/PUTLro.cs index 39b4bee5f56e..2ab91914059e 100644 --- a/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/PUTLro.cs +++ b/src/SdkCommon/ClientRuntime.Azure/ClientRuntime.Azure/LRO/Operations/PUTLro.cs @@ -65,6 +65,9 @@ protected override async Task PostPollingAsync() await CurrentPollingState.UpdateResourceFromPollingUri(CustomHeaders, CancelToken); } } +#if DEBUG + RemoveLroHeaders(removeOperation:true); +#endif } protected override void CheckForErrors() diff --git a/src/SdkCommon/ClientRuntime.sln b/src/SdkCommon/ClientRuntime.sln index 3750ed7061f7..983db0297d3e 100644 --- a/src/SdkCommon/ClientRuntime.sln +++ b/src/SdkCommon/ClientRuntime.sln @@ -17,8 +17,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Rest.ClientRuntim EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Rest.ClientRuntime", "ClientRuntime\ClientRuntime\Microsoft.Rest.ClientRuntime.csproj", "{C8DEE788-A658-4C1F-ACC4-866CDE9315BB}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClientRuntime.E2E.Tests", "Test\ClientRuntime.E2E.Tests\ClientRuntime.E2E.Tests.csproj", "{87980F3C-A993-4620-B43A-07A174DB852E}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CR.Azure.NetCore.Tests", "ClientRuntime.Azure\Tests\CR.Azure.NetCore.Tests\CR.Azure.NetCore.Tests.csproj", "{99E868D7-7046-4E3C-8B4F-AFF7D9F603AD}" ProjectSection(ProjectDependencies) = postProject {E67D3C1A-67CA-4315-918E-ADD2108AC66D} = {E67D3C1A-67CA-4315-918E-ADD2108AC66D} @@ -58,10 +56,6 @@ Global {C8DEE788-A658-4C1F-ACC4-866CDE9315BB}.Debug|Any CPU.Build.0 = Debug|Any CPU {C8DEE788-A658-4C1F-ACC4-866CDE9315BB}.Release|Any CPU.ActiveCfg = Release|Any CPU {C8DEE788-A658-4C1F-ACC4-866CDE9315BB}.Release|Any CPU.Build.0 = Release|Any CPU - {87980F3C-A993-4620-B43A-07A174DB852E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {87980F3C-A993-4620-B43A-07A174DB852E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {87980F3C-A993-4620-B43A-07A174DB852E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {87980F3C-A993-4620-B43A-07A174DB852E}.Release|Any CPU.Build.0 = Release|Any CPU {99E868D7-7046-4E3C-8B4F-AFF7D9F603AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {99E868D7-7046-4E3C-8B4F-AFF7D9F603AD}.Debug|Any CPU.Build.0 = Debug|Any CPU {99E868D7-7046-4E3C-8B4F-AFF7D9F603AD}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -81,7 +75,6 @@ Global GlobalSection(NestedProjects) = preSolution {05A3BD74-8C1B-457B-A85A-35C7B393449E} = {FC756A84-660A-4917-85D0-0BBFB19FF71C} {582890B6-B962-4852-8420-1D7BB68E41E8} = {FC756A84-660A-4917-85D0-0BBFB19FF71C} - {87980F3C-A993-4620-B43A-07A174DB852E} = {FC756A84-660A-4917-85D0-0BBFB19FF71C} {99E868D7-7046-4E3C-8B4F-AFF7D9F603AD} = {FC756A84-660A-4917-85D0-0BBFB19FF71C} {CCE671C2-5FCC-4A5B-8D80-0636A04D2E2D} = {FC756A84-660A-4917-85D0-0BBFB19FF71C} EndGlobalSection diff --git a/src/SdkCommon/Test/ClientRuntime.E2E.Tests/ClientRuntime.E2E.Tests.csproj b/src/SdkCommon/Test/ClientRuntime.E2E.Tests/ClientRuntime.E2E.Tests.csproj index 2a69a64a6134..52d89844ceaf 100644 --- a/src/SdkCommon/Test/ClientRuntime.E2E.Tests/ClientRuntime.E2E.Tests.csproj +++ b/src/SdkCommon/Test/ClientRuntime.E2E.Tests/ClientRuntime.E2E.Tests.csproj @@ -16,15 +16,16 @@ - - + - - + Microsoft.Rest.ClientRuntime.Azure.TestFramework Test framework for Microsoft AutoRest Generated Clients @@ -13,22 +12,30 @@ net452;net461;netcoreapp1.1;netcoreapp2.0 + + + true + + - + + + + - + - + @@ -41,20 +48,19 @@ - + - - + - + - + \ No newline at end of file diff --git a/src/SdkCommon/TestFramework/ClientRuntime.Azure.TestFramework/MockContext.cs b/src/SdkCommon/TestFramework/ClientRuntime.Azure.TestFramework/MockContext.cs index 0a753da6e5a9..8349aa7746dc 100644 --- a/src/SdkCommon/TestFramework/ClientRuntime.Azure.TestFramework/MockContext.cs +++ b/src/SdkCommon/TestFramework/ClientRuntime.Azure.TestFramework/MockContext.cs @@ -6,6 +6,7 @@ using System.Net.Http; using System.Reflection; using Microsoft.Azure.Test.HttpRecorder; +using Microsoft.Azure.Test.HttpRecorder.ProcessRecordings; namespace Microsoft.Rest.ClientRuntime.Azure.TestFramework { @@ -24,11 +25,26 @@ public class MockContext : IDisposable //prevent multiple dispose events protected bool disposed = false; private List undoHandlers = new List(); + private TestEnvironment _testFxEnvironment; static MockContext() { } + internal TestEnvironment TestFxEnvironment + { + get + { + if(_testFxEnvironment == null) + { + string envStr = Environment.GetEnvironmentVariable(TestEnvironmentFactory.TestCSMOrgIdConnectionStringKey); + _testFxEnvironment = new TestEnvironment(envStr); + } + + return _testFxEnvironment; + } + } + /// /// Return a new UndoContext /// @@ -59,7 +75,7 @@ public static MockContext Start( /// A Service client using credentials and base uri from the current environment public T GetServiceClient(bool internalBaseUri = false, params DelegatingHandler[] handlers) where T : class { - return GetServiceClient(TestEnvironmentFactory.GetTestEnvironment(), internalBaseUri, handlers); + return GetServiceClient(TestFxEnvironment, internalBaseUri, handlers); } /// @@ -84,7 +100,8 @@ public T GetGraphServiceClient( bool internalBaseUri = false, params DelegatingHandler[] handlers) where T : class { - return GetGraphServiceClient(TestEnvironmentFactory.GetTestEnvironment(), internalBaseUri, handlers); + //TestFxEnvironment = TestEnvironmentFactory.GetTestEnvironment(); + return GetGraphServiceClient(TestFxEnvironment, internalBaseUri, handlers); } /// @@ -122,7 +139,7 @@ public T GetGraphServiceClient( /// A Service client using credentials and base uri from the current environment public T GetServiceClientWithCredentials(object credentials, params DelegatingHandler[] handlers) where T : class { - return GetServiceClientWithCredentials(TestEnvironmentFactory.GetTestEnvironment(), credentials, handlers: handlers); + return GetServiceClientWithCredentials(TestFxEnvironment, credentials, handlers: handlers); } /// @@ -283,7 +300,17 @@ public void Stop() } } - HttpMockServer.Flush(); + string recordedFilePath = HttpMockServer.Flush(); + + if (HttpMockServer.Mode == HttpRecorderMode.Record) + { + if(TestFxEnvironment.OptimizeRecordedFile == true) + { + ProcessRecordedFiles procRecFile = new ProcessRecordedFiles(recordedFilePath); + procRecFile.CompactLroPolling(); + procRecFile.SerializeCompactData(); + } + } } private static bool MockServerInHandlers(List handlers) diff --git a/src/SdkCommon/TestFramework/ClientRuntime.Azure.TestFramework/TestEnvironment.cs b/src/SdkCommon/TestFramework/ClientRuntime.Azure.TestFramework/TestEnvironment.cs index f1b08f27de75..570986f50dd2 100644 --- a/src/SdkCommon/TestFramework/ClientRuntime.Azure.TestFramework/TestEnvironment.cs +++ b/src/SdkCommon/TestFramework/ClientRuntime.Azure.TestFramework/TestEnvironment.cs @@ -13,6 +13,7 @@ namespace Microsoft.Rest.ClientRuntime.Azure.TestFramework using System.Threading; using System.Threading.Tasks; using Microsoft.IdentityModel.Clients.ActiveDirectory; + using System.ComponentModel; /// /// Test Environment class @@ -69,6 +70,9 @@ public class TestEnvironment /// public IDictionary EnvEndpoints; + [DefaultValue(false)] + public bool OptimizeRecordedFile { get; set; } + /// /// Constructor /// @@ -86,6 +90,7 @@ public TestEnvironment(string connectionString) ConnectionString = new ConnectionString(connectionString); InitTestEndPoints(); + this.OptimizeRecordedFile = this.ConnectionString.GetValue(ConnectionStringKeys.OptimizeRecordedFileKey); this.SubscriptionId = this.ConnectionString.GetValue(ConnectionStringKeys.SubscriptionIdKey); this.UserName = this.ConnectionString.GetValue(ConnectionStringKeys.UserIdKey); this.Tenant = this.ConnectionString.GetValue(ConnectionStringKeys.AADTenantKey); diff --git a/src/SdkCommon/TestFramework/ClientRuntime.Azure.TestFramework/TestEnvironmentFactory.cs b/src/SdkCommon/TestFramework/ClientRuntime.Azure.TestFramework/TestEnvironmentFactory.cs index 3aaeda8a5923..f6b33884d0d6 100644 --- a/src/SdkCommon/TestFramework/ClientRuntime.Azure.TestFramework/TestEnvironmentFactory.cs +++ b/src/SdkCommon/TestFramework/ClientRuntime.Azure.TestFramework/TestEnvironmentFactory.cs @@ -27,6 +27,6 @@ public static TestEnvironment GetTestEnvironment() /// Sample Value 2 - Prompt for login credentials: /// TEST_CSM_ORGID_AUTHENTICATION=SubscriptionId={subscription-id};AADAuthEndpoint=https://login.windows-ppe.net/;BaseUri=https://api-next.resources.windows-int.net/ /// - private const string TestCSMOrgIdConnectionStringKey = "TEST_CSM_ORGID_AUTHENTICATION"; + internal const string TestCSMOrgIdConnectionStringKey = "TEST_CSM_ORGID_AUTHENTICATION"; } } diff --git a/src/SdkCommon/TestFramework/HttpRecorder.Tests/BinaryDataMockServerTests.cs b/src/SdkCommon/TestFramework/HttpRecorder.Tests/BinaryDataMoqServerTests.cs similarity index 97% rename from src/SdkCommon/TestFramework/HttpRecorder.Tests/BinaryDataMockServerTests.cs rename to src/SdkCommon/TestFramework/HttpRecorder.Tests/BinaryDataMoqServerTests.cs index 3feb41fb5db3..81096b1d3425 100644 --- a/src/SdkCommon/TestFramework/HttpRecorder.Tests/BinaryDataMockServerTests.cs +++ b/src/SdkCommon/TestFramework/HttpRecorder.Tests/BinaryDataMoqServerTests.cs @@ -5,14 +5,14 @@ namespace HttpRecorder.BinaryData.Tests { using HttpRecorder.Tests; using HttpRecorder.Tests.DelegatingHandlers; + using HttpRecorder.Tests.MocServerTests; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System.IO; using System.Net.Http; using Xunit; - using HttpRecorder.Tests.MockResponse; - public class BinaryDataMockServerTests : BaseMockServerTest + public class BinaryDataMoqServerTests : MoqServerTestBase { [Fact] public void RecordAndPlayBackAudioData() diff --git a/src/SdkCommon/TestFramework/HttpRecorder.Tests/DelegatingHandlers/LroResponseHandler.cs b/src/SdkCommon/TestFramework/HttpRecorder.Tests/DelegatingHandlers/LroResponseHandler.cs new file mode 100644 index 000000000000..5f3ebaaf6290 --- /dev/null +++ b/src/SdkCommon/TestFramework/HttpRecorder.Tests/DelegatingHandlers/LroResponseHandler.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +namespace HttpRecorder.Tests.DelegatingHandlers +{ + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Net; + using System.Net.Http; + using System.Text; + using System.Threading.Tasks; + + internal class LroResponseHandler : RecordedDelegatingHandler + { + private readonly List _responses; + + private int _counter; + + public List Requests { get; private set; } + + public LroResponseHandler() + { + _responses = new List(); + Requests = new List(); + _counter = 0; + } + + /// + /// + /// + /// + public LroResponseHandler(IEnumerable responses) : + this() + { + _responses.AddRange(responses); + } + + protected override async Task SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) + { + Requests.Add(request); + Debug.Assert(_counter < _responses.Count); + HttpResponseMessage res = _responses[_counter++]; + res.RequestMessage = request; + return await Task.Run(() => { return res; }); + } + } +} diff --git a/src/SdkCommon/TestFramework/HttpRecorder.Tests/HttpRecorder.Tests.csproj b/src/SdkCommon/TestFramework/HttpRecorder.Tests/HttpRecorder.Tests.csproj index aca677e8cdbd..6fb6dfc23c9f 100644 --- a/src/SdkCommon/TestFramework/HttpRecorder.Tests/HttpRecorder.Tests.csproj +++ b/src/SdkCommon/TestFramework/HttpRecorder.Tests/HttpRecorder.Tests.csproj @@ -19,6 +19,7 @@ + @@ -27,8 +28,5 @@ PreserveNewest - - - diff --git a/src/SdkCommon/TestFramework/HttpRecorder.Tests/MockResponse/LROOpertionTestResponses.cs b/src/SdkCommon/TestFramework/HttpRecorder.Tests/MockResponse/LROOpertionTestResponses.cs deleted file mode 100644 index b688a740787f..000000000000 --- a/src/SdkCommon/TestFramework/HttpRecorder.Tests/MockResponse/LROOpertionTestResponses.cs +++ /dev/null @@ -1,2362 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -namespace HttpRecorder.Tests.MockResponse -{ - using System; - using System.Collections.Generic; - using System.Net; - using System.Net.Http; - using System.Text; - - static class LROOpertionTestResponses - { - #region Async Operations - static internal IEnumerable MockLROAsyncOperationFailedWith200() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""location"": ""East US"", - ""etag"": ""9d8d7ed9-7422-46be-82b3-94c5345f6099"", - ""tags"": {}, - ""properties"": { - ""clusterVersion"": ""0.0.1000.0"", - ""osType"": ""Linux"", - ""provisioningState"": ""InProgress"", - ""clusterState"": ""Accepted"", - ""createdDate"": ""2017-07-25T21:48:17.427"", - ""quotaInfo"": - { - ""coresUsed"": ""200"" - }, - } - } - ") - }; - response1.Headers.Add("Azure-AsyncOperation", "https://management.azure.com:090/subscriptions/434c10bb-83d3-6b318c6c7305/resourceGroups/hdisdk1706/providers/Microsoft.HDInsight/clusters/hdisdk-fail/azureasyncoperations/create?api-version=2015-03-01-preview"); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"": ""Failed"", - ""error"": - { - ""code"": ""InvalidDocumentErrorCode"", - ""message"": ""DeploymentDocument 'HiveConfigurationValidator' failed the validation.Error: 'Cannot connect to Hive metastore using user provided connection string'"" - } - } - ") - }; - - yield return response2; - - } - - static internal IEnumerable MockCreateOrUpdateWithTwoTries() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""InProgress"", - ""comment"": ""Resource defined structure"" - } - }") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"" : ""Succeeded"", - ""error"" : { - ""code"": ""BadArgument"", - ""message"": ""The provided database ‘foo’ has an invalid username."" - } - }") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""comment"": ""Resource defined structure"" - } - }") - }; - - yield return response3; - } - - #endregion - - #region Location Headers - static internal IEnumerable MockLROLocationHeaderFailedWith200() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""East US"", - ""etag"": ""9d8d7ed9-7422-46be-82b3-94c5345f6099"", - ""tags"": {}, - ""properties"": { - ""clusterVersion"": ""0.0.1000.0"", - ""osType"": ""Linux"", - ""provisioningState"": ""InProgress"", - ""clusterState"": ""Accepted"", - ""createdDate"": ""2017-07-25T21:48:17.427"", - ""quotaInfo"": - { - ""coresUsed"": ""200"" - }, - } - } - ") - }; - response1.Headers.Add("Location", "https://management.azure.com:090/subscriptions/947c-43bc-83d3-6b318c6c7305/resourceGroups/hdisdk1706/providers/Microsoft.HDInsight/clusters/hdisdk-fail/azureasyncoperations/create?api-version=2015-03-01-preview"); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"": ""Failed"", - ""error"": - { - ""code"": ""InvalidDocumentErrorCode"", - ""message"": ""DeploymentDocument 'HiveConfigurationValidator' failed the validation.Error: 'Cannot connect to Hive metastore using user provided connection string'"" - } - } - ") - }; - - yield return response2; - - } - - static internal IEnumerable MockLROLocHdrNonStandardTerminalStatus() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""East US"", - ""etag"": ""9d8d7ed9-7422-46be-82b3-94c5345f6099"", - ""tags"": {}, - ""properties"": { - ""clusterVersion"": ""0.0.1000.0"", - ""osType"": ""Linux"", - ""provisioningState"": ""InProgress"", - ""clusterState"": ""Accepted"", - ""createdDate"": ""2017-07-25T21:48:17.427"", - ""quotaInfo"": - { - ""coresUsed"": ""200"" - }, - } - } - ") - }; - response1.Headers.Add("Location", "https://management.azure.com:090/subscriptions/56b5e0a9-b645-407d-99b0-c64f86013e3d/resourcegroups/sjrg8116/providers/Microsoft.StreamAnalytics/streamingjobs/sj3215/functions/function5403/OperationResults/f5dca005-e2ba-47d7-bf6e-4b3276e6bff9"); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"": ""TestFailed"", - ""error"": - { - ""code"": ""BadRequest"", - ""message"": ""DeploymentDocument 'HiveConfigurationValidator' failed the validation.Error: 'Cannot connect to Hive metastore using user provided connection string'"", - ""details"": null - } - } - ") - }; - - yield return response2; - - } - - static internal IEnumerable MockCreateOrUpdateWithLocationHeaderAnd202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("null") - }; - response1.Headers.Add("Location", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - response2.Headers.Add("Location", "http://custom/locationstatus"); - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - response3.Headers.Add("Location", "https://management.azure.com/subscriptions/1234/resourceGroups/rg/providers/Microsoft.Cache/Redis/redis"); - - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""comment"": ""Resource defined structure"" - } - }") - }; - - yield return response4; - } - #region Provisioning States - static internal IEnumerable MockAsyncOperaionWithMissingProvisioningState() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - response1.Headers.Add("Location", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("null") - }; - response2.Headers.Add("Location", "http://custom/status2"); - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("{ \"properties\": { }, \"id\": \"100\", \"name\": \"foo\" }") - }; - - yield return response3; - } - #endregion - - #endregion - - #region Provisioning States - internal static IEnumerable Location201FinalGet404WithEmptyStringProviState() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Location", @"https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/RedisCreateUpdate2536/providers/Microsoft.Cache/redis/RedisCreateUpdate9076?api-version=2017-10-01"); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Deleting"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": null, - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.NotFound) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - - internal static IEnumerable Location201FinalGet404WithEmptyProviState() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Location", @"https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/RedisCreateUpdate2536/providers/Microsoft.Cache/redis/RedisCreateUpdate9076?api-version=2017-10-01"); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Deleting"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": """", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.NotFound) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - - internal static IEnumerable Location201FinalGet404WithNoValueProviState() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Location", @"https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/RedisCreateUpdate2536/providers/Microsoft.Cache/redis/RedisCreateUpdate9076?api-version=2017-10-01"); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Deleting"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": , - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.NotFound) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - - internal static IEnumerable Location201FinalGet404WithNullStringProviState() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Location", @"https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/RedisCreateUpdate2536/providers/Microsoft.Cache/redis/RedisCreateUpdate9076?api-version=2017-10-01"); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Deleting"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": NULL, - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.NotFound) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - - internal static IEnumerable Location201FinalGet404WithMissingProviState() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Location", @"https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/RedisCreateUpdate2536/providers/Microsoft.Cache/redis/RedisCreateUpdate9076?api-version=2017-10-01"); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Deleting"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.NotFound) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - - #endregion - - #region PUT responses - static internal IEnumerable MockPutOperaionWithoutProvisioningStateInResponse() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent("{ \"properties\": { }, \"id\": \"100\", \"name\": \"foo\" }") - }; - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("{ \"properties\": { }, \"id\": \"100\", \"name\": \"foo\" }") - }; - yield return response2; - } - - static internal IEnumerable MockLROPUTWithCanceledStateResponse() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - { - ""properties"": { }, - ""id"": ""100"", - ""name"": ""foo"" - }") - }; - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"": ""Canceled"", - ""error"": - { - ""code"": ""OperationPreempted"", - ""message"": ""The operation has been preempted by a more recent operation"" - } - }" - - ) - }; - yield return response2; - } - - #endregion - - #region Retry-After - - static internal IEnumerable MockDeleteWithRetryAfterTwoTries() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@"") - }; - response1.Headers.Add("Location", "http://custom/location/status"); - response1.Headers.Add("Retry-After", "3"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@"") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.NoContent) - { - Content = new StringContent(@"") - }; - - yield return response3; - } - - static internal IEnumerable MockPatchWithRetryAfterTwoTries() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@"") - }; - response1.Headers.Add("Location", "http://custom/location/status"); - response1.Headers.Add("Retry-After", "3"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("{ \"properties\": { }, \"id\": \"100\", \"name\": \"foo\" }") - }; - - yield return response2; - } - - static internal IEnumerable MockCreateOrUpdateWithDifferentRetryAfterValues() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""InProgerss"", - ""comment"": ""Resource defined structure"" - } - }") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - response1.Headers.Add("Retry-After", "2"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"" : ""InProgerss"", - ""properties"": { - ""provisioningState"": ""InProgerss"", - ""comment"": ""Resource getting created"" - } - }") - }; - response2.Headers.Add("Retry-After", "5"); - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"" : ""Succeeded"", - ""properties"": { - ""id"": ""100"", - ""name"": ""foo"" - } - }") - }; - - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"" : ""Succeeded"", - ""properties"": { - ""id"": ""100"", - ""name"": ""foo"" - } - }") - }; - - yield return response4; - } - - static internal IEnumerable MockCreateWithRetryAfterDefaultMin() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@"") - }; - response1.Headers.Add("Location", "http://custom/location/status"); - response1.Headers.Add("Retry-After", "0"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("{ \"properties\": { }, \"id\": \"100\", \"name\": \"foo\" }") - }; - - yield return response2; - } - - static internal IEnumerable MockCreateWithRetryAfterDefaultMax() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@"") - }; - response1.Headers.Add("Location", "http://custom/location/status"); - response1.Headers.Add("Retry-After", "50"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("{ \"properties\": { }, \"id\": \"100\", \"name\": \"foo\" }") - }; - - yield return response2; - } - #endregion - - #region other LRO tests - static internal IEnumerable MockCreateOrUpdateWithoutHeaderInResponses() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""InProgress"", - ""comment"": ""Resource defined structure"" - } - }") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"" : ""InProgress"", - ""error"" : { - ""code"": ""BadArgument"", - ""message"": ""The provided database ‘foo’ has an invalid username."" - } - }") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"" : ""Succeeded"", - ""error"" : { - ""code"": ""BadArgument"", - ""message"": ""The provided database ‘foo’ has an invalid username."" - } - }") - }; - - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""comment"": ""Resource defined structure"" - } - }") - }; - - yield return response4; - } - - static internal IEnumerable MockAsyncOperaionWithNoBody() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""InProgress"", - ""comment"": ""Resource defined structure"" - } - }") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("") - }; - - yield return response2; - } - - static internal IEnumerable MockAsyncOperaionWithEmptyBody() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("{}") - }; - - yield return response2; - } - - static internal IEnumerable MockAsyncOperaionWithNullBody() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = null - }; - - yield return response2; - } - - static internal IEnumerable MockAsyncOperaionWithBadPayload() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - response1.Headers.Add("Location", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("null") - }; - response2.Headers.Add("Location", "http://custom/status2"); - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("{ \"properties\": { \"provisioningState\" : \"Succeeded\" }, \"id\": \"100\", \"name\": \"foo\" }") - }; - - yield return response3; - } - - static internal IEnumerable MockAsyncOperaionWithNonSuccessStatusAndInvalidResponseContent() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - response1.Headers.Add("Location", "http://custom/status"); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.BadRequest) - { - Content = new StringContent("<") - }; - yield return response2; - } - - static internal IEnumerable MockPutOperaionWitNonResource() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("null") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""status"" : ""Succeeded"", - ""error"" : { - ""code"": ""BadArgument"", - ""message"": ""The provided database ‘foo’ has an invalid username."" - } - }") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""name"": ""foo"" - }") - }; - - yield return response3; - } - - static internal IEnumerable MockPutOperaionWitSubResource() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""properties"": { - ""provisioningState"": ""InProgress"" - }, - ""id"": ""100"", - ""name"": ""foo"" - } - }") - }; - response1.Headers.Add("Location", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""100"" - }") - }; - - yield return response3; - } - - static internal IEnumerable MockPutOperaionWithImmediateSuccess() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("{ \"properties\": { \"provisioningState\": \"Succeeded\"}, \"id\": \"100\", \"name\": \"foo\" }") - }; - - yield return response1; - } - - static internal IEnumerable MockOperaionWithImmediateSuccessOKStatus() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("") - }; - - yield return response1; - } - - static internal IEnumerable MockPostOperaionWithImmediateSuccessOKStatus() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("{\"Capacity\":1,\"Family\":\"Family\"}") - }; - - yield return response1; - } - - static internal IEnumerable MockOperaionWithImmediateSuccessNoContentStatus() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("") - }; - - yield return response1; - } - - static internal IEnumerable MockPostOperaionWithBody() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - response1.Headers.Add("Location", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("{ \"properties\": { \"provisioningState\": \"Succeeded\"}, \"id\": \"100\", \"name\": \"foo\" }") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.NoContent) - { - Content = new StringContent(@" - { - ""name"": ""FooBar"" - }") - }; - yield return response3; - } - - static internal IEnumerable MockDeleteOperaionWithNoRetryableErrorInResponse() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - response1.Headers.Add("Location", "http://custom/status"); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.BadRequest) - { - Content = new StringContent("") - }; - yield return response2; - } - - static internal IEnumerable MockDeleteOperaionWithoutHeaderInResponse() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"" : ""InProgress"", - ""error"" : { - ""code"": ""BadArgument"", - ""message"": ""The provided database ‘foo’ has an invalid username."" - } - }") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"" : ""Succeeded"", - ""error"" : { - ""code"": ""BadArgument"", - ""message"": ""The provided database ‘foo’ has an invalid username."" - } - }") - }; - yield return response3; - } - - static internal IEnumerable MockDeleteOperaionWithoutLocationHeaderInResponse() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - response1.Headers.Add("Location", "http://custom/status"); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.NoContent) - { - Content = new StringContent("") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.NoContent) - { - Content = new StringContent("") - }; - yield return response4; - } - - static internal IEnumerable MockCreateOrUpdateWithAsyncHeaderAnd202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("null") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""status"" : ""Succeeded"", - ""error"" : { - ""code"": ""BadArgument"", - ""message"": ""The provided database ‘foo’ has an invalid username."" - } - }") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""InProgress"", - ""comment"": ""Resource defined structure"" - } - }") - }; - - yield return response3; - } - - static internal IEnumerable MockCreateOrUpdateWithWith202AndResource() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("null") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""status"" : ""Succeeded"", - ""error"" : { - ""code"": ""BadArgument"", - ""message"": ""The provided database ‘foo’ has an invalid username."" - } - }") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""comment"": ""Resource defined structure"" - } - }") - }; - - yield return response3; - } - - static internal IEnumerable MockPostWithResourceSku() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("null") - }; - response1.Headers.Add("Location", "http://custom/status"); - - yield return response1; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""Capacity"": ""1"", - ""Family"": ""Family"" - }") - }; - - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""Capacity"": ""1"", - ""Family"": ""Family"" - }") - }; - yield return response4; - } - - static internal IEnumerable MockCreateOrUpdateWithNoAsyncHeader() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""InProgress"", - ""comment"": ""Resource defined structure"" - } - }") - }; - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""Anything other than Succeeded"", - ""comment"": ""Resource defined structure"" - } - }") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""comment"": ""Resource defined structure"" - } - }") - }; - - yield return response3; - } - - static internal IEnumerable MockCreateOrUpdateWithFailedStatus() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""InProgress"", - ""comment"": ""Resource defined structure"" - } - }") - }; - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""Anything other than Succeeded"", - ""comment"": ""Resource defined structure"" - } - }") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""Failed"", - ""comment"": ""Resource defined structure"" - } - }") - }; - - yield return response3; - } - - static internal IEnumerable MockCreateOrUpdateWithImmediateServerError() - { - var response1 = new HttpResponseMessage(HttpStatusCode.InternalServerError) - { - Content = new StringContent(@" - { - ""error"": { - ""code"": ""BadArgument"", - ""message"": ""The provided database ‘foo’ has an invalid username."", - ""target"": ""query"", - ""details"": [ - { - ""code"": ""301"", - ""target"": ""$search"", - ""message"": ""$search query option not supported"" - } - ] - } - }") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - - yield return response1; - } - - static internal IEnumerable MockCreateOrUpdateWithNoErrorBody() - { - var response1 = new HttpResponseMessage(HttpStatusCode.InternalServerError) - { - Content = new StringContent(@"") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - - yield return response1; - } - - static internal IEnumerable MockCreateOrUpdateWithRetryAfterTwoTries() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""InProgress"", - ""comment"": ""Resource defined structure"" - } - }") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - response1.Headers.Add("Retry-After", "2"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"" : ""Succeeded"", - ""error"" : { - ""code"": ""BadArgument"", - ""message"": ""The provided database ‘foo’ has an invalid username."" - } - }") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""tags"": { - ""key1"": ""value 1"", - ""key2"": ""value 2"" - }, - - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""comment"": ""Resource defined structure"" - } - }") - }; - - yield return response3; - } - - static internal IEnumerable MockDeleteWithAsyncHeaderTwoTries() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@"") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"" : ""Succeeded"", - ""error"" : { - ""code"": ""BadArgument"", - ""message"": ""The provided database ‘foo’ has an invalid username."" - } - }") - }; - - yield return response2; - } - - static internal IEnumerable MockDeleteWithLocationHeaderTwoTries() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@"") - }; - response1.Headers.Add("Location", "http://custom/location/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@"") - }; - - yield return response2; - - var response4 = new HttpResponseMessage(HttpStatusCode.NotFound) - { - Content = new StringContent("") - }; - yield return response4; - } - - static internal IEnumerable MockDeleteWithLocationHeaderError() - { - var response1 = new HttpResponseMessage(HttpStatusCode.InternalServerError) - { - Content = new StringContent(@"") - }; - response1.Headers.Add("Location", "http://custom/location/status"); - - yield return response1; - } - - static internal IEnumerable MockDeleteWithLocationHeaderErrorInSecondCall() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@"") - }; - response1.Headers.Add("Location", "http://custom/location/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.InternalServerError) - { - Content = new StringContent(@"") - }; - - yield return response2; - } - - static internal IEnumerable MockPutWebAppLRO() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - { - ""id"":""/subscriptions/ffa52f27-be12-b1ea-c2c1b6cceb/resourceGroups/rgnemv_bef11205b7b0/providers/Microsoft.Web/sites/webapp1-35965806af0/sourcecontrols/web"", - ""name"":""webapp1-35965806af0"", - ""type"":""Microsoft.Web/sites/sourcecontrols"", - ""location"":""West US 2"", - ""tags"":{}, - ""properties"": - { - ""repoUrl"":""https://github.com/foo/azure-site-test"", - ""branch"":""master"", - ""isManualIntegration"":true, - ""deploymentRollbackEnabled"":false, - ""isMercurial"":false, - ""provisioningState"":""InProgress"" - } - }") - }; - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - { - ""id"":""/subscriptions/ffa52f27-be12-4cad-b1ea/resourceGroups/rgnemv_bef11205b7b0/providers/Microsoft.Web/sites/webapp1-35965806af0/sourcecontrols/web"", - ""name"":""webapp1-35965806af0"", - ""type"":""Microsoft.Web/sites/sourcecontrols"", - ""location"":""West US 2"", - ""tags"":{}, - ""properties"": - { - ""repoUrl"":""https://github.com/foo/azure-site-test"", - ""branch"":""master"", - ""isManualIntegration"":true, - ""deploymentRollbackEnabled"":false, - ""isMercurial"":false, - ""provisioningState"":""InProgress"", - ""provisioningDetails"":""2017-08-25T05:49:50.0340330 https://webapp1-359658.azurewebsites.net/api/deployments/latest?deployer=GitHub&time=2017-08-25_05-49-23"" - } - } - ") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"":""/subscriptions/ffa52f27-be12-4cad-b1ea-c2c241b6cceb/resourceGroups/rgnemv_bef11205b7b0/providers/Microsoft.Web/sites/webapp1-35965806af0"", - ""name"":""webapp1-35965806af0"", - ""type"":""Microsoft.Web/sites"", - ""kind"":""app"", - ""location"":""West US 2"", - ""tags"":{}, - ""properties"": - { - ""name"":""webapp1-35965806af0"", - ""state"":""Running"", - ""hostNames"":[""webapp1-35965806af0.jsdkdemo-62e18289a.com"", - ""webapp1-35965806af0.azurewebsites.net""], - ""webSpace"":""rgnemv_bef11205b7b0-WestUS2webspace"", - ""selfLink"":""https://waws.api.azurewebsites.windows.net/subscriptions/ffa52f27-b1ea-c2c241b6cceb/webspaces/rgnemv_bef11205b7b0-WestUS2webspace/sites/webapp1-35965806af0"", - ""repositorySiteName"":""webapp1-35965806af0"", - ""owner"":null, - ""usageState"":""Normal"", - ""enabled"":true, - ""adminEnabled"":true, - ""enabledHostNames"":[""webapp1-35965806af0.jsdkdemo-62e18289a.com"", - ""webapp1-35965806af0.azurewebsites.net"", - ""webapp1-35965806af0.scm.azurewebsites.net""], - ""siteProperties"":{""metadata"":null, - ""properties"":[], - ""appSettings"":null}, - ""availabilityState"":""Normal"", - ""sslCertificates"":null, - ""csrs"":[], - ""cers"":null, - ""siteMode"":null, - ""hostNameSslStates"":[ - { - ""name"":""webapp1-35965806af0.azurewebsites.net"", - ""sslState"":""Disabled"", - ""ipBasedSslResult"":null, - ""virtualIP"":null, - ""thumbprint"":null, - ""toUpdate"":null, - ""toUpdateIpBasedSsl"":null, - ""ipBasedSslState"":""NotConfigured"", - ""hostType"":""Standard"" - }, - { - ""name"":""webapp1-35965806af0.jsdkdemo-62e18289a.com"", - ""sslState"":""SniEnabled"", - ""ipBasedSslResult"":null, - ""virtualIP"":null, - ""thumbprint"":""40ECC6C60434CF"", - ""toUpdate"":null, - ""toUpdateIpBasedSsl"":null, - ""ipBasedSslState"":""NotConfigured"", - ""hostType"":""Standard"" - }, - { - ""name"":""webapp.scm.azurewebsites.net"", - ""sslState"":""Disabled"", - ""ipBasedSslResult"":null, - ""virtualIP"":null, - ""thumbprint"":null, - ""toUpdate"":null, - ""toUpdateIpBasedSsl"":null, - ""ipBasedSslState"":""NotConfigured"", - ""hostType"":""Repository"" - }], - ""computeMode"":null, - ""serverFarm"":null, - ""serverFarmId"":""/subscriptions/ffa52f27-b1ea-c2c241b6cceb/resourceGroups/rgnemv_bef11205b7b0/providers/Microsoft.Web/serverfarms/jplan1_73a739850"", - ""reserved"":false, - ""lastModifiedTimeUtc"":""2017-08-25T05:48:34.92"", - ""storageRecoveryDefaultState"":""Running"", - ""contentAvailabilityState"":""Normal"", - ""runtimeAvailabilityState"":""Normal"", - ""siteConfig"":null, - ""deploymentId"":""webapp1-35965806af0"", - ""trafficManagerHostNames"":null, - ""sku"":""Basic"", - ""scmSiteAlsoStopped"":false, - ""targetSwapSlot"":null, - ""hostingEnvironment"":null, - ""hostingEnvironmentProfile"":null, - ""clientAffinityEnabled"":true, - ""clientCertEnabled"":false, - ""hostNamesDisabled"":false, - ""domainVerificationIdentifiers"":null, - ""kind"":""app"", - ""outboundIpAddresses"":""93.99.231.000,62.66.007.111,36.36.261.144,93.93.282.10"", - ""possibleOutboundIpAddresses"":""93.99.231.000,62.66.007.111,36.36.261.144,93.93.282.10"", - ""containerSize"":0, - ""dailyMemoryTimeQuota"":0, - ""suspendedTill"":null, - ""siteDisabledReason"":0, - ""functionExecutionUnitsCache"":null, - ""maxNumberOfWorkers"":null, - ""homeStamp"":""waws-wch237-003"", - ""cloningInfo"":null, - ""hostingEnvironmentId"":null, - ""tags"":{}, - ""resourceGroup"":""rgnemv_bef11205b7b0"", - ""defaultHostName"":""webapp1-35965806af0.azurewebsites.net"", - ""slotSwapStatus"":null - } - } - ") - }; - - yield return response3; - } - #endregion - } - - static class LROOperationPatchTestResponses - { - static internal IEnumerable ServiceCustomResponse() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - { - ""properties"": { - ""topic"": ""/subscriptions/76fc5-4d01-b462-9f01b2d77/resourceGroups/rg-76fce8d7-1205-4d01-b462-9f01b2d70f67/providers/microsoft.eventgrid/topics/topic-76fce8d7-1205-4d01-b462-9f01b2d70f67"", - ""provisioningState"": ""Updating"", - ""destination"": { - ""properties"": { - ""endpointUrl"": null, - ""endpointBaseUrl"": ""https://subscriber-76fce8d7-1205-4d01-b462-9f01b2d70f67.eventgrid-int.azure.net:782/"" - }, - ""endpointType"": ""WebHook"" - }, - ""filter"": { - ""subjectBeginsWith"": """", - ""subjectEndsWith"": """", - ""includedEventTypes"": [ ""All"" ] - }, - ""labels"": null - }, - ""id"": ""/subscriptions/76fc5-4d01-b462-9f01b2d77/resourceGroups/rg-76fce8d7-12d01-b462-9f01b2d70f67/providers/Microsoft.EventGrid/topics/topic-76fce8d7-1205-4d01-b462-9f01b2d70f67/providers/Microsoft.EventGrid/eventSubscriptions/subscription-8da8b80f-a198-42f0-af01-99bc0c08d563"", - ""name"": ""subscription-8da8b80f-a198-42f0-af01-99bc0c08d563"", - ""type"": ""Microsoft.EventGrid/eventSubscriptions"" - }") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"": ""Succeeded"", - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""state"": ""Active"" - } - } - ") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""34adfa4f-cedf-4dc0-ba29-b6d1a69ab345"", - ""name"": ""test_account"", - ""type"": ""test_type"", - ""location"": ""test_location"", - ""tags"": { - ""test_key"": ""test_value"" - } - } - ") - }; - yield return response3; - - } - static internal IEnumerable MockPatchWithAzureAsyncOperationHeader() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - { - ""id"": ""34adfa4f-cedf-4dc0-ba29-b6d1a69ab345"", - ""name"": ""test_account"", - ""type"": ""test_type"", - ""location"": ""test_location"", - ""tags"": { - ""test_key"": ""test_value"" - }, - ""properties"": { - ""provisioningState"": ""InProgress"", - ""state"": ""InActive"" - } - }") - }; - response1.Headers.Add("Azure-AsyncOperation", "http://custom/status"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"": ""Succeeded"", - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""state"": ""Active"" - } - } - ") - }; - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""34adfa4f-cedf-4dc0-ba29-b6d1a69ab345"", - ""name"": ""test_account"", - ""type"": ""test_type"", - ""location"": ""test_location"", - ""tags"": { - ""test_key"": ""test_value"" - } - } - ") - }; - yield return response3; - } - - static internal IEnumerable MockPatchWithLocationHeader() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""id"": ""34adfa4f-cedf-4dc0-ba29-b6d1a69ab345"", - ""name"": ""test_account"", - ""type"": ""test_type"", - ""location"": ""test_location"", - ""tags"": { - ""test_key"": ""test_value"" - }, - ""properties"": { - ""provisioningState"": ""InProgress"", - ""state"": ""InActive"" - } - }") - }; - response1.Headers.Add("Location", "https://management.azure.com:090/subscriptions/947c-43bc-83d3-6b318c6c7305/resourceGroups/hdisdk1706/providers/Microsoft.HDInsight/clusters/hdisdk-fail/azureasyncoperations/create?api-version=2015-03-01-preview"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"": ""Succeeded"", - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""state"": ""Active"" - } - } - ") - }; - - yield return response2; - } - } - - static class LROOperationFailedTestResponses - { - static internal IEnumerable MockLROAsyncOperationFailedOnlyStatus() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""location"": ""East US"", - ""etag"": ""9d8d7ed9-7422-46be-82b3-94c5345f6099"", - ""tags"": {}, - ""properties"": { - ""clusterVersion"": ""0.0.1000.0"", - ""osType"": ""Linux"", - ""provisioningState"": ""InProgress"", - ""clusterState"": ""Accepted"", - ""createdDate"": ""2017-07-25T21:48:17.427"", - ""quotaInfo"": - { - ""coresUsed"": ""200"" - }, - } - } - ") - }; - //response1.Headers.Add("Azure-AsyncOperation", "https://management.azure.com:090/subscriptions/434c10bb-83d3-6b318c6c7305/resourceGroups/hdisdk1706/providers/Microsoft.HDInsight/clusters/hdisdk-fail/azureasyncoperations/create?api-version=2015-03-01-preview"); - response1.Headers.Add("Location", "https://management.azure.com:090/subscriptions/947c-43bc-83d3-6b318c6c7305/resourceGroups/hdisdk1706/providers/Microsoft.HDInsight/clusters/hdisdk-fail/azureasyncoperations/create?api-version=2015-03-01-preview"); - - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@"{}") - }; - yield return response2; - - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@"'https://mdsbrketwprodsn1prod.blob.core.windows.net/cmakexe/abbd1dc4-44eb-4a66-9d90-156f7e5191a7/vpnclientconfiguration.zip?sv=2015-04-05&sr=b&sig=Ec6g2tlP0xktQSipQCTO55mnNjwOxTsge4Ot3sjX8Z8%3D&st=2017-08-28T21%3A25%3A34Z&se=2017-08-28T22%3A25%3A34Z&sp=r&fileExtension=.zip'") - - // Content = new StringContent(@" - // { - // ""https://mdsbrketwprodsn1prod.blob.core.windows.net/cmakexe/abbd1dc4-44eb-4a66-9d90-156f7e5191a7/vpnclientconfiguration.zip?sv=2015-04-05&sr=b&sig=Ec6g2tlP0xktQSipQCTO55mnNjwOxTsge4Ot3sjX8Z8%3D&st=2017-08-28T21%3A25%3A34Z&se=2017-08-28T22%3A25%3A34Z&sp=r&fileExtension=.zip"" - // } - //") - }; - - yield return response3; - - } - } - - static class LROOperationMultipleHeaderResponses - { - static internal IEnumerable MockLROLocationHeaderAndAsyncOperation() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""location"": ""East US"", - ""etag"": ""9d8d7ed9-7422-46be-82b3-94c5345f6099"", - ""tags"": {}, - ""properties"": { - ""clusterVersion"": ""0.0.1000.0"", - ""osType"": ""Linux"", - ""provisioningState"": ""InProgress"", - ""clusterState"": ""Accepted"", - ""createdDate"": ""2017-07-25T21:48:17.427"", - ""quotaInfo"": - { - ""coresUsed"": ""200"" - }, - } - } - ") - }; - response1.Headers.Add("Location", "https://management.azure.com:090/subscriptions/947c-43bc-83d3-6b3186c7305/resourceGroups/hdisdk106/providers/Microsoft.HDInsight/clusters/hdisdk-fail/azureasyncoperations/create?api-version=2015-03-01-preview"); - - yield return response1; - - // Even if Async-Operation header is passed, but initially LocationHeader was used - // we cache it and use it because for 202, we prefere Location header over Async-Operation - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""id"": ""100"", - ""name"": ""foo"", - ""properties"": { - ""provisioningState"": ""InProgress"" - } - }") - }; - response2.Headers.Add("Azure-AsyncOperation", "http://custom/AsyncOperation"); - response2.Headers.Add("Retry-After", "12"); - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""status"": ""Succeeded"", - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""state"": ""Active"" - } - }") - }; - - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""North US"", - ""id"": ""100"" - }") - }; - - yield return response4; - } - - - /// - /// DELETE operatoin with multiple operations with 202 - /// Location is passed in the first round - /// AsyncOperaiton header is passed in the second round - /// This will enable to finish the polling using AsyncOperaiton after second round - /// - /// It will finally use Location header to do final GET and will succeed - /// - /// - static internal IEnumerable MockLRO_DeleteSuccessWithLocationHeaderFinalGetNotFound() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""location"": ""East US"", - ""etag"": ""9d8d7ed9-7422-46be-82b3-94c5345f6099"", - ""tags"": {}, - ""properties"": { - ""clusterVersion"": ""0.0.1000.0"", - ""osType"": ""Linux"", - ""provisioningState"": ""InProgress"", - ""clusterState"": ""Accepted"", - ""createdDate"": ""2017-07-25T21:48:17.427"", - ""quotaInfo"": - { - ""coresUsed"": ""200"" - }, - } - } - ") - }; - response1.Headers.Add("Location", "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/operationresults/eyJqb2JJZCI6IlJFU09VUkNFR1JPVVBERUxFVElPTkpPQi1DUlBURVNUQVI3ODkxLVNPVVRIRUFTVEFTSUEiLCJqb2JMb2NhdGlvbiI6InNvdXRoZWFzdGFzaWEifQ?api-version=2017-05-10"); - response1.Headers.Add("Retry-After", "5"); - yield return response1; - - // Even if Async-Operation header is passed, but initially LocationHeader was used - // we cache it and use it because for 202, we prefere Location header over Async-Operation - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - //response2.Headers.Add("Azure-AsyncOperation", "https://management.azure.com/subscriptions/24fb23e3-6ba3-41f0-9b6e-e41131d5d61e/providers/Microsoft.Compute/locations/southeastasia/DiskOperations/a467a7f3-d2e3-493c-9996-9b212a941154?api-version=2017-03-30"); - //response2.Headers.Add("Retry-After", "12"); - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("") - }; - - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.NotFound) - { - Content = new StringContent(@"") - }; - - yield return response4; - } - - /// - /// Delete with location header. - /// Final GET returns NoContent - /// - /// - static internal IEnumerable MockLRO_DeleteSuccessWithLocationHeaderFinalGetNoContent() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - response1.Headers.Add("Location", "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/operationresults/eyJqb2JJZCI6IlJFU09VUkNFR1JPVVBERUxFVElPTkpPQi1DUlBURVNUQVI3ODkxLVNPVVRIRUFTVEFTSUEiLCJqb2JMb2NhdGlvbiI6InNvdXRoZWFzdGFzaWEifQ?api-version=2017-05-10"); - response1.Headers.Add("Retry-After", "5"); - yield return response1; - - // Even if Async-Operation header is passed, but initially LocationHeader was used - // we cache it and use it because for 202, we prefere Location header over Async-Operation - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - //response2.Headers.Add("Azure-AsyncOperation", "https://management.azure.com/subscriptions/24fb23e3-6ba3-41f0-9b6e-e41131d5d61e/providers/Microsoft.Compute/locations/southeastasia/DiskOperations/a467a7f3-d2e3-493c-9996-9b212a941154?api-version=2017-03-30"); - //response2.Headers.Add("Retry-After", "12"); - - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("") - }; - - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.NoContent) - { - Content = new StringContent(@"") - }; - - yield return response4; - } - - /// - /// Pass Azure-async header as well as location header. - /// - /// - static internal IEnumerable MockLRO_POST_LocAsyncHeaderFinalGetSuccess() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent("") - }; - response1.Headers.Add("Azure-AsyncOperation", "https://management.azure.com/subscriptions/24fb23e3-6ba3-41f0-9b6e-e41131d5d61e/providers/Microsoft.Compute/locations/southeastasia/DiskOperations/a467a7f3-d2e3-493c-9996-9b212a941154?api-version=2017-03-30"); - //response1.Headers.Add("Retry-After", "5"); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T16:03:10.266925-08:00"", - ""status"": ""InProgress"", - ""name"": ""ef936d96-9f17-4226-b6ea-0d8590f7bdb5"" - }") - }; - response2.Headers.Add("Location", "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/providers/Microsoft.Compute/locations/southeastasia/operations/ef936d96-9f17-4226-b6ea-0d8590f7bdb5?monitor=true&api-version=2017-12-01"); - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T16:03:10.266925-08:00"", - ""status"": ""InProgress"", - ""name"": ""ef936d96-9f17-4226-b6ea-0d8590f7bdb5"" - }") - }; - - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T16:03:10.266925-08:00"", - ""endTime"": ""2018-02-08T16:04:25.3955911-08:00"", - ""status"": ""Succeeded"", - ""name"": ""ef936d96-9f17-4226-b6ea-0d8590f7bdb5"" - }") - }; - - yield return response4; - - var response5 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""name"": ""foo"" - }") - }; - - yield return response5; - } - } -} diff --git a/src/SdkCommon/TestFramework/HttpRecorder.Tests/MockResponse/LroRulesResponses.cs b/src/SdkCommon/TestFramework/HttpRecorder.Tests/MockResponse/LroRulesResponses.cs deleted file mode 100644 index db66f09f48cb..000000000000 --- a/src/SdkCommon/TestFramework/HttpRecorder.Tests/MockResponse/LroRulesResponses.cs +++ /dev/null @@ -1,2936 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -namespace HttpRecorder.Tests.MockResponse -{ - using System; - using System.Collections.Generic; - using System.Net; - using System.Net.Http; - using System.Text; - - /// - /// - /// - public class LroRules - { - /// - /// - /// - public class PUTResponses - { - #region const - /// - /// - /// - public const string status201_AzureAsyncOperationHeaderUrl = @"https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/providers/Microsoft.ContainerService/locations/australiasoutheast/operations/0adae43a-6224-4e9b-9452-89809d7e41f5?api-version=2017-01-31"; - - /// - /// - /// - public const string status201_LocationHeaderUrl = @"https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/RedisCreateUpdate2536/providers/Microsoft.Cache/redis/RedisCreateUpdate9076?api-version=2017-10-01"; - - /// - /// - /// - public const string status202_AzureAsyncOperationHeaderUrl = @"https://management.azure.com/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/providers/Microsoft.Compute/locations/westcentralus/DiskOperations/2e1f6b10-a489-466c-a471-934f5271e918?api-version=2017-03-30"; - - /// - /// - /// - public const string status202_LocationHeaderUrl = @"https://management.azure.com/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/providers/Microsoft.Compute/locations/westcentralus/DiskOperations/2e1f6b10-a489-466c-a471-934f5271e918?monitor=true&api-version=2017-03-30"; - //"https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/providers/Microsoft.Storage/locations/southeastasia/asyncoperations/45bc1627-1cc1-4df7-9209-56f9a77bc04e?monitor=true&api-version=2015-06-15" - - /// - /// - /// - public const string AltLocationHeaderUrl = @"https://custom.com"; - #endregion - - #region Case 1 (201 + Azure-AsyncOperation Header) - internal static IEnumerable AzAsync201() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Creating"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""SomeKeyData"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": ""true"" - } - } - } - } - ") - }; - response1.Headers.Add("Azure-AsyncOperation", status201_AzureAsyncOperationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", - ""status"": ""InProgress"", - ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", - ""endTime"": ""2018-02-08T17: 24: 28.3142823-08: 00"", - ""status"": ""Succeeded"", - ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""fqdn"": ""mdp8680.australiasoutheast.cloudapp.azure.com"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""fqdn"": ""apdp2498.australiasoutheast.cloudapp.azure.com"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": true, - ""storageUri"": ""https:\/\/anh36lyni2ra2diag0.blob.core.windows.net/"" - } - } - } - } - ") - }; - yield return response4; - } - - #endregion - - #region Case 2 (201 + Location Header) - internal static IEnumerable Location201() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - { - ""ResponseOrder"": ""1"", - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Creating"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": { - ""primaryKey"": ""e77DIxNC9kfKnAH0imMFNILFHSCW6BinwFGvHvpOj5U="", - ""secondaryKey"": ""NVzdWjgyhvoOjETlvj5JN+vK8qTXjqGUGYxpfguB8cM="" - }, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - response1.Headers.Add("Location", status201_LocationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""ResponseOrder"": ""2"", - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Creating"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""ResponseOrder"": ""3"", - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""tenantSettings"": { - ""InternalDependencyList"": [ - { - ""Type"": ""StorageBlob"", - ""Value"": ""https://wcus2554052479.blob.core.windows.net/"" - }, - { - ""Type"": ""StorageQueue"", - ""Value"": ""https://wcus2554052479.queue.core.windows.net/"" - }, - { - ""Type"": ""StorageBlob"", - ""Value"": ""https://wcusscaleunit5435222359.blob.core.windows.net/"" - }, - { - ""Type"": ""StorageQueue"", - ""Value"": ""https://wcusscaleunit5435222359.queue.core.windows.net"" - }, - { - ""Type"": ""StorageBlob"", - ""Value"": ""https://wcusgenevasa834343247016.blob.core.windows.net"" - }, - { - ""Type"": ""ServiceBus"", - ""Value"": ""wcusgenevasb832359349008.servicebus.windows.net"" - }, - { - ""Type"": ""StorageBlob"", - ""Value"": ""https:\/\/wcusgenevasa923230976597.blob.core.windows.net"" - }, - { - ""Type"": ""ServiceBus"", - ""Value"": ""wcusgenevasb929002419042.servicebus.windows.net"" - }, - { - ""Type"": ""StorageBlob"", - ""Value"": ""https:\/\/wcusgenevasa056552918724.blob.core.windows.net"" - }, - { - ""Type"": ""ServiceBus"", - ""Value"": ""wcusgenevasb058229963395.servicebus.windows.net"" - }, - { - ""Type"": ""StorageBlob"", - ""Value"": ""https:\/\/wcusgenevasa951612516970.blob.core.windows.net"" - }, - { - ""Type"": ""ServiceBus"", - ""Value"": ""wcusgenevasb952816101216.servicebus.windows.net"" - }, - { - ""Type"": ""StorageBlob"", - ""Value"": ""https:\/\/wcusgenevasa394407896818.blob.core.windows.net"" - }, - { - ""Type"": ""ServiceBus"", - ""Value"": ""wcusgenevasb398857595686.servicebus.windows.net"" - }, - { - ""Type"": ""MetricsConfigurationService"", - ""Value"": ""https:\/\/prod.warmpath.msftcloudes.com"" - }, - { - ""Type"": ""MetricsConfigurationService"", - ""Value"": ""https:\/\/WarmPathFEProdWUSc1.cloudapp.net"" - }, - { - ""Type"": ""MetricsConfigurationService"", - ""Value"": ""https:\/\/WarmPathFEProdCUSc1.cloudapp.net"" - }, - { - ""Type"": ""MetricsConfigurationService"", - ""Value"": ""https:\/\/WarmPathFEProdEUSc1.cloudapp.net"" - }, - { - ""Type"": ""MetricsConfigurationService"", - ""Value"": ""https:\/\/WarmPathFEProdWEURc1.cloudapp.net"" - }, - { - ""Type"": ""MetricsConfigurationService"", - ""Value"": ""https:\/\/WarmPathFEProdEASc1.cloudapp.net"" - } - ] - }, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response3; - } - - #endregion - - #region Case 3 (201 + Location and Azure-AsyncOperation Header) - internal static IEnumerable LocationAndAzAsync201() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Creating"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": ""true"" - } - } - } - } - ") - }; - response1.Headers.Add("Location", AltLocationHeaderUrl); - response1.Headers.Add("Azure-AsyncOperation", status201_AzureAsyncOperationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", - ""status"": ""InProgress"", - ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", - ""endTime"": ""2018-02-08T17: 24: 28.3142823-08: 00"", - ""status"": ""Succeeded"", - ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""fqdn"": ""mdp8680.australiasoutheast.cloudapp.azure.com"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""fqdn"": ""apdp2498.australiasoutheast.cloudapp.azure.com"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": true, - ""storageUri"": ""https:\/\/anh36lyni2ra2diag0.blob.core.windows.net/"" - } - } - } - } - ") - }; - yield return response4; - } - - #endregion - - #region Case 4 (201 + No Header provided) - internal static IEnumerable NoHeaders201() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Creating"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": ""true"" - } - } - } - } - ") - }; - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""properties"": { - ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", - ""provisioningState"": ""InProgress"", - ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" - } - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", - ""endTime"": ""2018-02-08T17: 24: 28.3142823-08: 00"", - ""status"": ""Succeeded"", - ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""fqdn"": ""mdp8680.australiasoutheast.cloudapp.azure.com"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""fqdn"": ""apdp2498.australiasoutheast.cloudapp.azure.com"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": true, - ""storageUri"": ""https:\/\/anh36lyni2ra2diag0.blob.core.windows.net/"" - } - } - } - } - ") - }; - yield return response4; - } - - #endregion - - - #region Case 5 (202 + Azure-AsyncOperation Header) - internal static IEnumerable AzAsync202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""sku"": { - ""name"": ""Standard_LRS"" - }, - ""properties"": { - ""osType"": ""Windows"", - ""creationData"": { - ""createOption"": ""Empty"" - }, - ""diskSizeGB"": 10, - ""encryptionSettings"": { - ""enabled"": true, - ""diskEncryptionKey"": { - ""sourceVault"": { - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/diskrplonglived/providers/Microsoft.KeyVault/vaults/swaggerkeyvault"" - }, - ""secretUrl"": ""https: \/\/swaggerkeyvault.vault.azure.net/secrets/swaggersecret/5684fd3915004bf39bda23df2d21b088"" - } - }, - ""provisioningState"": ""Updating"", - ""isArmResource"": true - }, - ""location"": ""westcentralus"" - } - ") - }; - response1.Headers.Add("Azure-AsyncOperation", status202_AzureAsyncOperationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2017-04-21T11: 39: 23.6625047-07: 00"", - ""endTime"": ""2017-04-21T11: 39: 24.4129092-07: 00"", - ""status"": ""Succeeded"", - ""properties"": { - ""output"": { - ""sku"": { - ""name"": ""Standard_LRS"", - ""tier"": ""Standard"" - }, - ""properties"": { - ""osType"": ""Windows"", - ""creationData"": { - ""createOption"": ""Empty"" - }, - ""diskSizeGB"": 10, - ""encryptionSettings"": { - ""enabled"": true, - ""diskEncryptionKey"": { - ""sourceVault"": { - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/diskrplonglived/providers/Microsoft.KeyVault/vaults/swaggerkeyvault"" - }, - ""secretUrl"": ""https:\/\/swaggerkeyvault.vault.azure.net/secrets/swaggersecret/5684fd3915004bf39bda23df2d21b088"" - } - }, - ""timeCreated"": ""2017-04-21T11: 39: 24.2722176-07: 00"", - ""provisioningState"": ""Succeeded"", - ""diskState"": ""Unattached"" - }, - ""type"": ""Microsoft.Compute/disks"", - ""location"": ""westcentralus"", - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/crptestar3104/providers/Microsoft.Compute/disks/diskrp2765"", - ""name"": ""diskrp2765"" - } - }, - ""name"": ""2e1f6b10-a489-466c-a471-934f5271e918"" - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""sku"": { - ""name"": ""Standard_LRS"", - ""tier"": ""Standard"" - }, - ""properties"": { - ""osType"": ""Windows"", - ""creationData"": { - ""createOption"": ""Empty"" - }, - ""diskSizeGB"": 10, - ""encryptionSettings"": { - ""enabled"": true, - ""diskEncryptionKey"": { - ""sourceVault"": { - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/diskrplonglived/providers/Microsoft.KeyVault/vaults/swaggerkeyvault"" - }, - ""secretUrl"": ""https:\/\/swaggerkeyvault.vault.azure.net/secrets/swaggersecret/5684fd3915004bf39bda23df2d21b088"" - } - }, - ""timeCreated"": ""2017-04-21T11: 39: 24.2722176-07: 00"", - ""provisioningState"": ""Succeeded"", - ""diskState"": ""Unattached"" - }, - ""type"": ""Microsoft.Compute/disks"", - ""location"": ""westcentralus"", - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/crptestar3104/providers/Microsoft.Compute/disks/diskrp2765"", - ""name"": ""diskrp2765"" - } - ") - }; - yield return response3; - } - - #endregion - - #region Case 6 (202 + Location Header) - internal static IEnumerable Location202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Location", status202_LocationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - {} - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""SoutheastAsia"", - ""properties"": { - ""accountType"": ""Standard_GRS"" - } - } - ") - }; - yield return response3; - } - - #endregion - - #region Case 7 (202 + Location and Azure-AsyncOperation Header) - internal static IEnumerable LocationAndAzAsync202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""sku"": { - ""name"": ""Standard_LRS"" - }, - ""properties"": { - ""osType"": ""Windows"", - ""creationData"": { - ""createOption"": ""Empty"" - }, - ""diskSizeGB"": 10, - ""encryptionSettings"": { - ""enabled"": true, - ""diskEncryptionKey"": { - ""sourceVault"": { - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/diskrplonglived/providers/Microsoft.KeyVault/vaults/swaggerkeyvault"" - }, - ""secretUrl"": ""https: \/\/swaggerkeyvault.vault.azure.net/secrets/swaggersecret/5684fd3915004bf39bda23df2d21b088"" - } - }, - ""provisioningState"": ""Updating"", - ""isArmResource"": true - }, - ""location"": ""westcentralus"" - } - ") - }; - response1.Headers.Add("Azure-AsyncOperation", status202_AzureAsyncOperationHeaderUrl); - response1.Headers.Add("Location", status202_LocationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2017-04-21T11: 39: 23.6625047-07: 00"", - ""endTime"": ""2017-04-21T11: 39: 24.4129092-07: 00"", - ""status"": ""Succeeded"", - ""properties"": { - ""output"": { - ""sku"": { - ""name"": ""Standard_LRS"", - ""tier"": ""Standard"" - }, - ""properties"": { - ""osType"": ""Windows"", - ""creationData"": { - ""createOption"": ""Empty"" - }, - ""diskSizeGB"": 10, - ""encryptionSettings"": { - ""enabled"": true, - ""diskEncryptionKey"": { - ""sourceVault"": { - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/diskrplonglived/providers/Microsoft.KeyVault/vaults/swaggerkeyvault"" - }, - ""secretUrl"": ""https:\/\/swaggerkeyvault.vault.azure.net/secrets/swaggersecret/5684fd3915004bf39bda23df2d21b088"" - } - }, - ""timeCreated"": ""2017-04-21T11: 39: 24.2722176-07: 00"", - ""provisioningState"": ""Succeeded"", - ""diskState"": ""Unattached"" - }, - ""type"": ""Microsoft.Compute/disks"", - ""location"": ""westcentralus"", - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/crptestar3104/providers/Microsoft.Compute/disks/diskrp2765"", - ""name"": ""diskrp2765"" - } - }, - ""name"": ""2e1f6b10-a489-466c-a471-934f5271e918"" - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""sku"": { - ""name"": ""Standard_LRS"", - ""tier"": ""Standard"" - }, - ""properties"": { - ""osType"": ""Windows"", - ""creationData"": { - ""createOption"": ""Empty"" - }, - ""diskSizeGB"": 10, - ""encryptionSettings"": { - ""enabled"": true, - ""diskEncryptionKey"": { - ""sourceVault"": { - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/diskrplonglived/providers/Microsoft.KeyVault/vaults/swaggerkeyvault"" - }, - ""secretUrl"": ""https:\/\/swaggerkeyvault.vault.azure.net/secrets/swaggersecret/5684fd3915004bf39bda23df2d21b088"" - } - }, - ""timeCreated"": ""2017-04-21T11: 39: 24.2722176-07: 00"", - ""provisioningState"": ""Succeeded"", - ""diskState"": ""Unattached"" - }, - ""type"": ""Microsoft.Compute/disks"", - ""location"": ""westcentralus"", - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/crptestar3104/providers/Microsoft.Compute/disks/diskrp2765"", - ""name"": ""diskrp2765"" - } - ") - }; - yield return response3; - } - - #endregion - - #region Case 8 (202 + No Header provided) - internal static IEnumerable NoHeaders202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Creating"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": ""true"" - } - } - } - } - ") - }; - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""properties"": { - ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", - ""provisioningState"": ""InProgress"", - ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" - } - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", - ""endTime"": ""2018-02-08T17: 24: 28.3142823-08: 00"", - ""status"": ""Succeeded"", - ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""fqdn"": ""mdp8680.australiasoutheast.cloudapp.azure.com"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""fqdn"": ""apdp2498.australiasoutheast.cloudapp.azure.com"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": true, - ""storageUri"": ""https:\/\/anh36lyni2ra2diag0.blob.core.windows.net/"" - } - } - } - } - ") - }; - yield return response4; - } - - #endregion - - - #region Case 9 (200 + Azure-AsyncOperation Header) - internal static IEnumerable AzAsync200() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Creating"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": ""true"" - } - } - } - } - ") - }; - response1.Headers.Add("Azure-AsyncOperation", status202_AzureAsyncOperationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", - ""status"": ""InProgress"", - ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2017-04-21T11: 39: 23.6625047-07: 00"", - ""endTime"": ""2017-04-21T11: 39: 24.4129092-07: 00"", - ""status"": ""Succeeded"", - ""properties"": { - ""output"": { - ""sku"": { - ""name"": ""Standard_LRS"", - ""tier"": ""Standard"" - }, - ""properties"": { - ""osType"": ""Windows"", - ""creationData"": { - ""createOption"": ""Empty"" - }, - ""diskSizeGB"": 10, - ""encryptionSettings"": { - ""enabled"": true, - ""diskEncryptionKey"": { - ""sourceVault"": { - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/diskrplonglived/providers/Microsoft.KeyVault/vaults/swaggerkeyvault"" - }, - ""secretUrl"": ""https:\/\/swaggerkeyvault.vault.azure.net/secrets/swaggersecret/5684fd3915004bf39bda23df2d21b088"" - } - }, - ""timeCreated"": ""2017-04-21T11: 39: 24.2722176-07: 00"", - ""provisioningState"": ""Succeeded"", - ""diskState"": ""Unattached"" - }, - ""type"": ""Microsoft.Compute/disks"", - ""location"": ""westcentralus"", - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/crptestar3104/providers/Microsoft.Compute/disks/diskrp2765"", - ""name"": ""diskrp2765"" - } - }, - ""name"": ""2e1f6b10-a489-466c-a471-934f5271e918"" - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""sku"": { - ""name"": ""Standard_LRS"", - ""tier"": ""Standard"" - }, - ""properties"": { - ""osType"": ""Windows"", - ""creationData"": { - ""createOption"": ""Empty"" - }, - ""diskSizeGB"": 10, - ""encryptionSettings"": { - ""enabled"": true, - ""diskEncryptionKey"": { - ""sourceVault"": { - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/diskrplonglived/providers/Microsoft.KeyVault/vaults/swaggerkeyvault"" - }, - ""secretUrl"": ""https:\/\/swaggerkeyvault.vault.azure.net/secrets/swaggersecret/5684fd3915004bf39bda23df2d21b088"" - } - }, - ""timeCreated"": ""2017-04-21T11: 39: 24.2722176-07: 00"", - ""provisioningState"": ""Succeeded"", - ""diskState"": ""Unattached"" - }, - ""type"": ""Microsoft.Compute/disks"", - ""location"": ""westcentralus"", - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/crptestar3104/providers/Microsoft.Compute/disks/diskrp2765"", - ""name"": ""diskrp2765"" - } - ") - }; - yield return response4; - } - - #endregion - - #region Case 10 (200 + Location Header) - internal static IEnumerable Location200() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Creating"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": ""true"" - } - } - } - } - ") - }; - response1.Headers.Add("Location", status202_LocationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""SoutheastAsia"", - ""properties"": { - ""accountType"": ""Standard_GRS"" - } - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""location"": ""SoutheastAsia"", - ""properties"": { - ""accountType"": ""Standard_GRS"" - } - } - ") - }; - yield return response3; - } - - #endregion - - #region Case 11 (200 + Location and Azure-AsyncOperation Header) - internal static IEnumerable LocationAndAzAsync200() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Creating"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": ""true"" - } - } - } - } - ") - }; - response1.Headers.Add("Location", AltLocationHeaderUrl); - response1.Headers.Add("Azure-AsyncOperation", status202_AzureAsyncOperationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2017-04-21T11: 39: 23.6625047-07: 00"", - ""endTime"": ""2017-04-21T11: 39: 24.4129092-07: 00"", - ""status"": ""Succeeded"", - ""properties"": { - ""output"": { - ""sku"": { - ""name"": ""Standard_LRS"", - ""tier"": ""Standard"" - }, - ""properties"": { - ""osType"": ""Windows"", - ""creationData"": { - ""createOption"": ""Empty"" - }, - ""diskSizeGB"": 10, - ""encryptionSettings"": { - ""enabled"": true, - ""diskEncryptionKey"": { - ""sourceVault"": { - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/diskrplonglived/providers/Microsoft.KeyVault/vaults/swaggerkeyvault"" - }, - ""secretUrl"": ""https:\/\/swaggerkeyvault.vault.azure.net/secrets/swaggersecret/5684fd3915004bf39bda23df2d21b088"" - } - }, - ""timeCreated"": ""2017-04-21T11: 39: 24.2722176-07: 00"", - ""provisioningState"": ""Succeeded"", - ""diskState"": ""Unattached"" - }, - ""type"": ""Microsoft.Compute/disks"", - ""location"": ""westcentralus"", - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/crptestar3104/providers/Microsoft.Compute/disks/diskrp2765"", - ""name"": ""diskrp2765"" - } - }, - ""name"": ""2e1f6b10-a489-466c-a471-934f5271e918"" - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""sku"": { - ""name"": ""Standard_LRS"", - ""tier"": ""Standard"" - }, - ""properties"": { - ""osType"": ""Windows"", - ""creationData"": { - ""createOption"": ""Empty"" - }, - ""diskSizeGB"": 10, - ""encryptionSettings"": { - ""enabled"": true, - ""diskEncryptionKey"": { - ""sourceVault"": { - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/diskrplonglived/providers/Microsoft.KeyVault/vaults/swaggerkeyvault"" - }, - ""secretUrl"": ""https:\/\/swaggerkeyvault.vault.azure.net/secrets/swaggersecret/5684fd3915004bf39bda23df2d21b088"" - } - }, - ""timeCreated"": ""2017-04-21T11: 39: 24.2722176-07: 00"", - ""provisioningState"": ""Succeeded"", - ""diskState"": ""Unattached"" - }, - ""type"": ""Microsoft.Compute/disks"", - ""location"": ""westcentralus"", - ""id"": ""/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/resourceGroups/crptestar3104/providers/Microsoft.Compute/disks/diskrp2765"", - ""name"": ""diskrp2765"" - } - ") - }; - yield return response3; - } - - #endregion - - #region Case 12 (200 + No Header provided but responses are similar to Azure-AsyncOperation) - internal static IEnumerable NoHeaders200Success() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Creating"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": ""true"" - } - } - } - } - ") - }; - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""properties"": { - ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", - ""provisioningState"": ""InProgress"", - ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" - } - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""fqdn"": ""mdp8680.australiasoutheast.cloudapp.azure.com"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""fqdn"": ""apdp2498.australiasoutheast.cloudapp.azure.com"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": true, - ""storageUri"": ""https:\/\/anh36lyni2ra2diag0.blob.core.windows.net/"" - } - } - } - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""fqdn"": ""mdp8680.australiasoutheast.cloudapp.azure.com"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""fqdn"": ""apdp2498.australiasoutheast.cloudapp.azure.com"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": true, - ""storageUri"": ""https:\/\/anh36lyni2ra2diag0.blob.core.windows.net/"" - } - } - } - } - ") - }; - yield return response4; - } - - #endregion - - #region Case 13 (200 + No Header pass through) - internal static IEnumerable NoHeader200PassThrough() - { - var response1 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Creating"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": ""true"" - } - } - } - } - ") - }; - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", - ""status"": ""InProgress"", - ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", - ""endTime"": ""2018-02-08T17: 24: 28.3142823-08: 00"", - ""status"": ""Succeeded"", - ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""type"": ""Microsoft.ContainerService/ContainerServices"", - ""location"": ""australiasoutheast"", - ""tags"": { - ""RG"": ""rg"", - ""testTag"": ""1"" - }, - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", - ""name"": ""cs8150"", - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""orchestratorProfile"": { - ""orchestratorType"": ""DCOS"" - }, - ""masterProfile"": { - ""count"": 1, - ""dnsPrefix"": ""mdp8680"", - ""fqdn"": ""mdp8680.australiasoutheast.cloudapp.azure.com"", - ""vmSize"": ""Standard_D2"" - }, - ""agentPoolProfiles"": [ - { - ""name"": ""AgentPool1"", - ""count"": 1, - ""vmSize"": ""Standard_A1"", - ""dnsPrefix"": ""apdp2498"", - ""fqdn"": ""apdp2498.australiasoutheast.cloudapp.azure.com"", - ""osType"": ""Linux"" - } - ], - ""linuxProfile"": { - ""ssh"": { - ""publicKeys"": [ - { - ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" - } - ] - }, - ""adminUsername"": ""azureuser"" - }, - ""diagnosticsProfile"": { - ""vmDiagnostics"": { - ""enabled"": true, - ""storageUri"": ""https:\/\/anh36lyni2ra2diag0.blob.core.windows.net/"" - } - } - } - } - ") - }; - yield return response4; - } - #endregion - } - - /// - /// - /// - public class POSTResponses - { - #region const - /// - /// - /// - public const string status201_PostAzureAsyncOperationHeaderUrl = @"https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/providers/Microsoft.ContainerService/locations/australiasoutheast/operations/0adae43a-6224-4e9b-9452-89809d7e41f5?api-version=2017-01-31"; - - /// - /// - /// - public const string status201_PostLocationHeaderUrl = @"https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/RedisCreateUpdate2536/providers/Microsoft.Cache/redis/RedisCreateUpdate9076?api-version=2017-10-01"; - - /// - /// - /// - public const string status202_PostAzureAsyncOperationHeaderUrl = @"https://management.azure.com/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/providers/Microsoft.Compute/locations/westcentralus/DiskOperations/2e1f6b10-a489-466c-a471-934f5271e918?api-version=2017-03-30"; - - /// - /// - /// - public const string status202_PostLocationHeaderUrl = @"https://management.azure.com/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/providers/Microsoft.Compute/locations/westcentralus/DiskOperations/2e1f6b10-a489-466c-a471-934f5271e918?monitor=true&api-version=2017-03-30"; - - /// - /// - /// - public const string AltLocationHeaderUrl = @"https://custom.com"; - - #endregion - - #region Case 1 (201 + Azure-AsyncOperation Header) - internal static IEnumerable AzAsync201() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - {} - ") - }; - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - #endregion - - #region Case 2 (201 + Location Header) - internal static IEnumerable Location201() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - { - ""odata.metadata"": ""https:\/\/graph.windows.net/1273adef-00a3-4086-a51a-dbcce1857d36/$metadata#directoryObjects/Microsoft.DirectoryServices.Group/@Element"", - ""odata.type"": ""Microsoft.DirectoryServices.Group"", - ""objectType"": ""Group"", - ""objectId"": ""cd3a90e9-f8c5-4f6a-847c-55693727d37b"", - ""deletionTimestamp"": null, - ""description"": null, - ""dirSyncEnabled"": null, - ""displayName"": ""testGroup005e51afb-ea56-4276-b1cb-dde04de6318b"", - ""lastDirSyncTime"": null, - ""mail"": null, - ""mailNickname"": ""testGroup005e51afb-ea56-4276-b1cb-dde04de6318btester"", - ""mailEnabled"": false, - ""onPremisesSecurityIdentifier"": null, - ""provisioningErrors"": [], - ""proxyAddresses"": [], - ""securityEnabled"": true - } - ") - }; - response1.Headers.Add("Location", status201_PostLocationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - { - ""odata.metadata"": ""https:\/\/graph.windows.net/1273adef-00a3-4086-a51a-dbcce1857d36/$metadata#directoryObjects/Microsoft.DirectoryServices.Group/@Element"", - ""odata.type"": ""Microsoft.DirectoryServices.Group"", - ""objectType"": ""Group"", - ""objectId"": ""ac9297d4-5ec6-470b-9f77-466b3767094a"", - ""deletionTimestamp"": null, - ""description"": null, - ""dirSyncEnabled"": null, - ""displayName"": ""testGroup18d7444f3-3f4c-457f-8ace-c67a5f096e86"", - ""lastDirSyncTime"": null, - ""mail"": null, - ""mailNickname"": ""testGroup18d7444f3-3f4c-457f-8ace-c67a5f096e86tester"", - ""mailEnabled"": false, - ""onPremisesSecurityIdentifier"": null, - ""provisioningErrors"": [], - ""proxyAddresses"": [], - ""securityEnabled"": true - } - ") - }; - response1.Headers.Add("Location", status201_PostLocationHeaderUrl); - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - #endregion - - #region Case 3 (201 + Location and Azure-AsyncOperation Header) - internal static IEnumerable LocationAndAzAsync201() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - {} - ") - }; - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - #endregion - - #region Case 4 (201 + No Header provided) - internal static IEnumerable NoHeader201() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - {} - ") - }; - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - #endregion - - - #region Case 5 (202 + Azure-AsyncOperation Header) - internal static IEnumerable AzAsync202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Azure-AsyncOperation", status202_PostAzureAsyncOperationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T10: 16: 58.8457489-08: 00"", - ""status"": ""InProgress"", - ""name"": ""64a21a0a-1d9f-43fb-aa97-17a80e232636"" - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T10: 16: 58.8457489-08: 00"", - ""endTime"": ""2018-02-08T10: 20: 09.9419477-08: 00"", - ""status"": ""Succeeded"", - ""name"": ""64a21a0a-1d9f-43fb-aa97-17a80e232636"" - } - ") - }; - yield return response3; - } - #endregion - - #region Case 6 (202 + Location Header) - internal static IEnumerable Location202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - {""Id"": ""5a8dbc9350f4b8121cab0000""} - ") - }; - response1.Headers.Add("Location", status202_PostLocationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/bab08e11-7b12-4354-9fd1-4b5d64d40b68/resourceGroups/Api-Default-CentralUS/providers/Microsoft.ApiManagement/service/sdktestservice"", - ""name"": ""sdktestservice"", - ""type"": ""Microsoft.ApiManagement/service"", - ""tags"": { - ""tag1"": ""value1"", - ""tag2"": ""value2"", - ""tag3"": ""value3"" - }, - ""location"": ""Central US"", - ""etag"": ""AAAAAADgrmk="", - ""properties"": { - ""publisherEmail"": ""apim@autorestsdk.com"", - ""publisherName"": ""autorestsdk"", - ""notificationSenderEmail"": ""apimgmt-noreply@mail.windowsazure.com"", - ""provisioningState"": ""Succeeded"", - ""targetProvisioningState"": """", - ""createdAtUtc"": ""2017-06-16T19: 08: 53.4371217Z"", - ""gatewayUrl"": ""https:\/\/sdktestservice.azure-api.net"", - ""gatewayRegionalUrl"": ""https:\/\/sdktestservice-centralus-01.regional.azure-api.net"", - ""portalUrl"": ""https:\/\/sdktestservice.portal.azure-api.net"", - ""managementApiUrl"": ""https:\/\/sdktestservice.management.azure-api.net"", - ""scmUrl"": ""https:\/\/sdktestservice.scm.azure-api.net"", - ""hostnameConfigurations"": [], - ""publicIPAddresses"": [ - ""52.173.77.113"" - ], - ""privateIPAddresses"": null, - ""additionalLocations"": null, - ""virtualNetworkConfiguration"": null, - ""customProperties"": null, - ""virtualNetworkType"": ""None"", - ""certificates"": null - }, - ""sku"": { - ""name"": ""Developer"", - ""capacity"": 1 - }, - ""identity"": null - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/bab08e11-7b12-4354-9fd1-4b5d64d40b68/resourceGroups/Api-Default-CentralUS/providers/Microsoft.ApiManagement/service/sdktestservice"", - ""name"": ""sdktestservice"", - ""type"": ""Microsoft.ApiManagement/service"", - ""tags"": { - ""tag1"": ""value1"", - ""tag2"": ""value2"", - ""tag3"": ""value3"" - }, - ""location"": ""Central US"", - ""etag"": ""AAAAAADgrmk="", - ""properties"": { - ""publisherEmail"": ""apim@autorestsdk.com"", - ""publisherName"": ""autorestsdk"", - ""notificationSenderEmail"": ""apimgmt-noreply@mail.windowsazure.com"", - ""provisioningState"": ""Succeeded"", - ""targetProvisioningState"": """", - ""createdAtUtc"": ""2017-06-16T19: 08: 53.4371217Z"", - ""gatewayUrl"": ""https:\/\/sdktestservice.azure-api.net"", - ""gatewayRegionalUrl"": ""https:\/\/sdktestservice-centralus-01.regional.azure-api.net"", - ""portalUrl"": ""https:\/\/sdktestservice.portal.azure-api.net"", - ""managementApiUrl"": ""https:\/\/sdktestservice.management.azure-api.net"", - ""scmUrl"": ""https:\/\/sdktestservice.scm.azure-api.net"", - ""hostnameConfigurations"": [], - ""publicIPAddresses"": [ - ""52.173.77.113"" - ], - ""privateIPAddresses"": null, - ""additionalLocations"": null, - ""virtualNetworkConfiguration"": null, - ""customProperties"": null, - ""virtualNetworkType"": ""None"", - ""certificates"": null - }, - ""sku"": { - ""name"": ""Developer"", - ""capacity"": 1 - }, - ""identity"": null - } - ") - }; - yield return response4; - } - #endregion - - #region Case 7 (202 + Location and Azure-AsyncOperation Header) - //SDKs\SqlManagement\Sql.Tests\SessionRecords\Sql.Tests.DatabaseActivationScenarioTests\TestPauseResumeDatabase.json - internal static IEnumerable LocationAndAzAsync202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""operation"": ""DeactivateDatabaseAsync"", - ""startTime"": ""2018-02-09T06: 12: 41.178Z"" - } - ") - }; - response1.Headers.Add("Location", AltLocationHeaderUrl); - response1.Headers.Add("Azure-AsyncOperation", status201_PostAzureAsyncOperationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""operationId"": ""b1362f58-d06b-46cc-8258-d29b54f91a2c"", - ""status"": ""InProgress"", - ""error"": null - } - ") - }; - response2.Headers.Add("Azure-AsyncOperation", status201_PostAzureAsyncOperationHeaderUrl); - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""operationId"": ""b1362f58-d06b-46cc-8258-d29b54f91a2c"", - ""status"": ""InProgress"", - ""error"": null - } - ") - }; - response2.Headers.Add("Azure-AsyncOperation", status201_PostAzureAsyncOperationHeaderUrl); - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""operationId"": ""b1362f58-d06b-46cc-8258-d29b54f91a2c"", - ""status"": ""Succeeded"", - ""error"": null - } - ") - }; - yield return response4; - - var response5 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/sqlcrudtest-5038/providers/Microsoft.Sql/servers/sqlcrudtest-1103/databases/sqlcrudtest-5439"", - ""name"": ""sqlcrudtest-5439"", - ""type"": ""Microsoft.Sql/servers/databases"", - ""location"": ""Japan East"", - ""kind"": ""v12.0,user,datawarehouse"", - ""properties"": { - ""databaseId"": ""00f3e474-516f-4b26-ab59-8364978ec99e"", - ""edition"": ""DataWarehouse"", - ""status"": ""Paused"", - ""serviceLevelObjective"": ""DW100"", - ""collation"": ""SQL_Latin1_General_CP1_CI_AS"", - ""maxSizeBytes"": ""263882790666240"", - ""creationDate"": ""2018-02-09T06: 10: 09.527Z"", - ""currentServiceObjectiveId"": ""4e63cb0e-91b9-46fd-b05c-51fdd2367618"", - ""requestedServiceObjectiveId"": ""4e63cb0e-91b9-46fd-b05c-51fdd2367618"", - ""requestedServiceObjectiveName"": ""DW100"", - ""sampleName"": null, - ""defaultSecondaryLocation"": ""Japan West"", - ""earliestRestoreDate"": null, - ""elasticPoolName"": null, - ""containmentState"": 2, - ""readScale"": ""Disabled"", - ""failoverGroupId"": null, - ""zoneRedundant"": false, - ""isUpgradeRequested"": false - }, - ""operationId"": ""b1362f58-d06b-46cc-8258-d29b54f91a2c"" - } - ") - }; - yield return response5; - } - #endregion - - #region Case 8 (202 + No Header provided) - internal static IEnumerable NoHeader202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - {} - ") - }; - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - #endregion - - - #region Case 9 (202 + Location and Azure-AsyncOperation Header with empty responses) - internal static IEnumerable LocationAndAzAsync202EmptyResponse() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Location", AltLocationHeaderUrl); - response1.Headers.Add("Azure-AsyncOperation", status201_PostAzureAsyncOperationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - {} - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T15: 58: 53.0355309-08: 00"", - ""endTime"": ""2018-02-08T15: 59: 05.9579892-08: 00"", - ""status"": ""Succeeded"", - ""name"": ""97a8befb-bb51-48a3-941b-f483ea09e43f"" - } - ") - }; - yield return response3; - - //var response4 = new HttpResponseMessage(HttpStatusCode.OK) - //{ - // Content = new StringContent(@" - // { - // ""startTime"": ""2018-02-08T15: 58: 53.0355309-08: 00"", - // ""endTime"": ""2018-02-08T15: 59: 05.9579892-08: 00"", - // ""status"": ""Succeeded"", - // ""name"": ""97a8befb-bb51-48a3-941b-f483ea09e43f"" - // } - //") - //}; - //yield return response4; - } - #endregion - } - - /// - /// - /// - public class DELETEResponses - { - #region const - /// - /// - /// - public const string status201_DelAzureAsyncOperationHeaderUrl = @"https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/providers/Microsoft.ContainerService/locations/australiasoutheast/operations/0adae43a-6224-4e9b-9452-89809d7e41f5?api-version=2017-01-31"; - - /// - /// - /// - public const string status201_DelLocationHeaderUrl = @"https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/RedisCreateUpdate2536/providers/Microsoft.Cache/redis/RedisCreateUpdate9076?api-version=2017-10-01"; - - /// - /// - /// - public const string status202_DelAzureAsyncOperationHeaderUrl = @"https://management.azure.com/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/providers/Microsoft.Compute/locations/westcentralus/DiskOperations/2e1f6b10-a489-466c-a471-934f5271e918?api-version=2017-03-30"; - - /// - /// - /// - public const string status202_DelLocationHeaderUrl = @"https://management.azure.com/subscriptions/97f78232-382b-46a7-8a72-964d692c4f3f/providers/Microsoft.Compute/locations/westcentralus/DiskOperations/2e1f6b10-a489-466c-a471-934f5271e918?monitor=true&api-version=2017-03-30"; - //"https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/providers/Microsoft.Storage/locations/southeastasia/asyncoperations/45bc1627-1cc1-4df7-9209-56f9a77bc04e?monitor=true&api-version=2015-06-15" - - /// - /// - /// - public const string AltLocationHeaderUrl = @"https://custom.com"; - - #endregion - - #region Case 1 (201 + Azure-AsyncOperation Header) - internal static IEnumerable AzAsync201() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Azure-AsyncOperation", status201_DelAzureAsyncOperationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T10: 16: 58.8457489-08: 00"", - ""status"": ""InProgress"", - ""name"": ""64a21a0a-1d9f-43fb-aa97-17a80e232636"" - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T10: 16: 58.8457489-08: 00"", - ""endTime"": ""2018-02-08T10: 20: 09.9419477-08: 00"", - ""status"": ""Succeeded"", - ""name"": ""64a21a0a-1d9f-43fb-aa97-17a80e232636"" - } - ") - }; - yield return response3; - } - #endregion - - #region Case 2 (201 + Location Header) - internal static IEnumerable Location201() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Location", status201_DelLocationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Deleting"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - #endregion - - #region Case 3 (201 + Location and Azure-AsyncOperation Header) - internal static IEnumerable LocationAndAzAsync201() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Location", status201_DelLocationHeaderUrl); - response1.Headers.Add("Azure-AsyncOperation", status201_DelAzureAsyncOperationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Creating"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - #endregion - - #region Case 4 (201 + No Header provided) - internal static IEnumerable NoHeader201() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - {} - ") - }; - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - #endregion - - #region Case (201 + Location Header + Final GET 404) - internal static IEnumerable Location201FinalGet404() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Created) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Location", status201_DelLocationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Deleting"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", - ""location"": ""West Central US"", - ""name"": ""RedisCreateUpdate7534"", - ""type"": ""Microsoft.Cache/Redis"", - ""tags"": {}, - ""properties"": { - ""provisioningState"": ""Succeeded"", - ""redisVersion"": ""3.2.7"", - ""sku"": { - ""name"": ""Basic"", - ""family"": ""C"", - ""capacity"": 0 - }, - ""enableNonSslPort"": false, - ""redisConfiguration"": { - ""maxclients"": ""256"", - ""maxmemory-reserved"": ""2"", - ""maxfragmentationmemory-reserved"": ""12"", - ""maxmemory-delta"": ""2"" - }, - ""accessKeys"": null, - ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", - ""port"": 6379, - ""sslPort"": 6380, - ""linkedServers"": [] - } - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.NotFound) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - #endregion - - #region Case 5 (202 + Azure-AsyncOperation Header) - internal static IEnumerable AzAsync202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Azure-AsyncOperation", status202_DelAzureAsyncOperationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T10: 16: 58.8457489-08: 00"", - ""status"": ""InProgress"", - ""name"": ""64a21a0a-1d9f-43fb-aa97-17a80e232636"" - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T10: 16: 58.8457489-08: 00"", - ""endTime"": ""2018-02-08T10: 20: 09.9419477-08: 00"", - ""status"": ""Succeeded"", - ""name"": ""64a21a0a-1d9f-43fb-aa97-17a80e232636"" - } - ") - }; - yield return response3; - } - #endregion - - #region Case 6 (202 + Location Header) - internal static IEnumerable Location202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Location", status202_DelLocationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - {} - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - #endregion - - #region Case 7 (202 + Location and Azure-AsyncOperation Header) - internal static IEnumerable LocationAndAzAsync202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Azure-AsyncOperation", status202_DelAzureAsyncOperationHeaderUrl); - response1.Headers.Add("Location", status202_DelLocationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T10: 16: 58.8457489-08: 00"", - ""status"": ""InProgress"", - ""name"": ""64a21a0a-1d9f-43fb-aa97-17a80e232636"" - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T10: 16: 58.8457489-08: 00"", - ""endTime"": ""2018-02-08T10: 20: 09.9419477-08: 00"", - ""status"": ""Succeeded"", - ""name"": ""64a21a0a-1d9f-43fb-aa97-17a80e232636"" - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - #endregion - - #region Case 8 (202 + No Header provided) - internal static IEnumerable NoHeader202() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - {} - ") - }; - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - #endregion - - - #region Case 9 (202 + Location and Azure-AsyncOperation Header + Final GET 404) - internal static IEnumerable LocationAndAzAsync202FinalGet404() - { - var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - {} - ") - }; - response1.Headers.Add("Azure-AsyncOperation", status202_DelAzureAsyncOperationHeaderUrl); - response1.Headers.Add("Location", status202_DelLocationHeaderUrl); - yield return response1; - - var response2 = new HttpResponseMessage(HttpStatusCode.Accepted) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T10: 16: 58.8457489-08: 00"", - ""status"": ""InProgress"", - ""name"": ""64a21a0a-1d9f-43fb-aa97-17a80e232636"" - } - ") - }; - yield return response2; - - var response3 = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(@" - { - ""startTime"": ""2018-02-08T10: 16: 58.8457489-08: 00"", - ""endTime"": ""2018-02-08T10: 20: 09.9419477-08: 00"", - ""status"": ""Succeeded"", - ""name"": ""64a21a0a-1d9f-43fb-aa97-17a80e232636"" - } - ") - }; - yield return response3; - - var response4 = new HttpResponseMessage(HttpStatusCode.NotFound) - { - Content = new StringContent(@" - {} - ") - }; - yield return response4; - } - #endregion - - } - } -} diff --git a/src/SdkCommon/TestFramework/HttpRecorder.Tests/MoqServerTests/BinaryDataTests.cs b/src/SdkCommon/TestFramework/HttpRecorder.Tests/MoqServerTests/BinaryDataTests.cs new file mode 100644 index 000000000000..cf698e6b7b10 --- /dev/null +++ b/src/SdkCommon/TestFramework/HttpRecorder.Tests/MoqServerTests/BinaryDataTests.cs @@ -0,0 +1,76 @@ + + +namespace HttpRecorder.Tests.MocServerTests +{ + using HttpRecorder.Tests; + using HttpRecorder.Tests.DelegatingHandlers; + using Microsoft.Azure.Test.HttpRecorder; + using Microsoft.Rest.ClientRuntime.Azure.TestFramework; + using System.IO; + using System.Net.Http; + using Xunit; + + public class BinaryDataTests : MoqServerTestBase + { + [Fact] + public void RecordAndPlayBackAudioData() + { + HttpMockServer.Initialize(this.GetType(), TestUtilities.GetCurrentMethodName(), HttpRecorderMode.Record); + FakeHttpClient recordClient = CreateClient(new BinaryDataDelegatingHandler(ContentMimeType.Audio)); + var result = recordClient.DoStuffA().Result; + HttpMockServer.Flush(this.CurrentDir); + + string recordedFilePath = Path.Combine(HttpMockServer.CallerIdentity, TestUtilities.GetCurrentMethodName() + ".json"); + Assert.True(File.Exists(recordedFilePath)); + + HttpMockServer.RecordsDirectory = this.CurrentDir; + HttpMockServer.Initialize(this.GetType(), TestUtilities.GetCurrentMethodName(), HttpRecorderMode.Playback); + FakeHttpClient playbackClient = CreateClient(new BinaryDataDelegatingHandler(ContentMimeType.Audio)); + HttpResponseMessage playBackResult = playbackClient.DoStuffA().Result; + + Assert.True(RecorderUtilities.IsHttpContentBinary(playBackResult.Content), "Binary Data was not correctly serialized to recording file"); + HttpMockServer.Flush(CurrentDir); + } + + [Fact] + public void RecordAndPlayBackImageData() + { + HttpMockServer.Initialize(this.GetType(), TestUtilities.GetCurrentMethodName(), HttpRecorderMode.Record); + FakeHttpClient recordClient = CreateClient(new BinaryDataDelegatingHandler(ContentMimeType.Image)); + var result = recordClient.DoStuffA().Result; + HttpMockServer.Flush(this.CurrentDir); + + string recordedFilePath = Path.Combine(HttpMockServer.CallerIdentity, TestUtilities.GetCurrentMethodName() + ".json"); + Assert.True(File.Exists(recordedFilePath)); + + HttpMockServer.RecordsDirectory = this.CurrentDir; + HttpMockServer.Initialize(this.GetType(), TestUtilities.GetCurrentMethodName(), HttpRecorderMode.Playback); + FakeHttpClient playbackClient = CreateClient(new BinaryDataDelegatingHandler(ContentMimeType.Image)); + HttpResponseMessage playBackResult = playbackClient.DoStuffA().Result; + + Assert.True(RecorderUtilities.IsHttpContentBinary(playBackResult.Content), "Binary Data was not correctly serialized to recording file"); + HttpMockServer.Flush(CurrentDir); + } + + + [Fact] + public void RecordAndPlayBackNullResponse() + { + HttpMockServer.Initialize(this.GetType(), TestUtilities.GetCurrentMethodName(), HttpRecorderMode.Record); + FakeHttpClient recordClient = CreateClient(new BinaryDataDelegatingHandler(ContentMimeType.Null)); + var result = recordClient.DoStuffA().Result; + HttpMockServer.Flush(this.CurrentDir); + + string recordedFilePath = Path.Combine(HttpMockServer.CallerIdentity, TestUtilities.GetCurrentMethodName() + ".json"); + Assert.True(File.Exists(recordedFilePath)); + + HttpMockServer.RecordsDirectory = this.CurrentDir; + HttpMockServer.Initialize(this.GetType(), TestUtilities.GetCurrentMethodName(), HttpRecorderMode.Playback); + FakeHttpClient playbackClient = CreateClient(new BinaryDataDelegatingHandler(ContentMimeType.Null)); + HttpResponseMessage playBackResult = playbackClient.DoStuffA().Result; + + Assert.NotNull(playBackResult.Content); + HttpMockServer.Flush(CurrentDir); + } + } +} diff --git a/src/SdkCommon/TestFramework/HttpRecorder.Tests/BaseMockServerTest.cs b/src/SdkCommon/TestFramework/HttpRecorder.Tests/MoqServerTests/MoqServerTestBase.cs similarity index 81% rename from src/SdkCommon/TestFramework/HttpRecorder.Tests/BaseMockServerTest.cs rename to src/SdkCommon/TestFramework/HttpRecorder.Tests/MoqServerTests/MoqServerTestBase.cs index e7249a014ee6..4ec397f71834 100644 --- a/src/SdkCommon/TestFramework/HttpRecorder.Tests/BaseMockServerTest.cs +++ b/src/SdkCommon/TestFramework/HttpRecorder.Tests/MoqServerTests/MoqServerTestBase.cs @@ -1,20 +1,23 @@ -using Microsoft.Azure.Test.HttpRecorder; -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Net.Http; -using System.Text; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. -namespace HttpRecorder.Tests +namespace HttpRecorder.Tests.MocServerTests { - public class BaseMockServerTest: IDisposable + using Microsoft.Azure.Test.HttpRecorder; + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Net.Http; + using System.Text; + + public class MoqServerTestBase : IDisposable { private string _currentDir; protected string CurrentDir { get => _currentDir; set => _currentDir = value; } - public BaseMockServerTest() + public MoqServerTestBase() { _currentDir = Directory.GetCurrentDirectory();// Environment.CurrentDirectory; HttpMockServer.FileSystemUtilsObject = new FileSystemUtils(); @@ -67,4 +70,7 @@ public void Dispose() HttpMockServer.RecordsDirectory = "SessionRecords"; } } + + + } diff --git a/src/SdkCommon/TestFramework/HttpRecorder.Tests/ProcessRecordedTests/RecordProcessTests.cs b/src/SdkCommon/TestFramework/HttpRecorder.Tests/ProcessRecordedTests/RecordProcessTests.cs new file mode 100644 index 000000000000..72ba5e453544 --- /dev/null +++ b/src/SdkCommon/TestFramework/HttpRecorder.Tests/ProcessRecordedTests/RecordProcessTests.cs @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +namespace HttpRecorder.Tests.ProcessRecordedTests +{ + using HttpRecorder.Tests.DelegatingHandlers; + using HttpRecorder.Tests.ResponseData; + using HttpRecorder.Tests.TestClients.Redis; + using HttpRecorder.Tests.TestClients.Redis.Models; + using Microsoft.Azure.Test.HttpRecorder; + using Microsoft.Azure.Test.HttpRecorder.ProcessRecordings; + using Microsoft.Rest.ClientRuntime.Azure.TestFramework; + using System.Collections.Generic; + using System.IO; + using System.Net.Http; + using Xunit; + + public class CompactLroRequestsTests : ProcessRecordingTestBase + { +#if DEBUG + [Fact] + public void CRUDLroCompact() + { + string testIdentity = this.GetType().Name; + LroResponseData responseData = new LroResponseData(); + List responses = new List(); + int putPollingCount = 20; + int postPollingCount = 30; + int deletePollingCount = 50; + + responses = this.AppendResponse( + responseData.PutLroResponse(putPollingCount, LroHeaders.Location_And_AzureAsync), + responseData.PostLroResponse(postPollingCount, LroHeaders.Location_And_AzureAsync), + responseData.DeleteLroResponse(deletePollingCount, LroHeaders.Location_And_AzureAsync)); + + LroResponseHandler lroHandler = new LroResponseHandler(responses); + + // RECORD + this.CurrentRecordMode = HttpRecorderMode.Record; + HttpMockServer.Initialize(testIdentity, TestUtilities.GetCurrentMethodName(), HttpRecorderMode.Record); + CreateRedisClient(lroHandler); + CreateResource(this.TestClient); + PostRequest(this.TestClient); + DeleteResource(this.TestClient); + string recordedFilePath = HttpMockServer.Flush(this.CurrentDir); + + CompactRecordedFile(recordedFilePath); + + // PLAYBACK + HttpMockServer.RecordsDirectory = ""; + HttpMockServer.Initialize(testIdentity, TestUtilities.GetCurrentMethodName(), HttpRecorderMode.Playback); + + responses = this.AppendResponse( + responseData.PutLroResponse(putPollingCount, LroHeaders.Location_And_AzureAsync), + responseData.PostLroResponse(postPollingCount, LroHeaders.Location_And_AzureAsync), + responseData.DeleteLroResponse(deletePollingCount, LroHeaders.Location_And_AzureAsync)); + + lroHandler = new LroResponseHandler(responses); + + CreateRedisClient(lroHandler); + CreateResource(this.TestClient); + PostRequest(this.TestClient); + DeleteResource(this.TestClient); + Assert.True(true); + } + + #region Compact Files + + + + #endregion +#endif + + void CompactRecordedFile(string filePathToCompact) + { + ProcessRecordedFiles procRecFile = new ProcessRecordedFiles(filePathToCompact); + procRecFile.CompactLroPolling(); + procRecFile.SerializeCompactData(); + } + + #region Drive Operations + RedisResource CreateResource(IRedisManagementClient client) + { + RedisResource redisRes = client.RedisOperations.CreateOrUpdate(DefaultRG, DefaultResourceName, DefaultRedisParameters, DefaultSubscription); + return redisRes; + } + + void DeleteResource(IRedisManagementClient client) + { + client.RedisOperations.Delete(DefaultRG, DefaultResourceName, DefaultSubscription); + } + + Sku PostRequest(IRedisManagementClient client) + { + Sku redisSku = client.RedisOperations.Post(DefaultRG, DefaultResourceName, DefaultSubscription); + return redisSku; + } + + void CreateRedisClient(RecordedDelegatingHandler handler) + { + this.TestClient = new RedisManagementClient(HttpMockServer.CreateInstance(), handler); + this.TestClient.LongRunningOperationInitialTimeout = 0; + this.TestClient.LongRunningOperationRetryTimeout = 0; + } + + #endregion + + //internal string RecordLroOperation(HttpMethod method, int lroPollingCount) + //{ + // HttpMockServer.Initialize(this.GetType().Name, TestUtilities.GetCurrentMethodName(), HttpRecorderMode.Record); + // LroResponseData responseData = new LroResponseData(); + // //var responses = responseData.GetLroPUTResponse(lroPollingCount, true, false, true, HttpStatusCode.OK); + // var responses = responseData.PutLroResponse(lroPollingCount, LroHeaders.Location_And_AzureAsync); + // var lroHandler = new LroResponseHandler(responses); + + // RedisManagementClient redisClient = new RedisManagementClient(HttpMockServer.CreateInstance(), lroHandler); + // redisClient.LongRunningOperationInitialTimeout = 1; + // redisClient.LongRunningOperationRetryTimeout = 1; + // redisClient.RedisOperations.CreateOrUpdate("rg", "redis", new RedisCreateOrUpdateParameters(), "1234"); + + // string recordedFilePath = HttpMockServer.Flush(this.CurrentDir); + + // return recordedFilePath; + //} + } + + public class ProcessRecordingTestBase + { + protected HttpRecorderMode CurrentRecordMode { get; set; } + protected string DefaultRG { get; set; } + protected string DefaultSubscription { get; set; } + + protected RedisCreateOrUpdateParameters DefaultRedisParameters { get; set; } + + protected string DefaultResourceName { get; set; } + + protected string CurrentDir { get; set; } + + public IRedisManagementClient TestClient { get; set; } + + public ProcessRecordingTestBase() + { + CurrentDir = Directory.GetCurrentDirectory();// Environment.CurrentDirectory; + HttpMockServer.FileSystemUtilsObject = new FileSystemUtils(); + DefaultRedisParameters = new RedisCreateOrUpdateParameters(); + DefaultRG = "rg"; + DefaultSubscription = "1234"; + DefaultResourceName = "redis"; + } + + public List AppendResponse(params IEnumerable[] responses) + { + List responseList = new List(); + foreach (IEnumerable res in responses) + { + responseList.AddRange(res); + } + + return responseList; + } + } +} diff --git a/src/SdkCommon/TestFramework/HttpRecorder.Tests/ResponseData/LroResponseData.cs b/src/SdkCommon/TestFramework/HttpRecorder.Tests/ResponseData/LroResponseData.cs new file mode 100644 index 000000000000..510e09b950d1 --- /dev/null +++ b/src/SdkCommon/TestFramework/HttpRecorder.Tests/ResponseData/LroResponseData.cs @@ -0,0 +1,1022 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Text; + +namespace HttpRecorder.Tests.ResponseData +{ + internal class LroResponseData + { + #region Fields + internal static string LroAsyncHeaderName = "Azure-AsyncOperation"; + internal static string LroLocationHeaderName = "Location"; + + internal static string LroAsyncHeaderValue = "Http://custom/status"; + internal static string LroLocationHeaderValue = "https://management.azure.com:090/subscriptions/947c-43bc-83d3-6b318c6c7305/resourceGroups/hdisdk1706/providers/Microsoft.HDInsight/clusters/hdisdk-fail/azureasyncoperations/create?api-version=2015-03-01-preview"; + #endregion + + internal class PutResponse + { + internal static string Put_AsyncHeaderValue_1 = "https://management.azure.com/subscriptions/24fb23e3-6ba3-41f0-9b6e-e41131d5d61e/providers/Microsoft.Compute/locations/southeastasia/DiskOperations/a467a7f3-d2e3-493c-9996-9b212a941154?api-version=2017-03-30"; + internal static string Put_LocationHeaderValue_1 = "https://management.azure.com:893/subscriptions/947c-4345t-83d3-6b318c6c7305/resourceGroups/VMSS2345/providers/Microsoft.HDInsight/clusters/hdisdk-fail/azureasyncoperations/create?api-version=2015-03-01-preview"; + + internal static string EmptyInitialResponse = @""; + + #region initialResponse + internal static string InitalResponse = @" + { + ""name"": ""pip4477"", + ""id"": ""/subscriptions/24fb23e3-6bf0-9b6e-e41131d5d61e/resourceGroups/crptestar2207/providers/Microsoft.Network/publicIPAddresses/pip4477"", + ""etag"": ""0147dbca-57cd-4e6e-bbf7-084fd1c05c"", + ""location"": ""southeastasia"", + ""tags"": { + ""key"": ""value"" + }, + ""properties"": { + ""provisioningState"": ""Updating"", + ""resourceGuid"": ""a410e4f1-3daf-41-a486-c419103ec996"", + ""publicIPAddressVersion"": ""IPv4"", + ""publicIPAllocationMethod"": ""Dynamic"", + ""idleTimeoutInMinutes"": 4, + ""dnsSettings"": { + ""domainNameLabel"": ""dn2871"", + ""fqdn"": ""zr4tg71.southeasia.cloudapp.azure.net"" + } + }, + ""type"": ""Microsoft.Network/publicIPAddresses"" + }"; + #endregion + + internal static HttpResponseMessage GetResponse(string responseContent, HttpStatusCode statusCode, LroHeaders headersToAdd) + { + HttpResponseMessage res = new HttpResponseMessage(statusCode) + { + Content = new StringContent(responseContent) + }; + res = PutAddHeaders(res, headersToAdd); + + return res; + } + + internal static IEnumerable PollingResponse(LroHeaders header, int pollingCount, HttpStatusCode pollingStatusCode) + { + string pollResponse = string.Empty; + string pollEndResponse = string.Empty; + string finalGetResponse = string.Empty; + + List responseList = new List(); + + switch (header) + { + case LroHeaders.AzureAsync: + { + pollResponse = AsyncOperationHeader.IntrimPollingResponse; + pollEndResponse = AsyncOperationHeader.PollingCompletedResponse; + } + break; + + case LroHeaders.Location: + { + pollResponse = LocationHeader.IntrimPollingResponse_1; + pollEndResponse = LocationHeader.PollingCompletedResponse; + finalGetResponse = LocationHeader.LH_FinalResource; + } + break; + + case LroHeaders.Location_And_AzureAsync: + { + pollResponse = AsyncOperationHeader.IntrimPollingResponse; + pollEndResponse = AsyncOperationHeader.PollingCompletedResponse; + finalGetResponse = LocationHeader.LH_FinalResource; + } + break; + } + + for (int i = 0; i <= pollingCount - 1; i++) + { + HttpResponseMessage res = new HttpResponseMessage(pollingStatusCode) + { + Content = new StringContent(pollResponse) + }; + res = PutAddHeaders(res, header); + + responseList.Add(res); + } + + if (!string.IsNullOrEmpty(pollEndResponse)) + { + HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(pollEndResponse) + }; + + responseList.Add(res); + } + + if (!string.IsNullOrEmpty(finalGetResponse)) + { + HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(finalGetResponse) + }; + + responseList.Add(res); + } + + return responseList; + } + + static HttpResponseMessage PutAddHeaders(HttpResponseMessage response, LroHeaders headersToAdd) + { + switch (headersToAdd) + { + case LroHeaders.AzureAsync: + { + response.Headers.Add(LroAsyncHeaderName, Put_AsyncHeaderValue_1); + break; + } + case LroHeaders.Location: + { + response.Headers.Add(LroLocationHeaderName, Put_LocationHeaderValue_1); + break; + } + case LroHeaders.Location_And_AzureAsync: + { + response.Headers.Add(LroAsyncHeaderName, Put_AsyncHeaderValue_1); + response.Headers.Add(LroLocationHeaderName, Put_LocationHeaderValue_1); + break; + } + } + + return response; + } + + //internal static HttpResponseMessage PostPollingResponse(LroHeaders header, HttpStatusCode finalGetStatusCode) + //{ + // string postPollResponse = string.Empty; + + // switch (header) + // { + // case LroHeaders.AzureAsync: + // { + // postPollResponse = AsyncOperationHeader.AsyncOperationHeaderFinalResource; + // } + // break; + + // case LroHeaders.Location: + // { + // postPollResponse = LocationHeader.LH_FinalResource; + // } + // break; + + // case LroHeaders.Location_And_AzureAsync: + // { + // postPollResponse = LocationHeader.LH_FinalResource; + // } + // break; + // } + + // HttpResponseMessage res = new HttpResponseMessage(finalGetStatusCode) + // { + // Content = new StringContent(postPollResponse) + // }; + + // return res; + //} + } + + + internal class PostResponse + { + internal static string Post_AsyncHeaderValue_1 = "https://management.azure.net/subscriptions/popo23e3-6ba3-41f0-9b6e-e41131d5d61e/providers/Microsoft.Compute/locations/southeastasia/DiskOperations/a467a7f3-d2e3-493c-9996-9b212a941154?api-version=2017-01-11"; + internal static string Post_LocationHeaderValue_1 = "https://management.azure.com:893/subscriptions/post-4345t-83d3-6b318c6c7305/resourceGroups/VMSS2345/providers/Microsoft.HDInsight/clusters/hdisdk-fail/azureasyncoperations/create?api-version=2015-03-01-preview"; + + internal static string EmptyInitialResponse = @""; + + #region initialResponse + internal static string InitalResponse = @" + { + ""name"": ""pip4477"", + ""id"": ""/subscriptions/24fb23e3-6bf0-9b6e-e41131d5d61e/resourceGroups/crptestar2207/providers/Microsoft.Network/publicIPAddresses/pip4477"", + ""etag"": ""0147dbca-57cd-4e6e-bbf7-084fd1c05c"", + ""location"": ""southeastasia"", + ""tags"": { + ""key"": ""value"" + }, + ""properties"": { + ""provisioningState"": ""Updating"", + ""resourceGuid"": ""a410e4f1-3daf-41-a486-c419103ec996"", + ""publicIPAddressVersion"": ""IPv4"", + ""publicIPAllocationMethod"": ""Dynamic"", + ""idleTimeoutInMinutes"": 4, + ""dnsSettings"": { + ""domainNameLabel"": ""dn2871"", + ""fqdn"": ""zr4tg71.southeasia.cloudapp.azure.net"" + } + }, + ""type"": ""Microsoft.Network/publicIPAddresses"" + }"; + #endregion + + internal static HttpResponseMessage GetResponse(string responseContent, HttpStatusCode statusCode, LroHeaders headersToAdd) + { + HttpResponseMessage res = new HttpResponseMessage(statusCode) + { + Content = new StringContent(responseContent) + }; + res = PostAddHeaders(res, headersToAdd); + + return res; + } + + internal static IEnumerable PollingResponse(LroHeaders header, int pollingCount, HttpStatusCode pollingStatusCode) + { + string pollResponse = string.Empty; + string pollEndResponse = string.Empty; + string finalGetResponse = string.Empty; + + List responseList = new List(); + + switch (header) + { + case LroHeaders.AzureAsync: + { + pollResponse = AsyncOperationHeader.IntrimPollingResponse; + pollEndResponse = AsyncOperationHeader.PollingCompletedResponse; + } + break; + + case LroHeaders.Location: + { + pollResponse = LocationHeader.IntrimPollingResponse_1; + pollEndResponse = LocationHeader.PollingCompletedResponse; + finalGetResponse = LocationHeader.LH_FinalResource; + } + break; + + case LroHeaders.Location_And_AzureAsync: + { + pollResponse = AsyncOperationHeader.IntrimPollingResponse; + pollEndResponse = AsyncOperationHeader.PollingCompletedResponse; + finalGetResponse = LocationHeader.LH_FinalResource; + } + break; + } + + for (int i = 0; i <= pollingCount - 1; i++) + { + HttpResponseMessage res = new HttpResponseMessage(pollingStatusCode) + { + Content = new StringContent(pollResponse) + }; + res = PostAddHeaders(res, header); + + responseList.Add(res); + } + + if (!string.IsNullOrEmpty(pollEndResponse)) + { + HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(pollEndResponse) + }; + + responseList.Add(res); + } + + if (!string.IsNullOrEmpty(finalGetResponse)) + { + HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(finalGetResponse) + }; + + responseList.Add(res); + } + + return responseList; + } + + static HttpResponseMessage PostAddHeaders(HttpResponseMessage response, LroHeaders headersToAdd) + { + switch (headersToAdd) + { + case LroHeaders.AzureAsync: + { + response.Headers.Add(LroAsyncHeaderName, Post_AsyncHeaderValue_1); + break; + } + case LroHeaders.Location: + { + response.Headers.Add(LroLocationHeaderName, Post_LocationHeaderValue_1); + break; + } + case LroHeaders.Location_And_AzureAsync: + { + response.Headers.Add(LroAsyncHeaderName, Post_AsyncHeaderValue_1); + response.Headers.Add(LroLocationHeaderName, Post_LocationHeaderValue_1); + break; + } + } + + return response; + } + } + + + + + internal static class DeleteResponse + { + internal static string Delete_AsyncHeaderValue_1 = "https://management.azure.com:090/subscriptions/434c10bb-83d3-6b318c6c7305/resourceGroups/hdisdk1706/providers/Microsoft.HDInsight/clusters/hdisdk-fail/azureasyncoperations/create?api-version=2015-03-01-preview"; + internal static string Delete_LocationHeaderValue_1 = "https://management.azure.com/subscriptions/fffc-4345t-83d3-6b318c6c7305/resourceGroups/testgrp3569/providers/Microsoft.Compute/clusters/hdisdk-fail/azureasyncoperations/patch?api-version=2019-03-01"; + + #region Responses + internal static string Initial_EmptyResponse = @""; + + internal static string Intrim_AzAsyncHeaderStatusInProgress = @" + { + ""startTime"": ""2018-02-08T10: 16: 58.8457489-08: 00"", + ""status"": ""InProgress"", + ""name"": ""64a21a0a-1d9f-43fb-aa97-17a80e232636"" + }"; + + internal static string Intrim_AzAsyncHeaderSuccessResponse = @" + { + ""startTime"": ""2018-02-08T10: 16: 58.8457489-08: 00"", + ""endTime"": ""2018-02-08T10: 20: 09.9419477-08: 00"", + ""status"": ""Succeeded"", + ""name"": ""64a21a0a-1d9f-43fb-aa97-17a80e232636"" + } + "; + + internal static string Intrim_LocationInProgress = @" + { + ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", + ""location"": ""West Central US"", + ""name"": ""RedisCreateUpdate7534"", + ""type"": ""Microsoft.Cache/Redis"", + ""tags"": {}, + ""properties"": { + ""provisioningState"": ""Deleting"", + ""redisVersion"": ""3.2.7"", + ""sku"": { + ""name"": ""Basic"", + ""family"": ""C"", + ""capacity"": 0 + }, + ""enableNonSslPort"": false, + ""redisConfiguration"": { + ""maxclients"": ""256"", + ""maxmemory-reserved"": ""2"", + ""maxfragmentationmemory-reserved"": ""12"", + ""maxmemory-delta"": ""2"" + }, + ""accessKeys"": null, + ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", + ""port"": 6379, + ""sslPort"": 6380, + ""linkedServers"": [] + } + } + "; + + internal static string Intrim_LocationSuccess = @"{}"; + + internal static string Final_LocationSucess = @"{}"; + #endregion + + internal static HttpResponseMessage GetResponse(string responseContent, HttpStatusCode statusCode, LroHeaders headersToAdd) + { + HttpResponseMessage res = new HttpResponseMessage(statusCode) + { + Content = new StringContent(responseContent) + }; + res = DeleteAddHeaders(res, headersToAdd); + + return res; + } + + internal static IEnumerable PollingResponse(LroHeaders header, int pollingCount, HttpStatusCode pollingStatusCode) + { + string pollResponse = string.Empty; + string pollEndResponse = string.Empty; + string finalGetResponse = string.Empty; + List responseList = new List(); + + switch (header) + { + case LroHeaders.AzureAsync: + { + pollResponse = Intrim_AzAsyncHeaderStatusInProgress; + pollEndResponse = Intrim_AzAsyncHeaderSuccessResponse; + } + break; + + case LroHeaders.Location: + { + pollResponse = Intrim_LocationInProgress; + pollEndResponse = Intrim_LocationSuccess; + finalGetResponse = Intrim_LocationSuccess; + } + break; + + case LroHeaders.Location_And_AzureAsync: + { + pollResponse = Intrim_AzAsyncHeaderStatusInProgress; + pollEndResponse = Intrim_AzAsyncHeaderSuccessResponse; + finalGetResponse = Intrim_LocationSuccess; + } + break; + } + + for (int i = 0; i <= pollingCount - 1; i++) + { + HttpResponseMessage res = new HttpResponseMessage(pollingStatusCode) + { + Content = new StringContent(pollResponse) + }; + res = DeleteAddHeaders(res, header); + + responseList.Add(res); + } + + if (!string.IsNullOrEmpty(pollEndResponse)) + { + HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(pollEndResponse) + }; + + responseList.Add(res); + } + + if(!string.IsNullOrEmpty(finalGetResponse)) + { + HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(finalGetResponse) + }; + + responseList.Add(res); + } + + return responseList; + } + + static HttpResponseMessage DeleteAddHeaders(HttpResponseMessage response, LroHeaders headersToAdd) + { + switch (headersToAdd) + { + case LroHeaders.AzureAsync: + { + response.Headers.Add(LroAsyncHeaderName, Delete_AsyncHeaderValue_1); + break; + } + case LroHeaders.Location: + { + response.Headers.Add(LroLocationHeaderName, Delete_LocationHeaderValue_1); + break; + } + case LroHeaders.Location_And_AzureAsync: + { + response.Headers.Add(LroAsyncHeaderName, Delete_AsyncHeaderValue_1); + response.Headers.Add(LroLocationHeaderName, Delete_LocationHeaderValue_1); + break; + } + } + + return response; + } + } + + internal class AsyncOperationHeader + { + #region Initial Response + internal static string InitialResponse = @" + { + ""type"": ""Microsoft.ContainerService/ContainerServices"", + ""location"": ""australiasoutheast"", + ""tags"": { + ""RG"": ""rg"", + ""testTag"": ""1"" + }, + ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", + ""name"": ""cs8150"", + ""properties"": { + ""provisioningState"": ""Creating"", + ""orchestratorProfile"": { + ""orchestratorType"": ""DCOS"" + }, + ""masterProfile"": { + ""count"": 1, + ""dnsPrefix"": ""mdp8680"", + ""vmSize"": ""Standard_D2"" + }, + ""agentPoolProfiles"": [ + { + ""name"": ""AgentPool1"", + ""count"": 1, + ""vmSize"": ""Standard_A1"", + ""dnsPrefix"": ""apdp2498"", + ""osType"": ""Linux"" + } + ], + ""linuxProfile"": { + ""ssh"": { + ""publicKeys"": [ + { + ""keyData"": ""SomeKeyData"" + } + ] + }, + ""adminUsername"": ""azureuser"" + }, + ""diagnosticsProfile"": { + ""vmDiagnostics"": { + ""enabled"": ""true"" + } + } + } + } + "; + #endregion + + #region Intrim Response + + internal static string IntrimPollingResponse = @" + { + ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", + ""status"": ""InProgress"", + ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" + } + "; + + internal static string PollingCompletedResponse = @" + { + ""startTime"": ""2018-02-08T17: 17: 43.4257988-08: 00"", + ""endTime"": ""2018-02-08T17: 24: 28.3142823-08: 00"", + ""status"": ""Succeeded"", + ""name"": ""0adae43a-6224-4e9b-9452-89809d7e41f5"" + } + "; + #endregion + + #region Final Response + internal static string AsyncOperationHeaderFinalResource = @" + { + ""type"": ""Microsoft.ContainerService/ContainerServices"", + ""location"": ""australiasoutheast"", + ""tags"": { + ""RG"": ""rg"", + ""testTag"": ""1"" + }, + ""id"": ""/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/crptestar9541/providers/Microsoft.ContainerService/containerServices/cs8150"", + ""name"": ""cs8150"", + ""properties"": { + ""provisioningState"": ""Succeeded"", + ""orchestratorProfile"": { + ""orchestratorType"": ""DCOS"" + }, + ""masterProfile"": { + ""count"": 1, + ""dnsPrefix"": ""mdp8680"", + ""fqdn"": ""mdp8680.australiasoutheast.cloudapp.azure.com"", + ""vmSize"": ""Standard_D2"" + }, + ""agentPoolProfiles"": [ + { + ""name"": ""AgentPool1"", + ""count"": 1, + ""vmSize"": ""Standard_A1"", + ""dnsPrefix"": ""apdp2498"", + ""fqdn"": ""apdp2498.australiasoutheast.cloudapp.azure.com"", + ""osType"": ""Linux"" + } + ], + ""linuxProfile"": { + ""ssh"": { + ""publicKeys"": [ + { + ""keyData"": ""ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDorij8dGcKUBTbvHylBpm5NZ2MtDgn1+jbyHE8N4dCS4ZoIl6Pdoa1At/GjXVhIRuz1hlyT2ey5BaC8iQnQTh/f2oyNctQ5+2KX1sgFlvaQAJCVn0tN7yDT29ZiIE2kfL3RCV5HH7p+NjBQ/cvtaOgESgoi/CI3S58w1XaRdDKo5Uz0U0DDuuB5lO5dq4nceAH8sx2bFTNjlgJcoyxi13h9CYkymm0mVaZkwiIJY8cU+UrupZKCMboBbCM7Q2spmRQ1tGicT5g84PsCqUf417u+Jvtf0kD1GdsCyMGALzBDS0scORhMiXHZ/vEM6rOPCIBpH7IzeULhWGXZfPdg4bL acs-bot@microsoft.com"" + } + ] + }, + ""adminUsername"": ""azureuser"" + }, + ""diagnosticsProfile"": { + ""vmDiagnostics"": { + ""enabled"": true, + ""storageUri"": ""https:\/\/anh36lyni2ra2diag0.blob.core.windows.net/"" + } + } + } + } + "; + #endregion + + internal static HttpResponseMessage GetResponse(HttpStatusCode statusCode, ResponseKind resKind) + { + HttpResponseMessage res = new HttpResponseMessage(); + switch(resKind) + { + case ResponseKind.Initial: + res.Content = new StringContent(InitialResponse); + break; + + case ResponseKind.IntrimPolling: + res.Content = new StringContent(IntrimPollingResponse); + break; + + case ResponseKind.PostPolling: + res.Content = new StringContent(AsyncOperationHeaderFinalResource); + break; + } + + return res; + } + + internal static HttpResponseMessage GetResponse(HttpStatusCode statusCode, ResponseKind resKind, LroHeaders headers) + { + HttpResponseMessage res = GetResponse(statusCode, resKind); + //res = AddHeaders(res, headers); + + return res; + } + } + + internal static class LocationHeader + { + #region Initial Response + internal static string InitialResponse = @" + { + ""ResponseOrder"": ""1"", + ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", + ""location"": ""West Central US"", + ""name"": ""RedisCreateUpdate7534"", + ""type"": ""Microsoft.Cache/Redis"", + ""tags"": {}, + ""properties"": { + ""provisioningState"": ""Creating"", + ""redisVersion"": ""3.2.7"", + ""sku"": { + ""name"": ""Basic"", + ""family"": ""C"", + ""capacity"": 0 + }, + ""enableNonSslPort"": false, + ""redisConfiguration"": { + ""maxclients"": ""256"", + ""maxmemory-reserved"": ""2"", + ""maxfragmentationmemory-reserved"": ""12"", + ""maxmemory-delta"": ""2"" + }, + ""accessKeys"": { + ""primaryKey"": ""e77DIxNC9kfKnAH0imMFNILFHSCW6BinwFGvHvpOj5U="", + ""secondaryKey"": ""NVzdWjgyhvoOjETlvj5JN+vK8qTXjqGUGYxpfguB8cM="" + }, + ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", + ""port"": 6379, + ""sslPort"": 6380, + ""linkedServers"": [] + } + } + "; + #endregion + + #region Intrim Response + internal static string IntrimPollingResponse_1 = @" + { + ""ResponseOrder"": ""2"", + ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", + ""location"": ""West Central US"", + ""name"": ""RedisCreateUpdate7534"", + ""type"": ""Microsoft.Cache/Redis"", + ""tags"": {}, + ""properties"": { + ""provisioningState"": ""Creating"", + ""redisVersion"": ""3.2.7"", + ""sku"": { + ""name"": ""Basic"", + ""family"": ""C"", + ""capacity"": 0 + }, + ""enableNonSslPort"": false, + ""redisConfiguration"": { + ""maxclients"": ""256"", + ""maxmemory-reserved"": ""2"", + ""maxfragmentationmemory-reserved"": ""12"", + ""maxmemory-delta"": ""2"" + }, + ""accessKeys"": null, + ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", + ""port"": 6379, + ""sslPort"": 6380, + ""linkedServers"": [] + } + } + "; + + internal static string IntrimPollingResponse_2 = @" + { + ""id"": ""https://management.azure.com/subscriptions/1cba1da6-5a83-45e1-a88e-8b397eb84356/providers/Microsoft.BatchAI/locations/eastus/operationresults/b183d70f-25fb-47b3-875e-c3c7b7095823"", + ""name"": ""b183d70f-25fb-47b3-875e-c3c7b7095823"", + ""status"": ""InProgress"", + ""startTime"": ""2018-06-20T22:04:36.271Z"" + }"; + + internal static string PollingCompletedResponse = @" + { + ""ResponseOrder"": ""3"", + ""id"": ""/subscriptions/592cc9de-a3cd-4d70-9bc1-c1a28a3625b5/resourceGroups/RedisCreateUpdate3324/providers/Microsoft.Cache/Redis/RedisCreateUpdate7534"", + ""location"": ""West Central US"", + ""name"": ""RedisCreateUpdate7534"", + ""type"": ""Microsoft.Cache/Redis"", + ""tags"": {}, + ""properties"": { + ""provisioningState"": ""Succeeded"", + ""redisVersion"": ""3.2.7"", + ""sku"": { + ""name"": ""Basic"", + ""family"": ""C"", + ""capacity"": 0 + }, + ""enableNonSslPort"": false, + ""tenantSettings"": { + ""InternalDependencyList"": [ + { + ""Type"": ""StorageBlob"", + ""Value"": ""https://wcus2554052479.blob.core.windows.net/"" + }, + { + ""Type"": ""StorageQueue"", + ""Value"": ""https://wcus2554052479.queue.core.windows.net/"" + }, + { + ""Type"": ""StorageBlob"", + ""Value"": ""https://wcusscaleunit5435222359.blob.core.windows.net/"" + }, + { + ""Type"": ""StorageQueue"", + ""Value"": ""https://wcusscaleunit5435222359.queue.core.windows.net"" + }, + { + ""Type"": ""StorageBlob"", + ""Value"": ""https://wcusgenevasa834343247016.blob.core.windows.net"" + }, + { + ""Type"": ""ServiceBus"", + ""Value"": ""wcusgenevasb832359349008.servicebus.windows.net"" + }, + { + ""Type"": ""StorageBlob"", + ""Value"": ""https:\/\/wcusgenevasa923230976597.blob.core.windows.net"" + }, + { + ""Type"": ""ServiceBus"", + ""Value"": ""wcusgenevasb929002419042.servicebus.windows.net"" + }, + { + ""Type"": ""StorageBlob"", + ""Value"": ""https:\/\/wcusgenevasa056552918724.blob.core.windows.net"" + }, + { + ""Type"": ""ServiceBus"", + ""Value"": ""wcusgenevasb058229963395.servicebus.windows.net"" + }, + { + ""Type"": ""StorageBlob"", + ""Value"": ""https:\/\/wcusgenevasa951612516970.blob.core.windows.net"" + }, + { + ""Type"": ""ServiceBus"", + ""Value"": ""wcusgenevasb952816101216.servicebus.windows.net"" + }, + { + ""Type"": ""StorageBlob"", + ""Value"": ""https:\/\/wcusgenevasa394407896818.blob.core.windows.net"" + }, + { + ""Type"": ""ServiceBus"", + ""Value"": ""wcusgenevasb398857595686.servicebus.windows.net"" + }, + { + ""Type"": ""MetricsConfigurationService"", + ""Value"": ""https:\/\/prod.warmpath.msftcloudes.com"" + }, + { + ""Type"": ""MetricsConfigurationService"", + ""Value"": ""https:\/\/WarmPathFEProdWUSc1.cloudapp.net"" + }, + { + ""Type"": ""MetricsConfigurationService"", + ""Value"": ""https:\/\/WarmPathFEProdCUSc1.cloudapp.net"" + }, + { + ""Type"": ""MetricsConfigurationService"", + ""Value"": ""https:\/\/WarmPathFEProdEUSc1.cloudapp.net"" + }, + { + ""Type"": ""MetricsConfigurationService"", + ""Value"": ""https:\/\/WarmPathFEProdWEURc1.cloudapp.net"" + }, + { + ""Type"": ""MetricsConfigurationService"", + ""Value"": ""https:\/\/WarmPathFEProdEASc1.cloudapp.net"" + } + ] + }, + ""redisConfiguration"": { + ""maxclients"": ""256"", + ""maxmemory-reserved"": ""2"", + ""maxfragmentationmemory-reserved"": ""12"", + ""maxmemory-delta"": ""2"" + }, + ""accessKeys"": null, + ""hostName"": ""RedisCreateUpdate7534.redis.cache.windows.net"", + ""port"": 6379, + ""sslPort"": 6380, + ""linkedServers"": [] + } + } + "; + #endregion + + #region Final Response + internal static string LH_FinalResource = @" + { + ""location"": ""SoutheastAsia"", + ""properties"": { + ""accountType"": ""Standard_GRS"" + } + }"; + + #endregion + + + internal static HttpResponseMessage GetResponse(HttpStatusCode statusCode, ResponseKind resKind) + { + HttpResponseMessage res = new HttpResponseMessage(); + switch (resKind) + { + case ResponseKind.Initial: + res.Content = new StringContent(InitialResponse); + break; + + case ResponseKind.IntrimPolling: + res.Content = new StringContent(IntrimPollingResponse_1); + break; + + case ResponseKind.PostPolling: + res.Content = new StringContent(LH_FinalResource); + break; + } + + return res; + } + + internal static HttpResponseMessage GetResponse(HttpStatusCode statusCode, ResponseKind resKind, LroHeaders headers) + { + HttpResponseMessage res = GetResponse(statusCode, resKind); + //res = AddHeaders(res, headers); + + return res; + } + } + + internal LroResponseData() { } + + //internal IEnumerable GetLroPUTResponse(int pollingResponseCount, bool includeAsyncOperationHeader, + // bool includeLocationHeader, bool includeFinalResponse, + // HttpStatusCode finalResponseStatusCode) + //{ + // HttpResponseMessage res = null; + + // #region Initial Response + // res = new HttpResponseMessage(HttpStatusCode.Created) + // { + // Content = new StringContent(AsyncOperationHeader.InitialResponse) + // }; + // res.Headers.Add(LroAsyncHeaderName, LroAsyncHeaderValue); + // #endregion + + // #region polling + // for (int i = 0; i <= pollingResponseCount - 1; i++) + // { + // if (includeAsyncOperationHeader == true) + // { + // res = new HttpResponseMessage(HttpStatusCode.Created) + // { + // Content = new StringContent(AsyncOperationHeader.IntrimPollingResponse) + // }; + // res.Headers.Add(LroAsyncHeaderName, LroAsyncHeaderValue); + // } + + // if (includeLocationHeader == true) + // { + // res.Headers.Add(LroLocationHeaderName, LroLocationHeaderValue); + // } + + // yield return res; + // } + + // res = new HttpResponseMessage(HttpStatusCode.OK) + // { + // Content = new StringContent(AsyncOperationHeader.PollingCompletedResponse) + // }; + // yield return res; + // #endregion + + // #region Final Response + + + // #endregion + + // res = new HttpResponseMessage(HttpStatusCode.OK) + // { + // Content = new StringContent(AsyncOperationHeader.AsyncOperationHeaderFinalResource) + // }; + // yield return res; + //} + + + internal IEnumerable PutLroResponse(int pollingCount, LroHeaders header) + { + List lroResList = new List(); + lroResList.Add(PutResponse.GetResponse(PutResponse.EmptyInitialResponse, HttpStatusCode.Created, header)); + + var lroResponses = PutResponse.PollingResponse(header, pollingCount, HttpStatusCode.Created); + lroResList.AddRange(lroResponses); + + //lroResList.Add(PutResponse.PostPollingResponse(header, HttpStatusCode.OK)); + return lroResList; + } + + + internal IEnumerable DeleteLroResponse(int pollingCount, LroHeaders header) + { + List lroResList = new List(); + + lroResList.Add(DeleteResponse.GetResponse(DeleteResponse.Initial_EmptyResponse, HttpStatusCode.Accepted, header)); + var deleteLroResponses = DeleteResponse.PollingResponse(header, pollingCount, HttpStatusCode.Accepted); + + lroResList.AddRange(deleteLroResponses); + + return lroResList; + } + + internal IEnumerable PostLroResponse(int pollingCount, LroHeaders header) + { + List lroResList = new List(); + + lroResList.Add(PostResponse.GetResponse(PostResponse.EmptyInitialResponse, HttpStatusCode.Accepted, header)); + var postLroResponses = PostResponse.PollingResponse(header, pollingCount, HttpStatusCode.Accepted); + + lroResList.AddRange(postLroResponses); + + return lroResList; + } + + //static HttpResponseMessage AddHeaders(HttpResponseMessage response, LroHeaders headersToAdd) + //{ + // switch (headersToAdd) + // { + // case LroHeaders.AzureAsync: + // { + // response.Headers.Add(LroAsyncHeaderName, LroAsyncHeaderValue); + // break; + // } + // case LroHeaders.Location: + // { + // response.Headers.Add(LroLocationHeaderName, LroLocationHeaderValue); + // break; + // } + // case LroHeaders.Location_And_AzureAsync: + // { + // response.Headers.Add(LroAsyncHeaderName, LroAsyncHeaderValue); + // response.Headers.Add(LroLocationHeaderName, LroLocationHeaderValue); + // break; + // } + // } + + // return response; + //} + } + + + enum LroHeaders + { + Location, + AzureAsync, + Location_And_AzureAsync + } + + enum ResponseKind + { + Initial, + IntrimPolling, + PostPolling + } + +} diff --git a/src/SdkCommon/TestFramework/HttpRecorder.Tests/TestClients/RedisManagementClient.cs b/src/SdkCommon/TestFramework/HttpRecorder.Tests/TestClients/RedisManagementClient.cs new file mode 100644 index 000000000000..6bbdcae9b77a --- /dev/null +++ b/src/SdkCommon/TestFramework/HttpRecorder.Tests/TestClients/RedisManagementClient.cs @@ -0,0 +1,2398 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + using HttpRecorder.Tests.TestClients.Redis.Models; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; +using Microsoft.Rest.Azure; + +namespace HttpRecorder.Tests.TestClients.Redis.Models +{ + public partial class RedisCreateOrUpdateParameters + { + private string _location; + + /// + /// Optional. + /// + public string Location + { + get { return this._location; } + set { this._location = value; } + } + + private RedisProperties _properties; + + /// + /// Optional. + /// + public RedisProperties Properties + { + get { return this._properties; } + set { this._properties = value; } + } + } + + public partial class RedisResource : IResource + { + /// + /// Gets the ID of the resource. + /// + [JsonProperty("id")] + public string Id { get; private set; } + + /// + /// Gets the name of the resource. + /// + [JsonProperty("name")] + public string Name { get; private set; } + + /// + /// Gets the type of the resource. + /// + [JsonProperty("type")] + public string Type { get; private set; } + + /// + /// Required. Gets or sets the location of the resource. + /// + [JsonProperty("location")] + public string Location { get; set; } + + /// + /// Optional. Gets or sets the tags attached to the resource. + /// + [JsonProperty("tags")] + public IDictionary Tags { get; set; } + + /// + /// Validate the object. Throws ArgumentException or ArgumentNullException if validation fails. + /// + public virtual void Validate() + { + if (Location == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "Location"); + } + } + + private string _hostName; + + /// + /// Optional. + /// + public string HostName + { + get { return this._hostName; } + set { this._hostName = value; } + } + + private int? _port; + + /// + /// Optional. + /// + public int? Port + { + get { return this._port; } + set { this._port = value; } + } + + private int? _sslPort; + + /// + /// Optional. + /// + public int? SslPort + { + get { return this._sslPort; } + set { this._sslPort = value; } + } + + /// + /// Optional. + /// + [JsonProperty("properties.provisioningState")] + public string ProvisioningState { get; set; } + } + + public partial class RedisSubResource : IResource + { + /// + /// Gets the ID of the resource. + /// + [JsonProperty("id")] + public string Id { get; private set; } + + private string _hostName; + + /// + /// Optional. + /// + public string HostName + { + get { return this._hostName; } + set { this._hostName = value; } + } + + private int? _port; + + /// + /// Optional. + /// + public int? Port + { + get { return this._port; } + set { this._port = value; } + } + + private int? _sslPort; + + /// + /// Optional. + /// + public int? SslPort + { + get { return this._sslPort; } + set { this._sslPort = value; } + } + } + + public partial class RedisProperties + { + private bool? _enableNonSslPort; + + /// + /// Optional. + /// + public bool? EnableNonSslPort + { + get { return this._enableNonSslPort; } + set { this._enableNonSslPort = value; } + } + + private string _maxMemoryPolicy; + + /// + /// Optional. + /// + public string MaxMemoryPolicy + { + get { return this._maxMemoryPolicy; } + set { this._maxMemoryPolicy = value; } + } + + private string _redisVersion; + + /// + /// Optional. + /// + public string RedisVersion + { + get { return this._redisVersion; } + set { this._redisVersion = value; } + } + + private Sku _sku; + + /// + /// Optional. + /// + public Sku Sku + { + get { return this._sku; } + set { this._sku = value; } + } + } + + public partial class RedisReadableProperties + { + private string _hostName; + + /// + /// Optional. + /// + public string HostName + { + get { return this._hostName; } + set { this._hostName = value; } + } + + private int? _port; + + /// + /// Optional. + /// + public int? Port + { + get { return this._port; } + set { this._port = value; } + } + + private string _provisioningState; + + /// + /// Optional. + /// + public string ProvisioningState + { + get { return this._provisioningState; } + set { this._provisioningState = value; } + } + + private int? _sslPort; + + /// + /// Optional. + /// + public int? SslPort + { + get { return this._sslPort; } + set { this._sslPort = value; } + } + } + + public partial class Sku + { + private int? _capacity; + + /// + /// Optional. + /// + public int? Capacity + { + get { return this._capacity; } + set { this._capacity = value; } + } + + private string _family; + + /// + /// Optional. + /// + public string Family + { + get { return this._family; } + set { this._family = value; } + } + + private string _name; + + /// + /// Optional. + /// + public string Name + { + get { return this._name; } + set { this._name = value; } + } + } +} + +namespace HttpRecorder.Tests.TestClients.Redis +{ + public static partial class RedisManagementClientExtensions + { + } + + public partial interface IRedisManagementClient : IDisposable + { + string ApiVersion + { + get; + set; + } + + /// + /// The base URI of the service. + /// + Uri BaseUri + { + get; + set; + } + + ServiceClientCredentials Credentials + { + get; + set; + } + + int? LongRunningOperationInitialTimeout + { + get; + set; + } + + int? LongRunningOperationRetryTimeout + { + get; + set; + } + + IRedisOperations RedisOperations + { + get; + } + } + + public partial class RedisManagementClient : ServiceClient, IRedisManagementClient, IAzureClient + { + private string _apiVersion; + + public string ApiVersion + { + get { return this._apiVersion; } + set { this._apiVersion = value; } + } + + private Uri _baseUri; + + /// + /// The base URI of the service. + /// + public Uri BaseUri + { + get { return this._baseUri; } + set { this._baseUri = value; } + } + + /// + /// Gets or sets json serialization settings. + /// + public JsonSerializerSettings SerializationSettings { get; private set; } + + /// + /// Gets or sets json deserialization settings. + /// + public JsonSerializerSettings DeserializationSettings { get; private set; } + + private ServiceClientCredentials _credentials; + + public ServiceClientCredentials Credentials + { + get { return this._credentials; } + set { this._credentials = value; } + } + + private int? _longRunningOperationInitialTimeout; + + public int? LongRunningOperationInitialTimeout + { + get { return this._longRunningOperationInitialTimeout; } + set { this._longRunningOperationInitialTimeout = value; } + } + + private int? _longRunningOperationRetryTimeout; + + public int? LongRunningOperationRetryTimeout + { + get { return this._longRunningOperationRetryTimeout; } + set { this._longRunningOperationRetryTimeout = value; } + } + + public bool? GenerateClientRequestId { get; set; } + + private IRedisOperations _redisOperations; + + public virtual IRedisOperations RedisOperations + { + get { return this._redisOperations; } + } + + /// + /// Initializes a new instance of the RedisManagementClient class. + /// + public RedisManagementClient() + : base() + { + this._redisOperations = new RedisOperations(this); + this._baseUri = new Uri("https://management.azure.com"); + this._apiVersion = "2014-04-01-preview"; + this.HttpClient.Timeout = TimeSpan.FromSeconds(300); + this.Initialize(); + } + + /// + /// Initializes a new instance of the RedisManagementClient class. + /// + /// + /// Optional. The set of delegating handlers to insert in the http + /// client pipeline. + /// + public RedisManagementClient(params DelegatingHandler[] handlers) + : base(handlers) + { + this._redisOperations = new RedisOperations(this); + this._baseUri = new Uri("https://management.azure.com"); + this._apiVersion = "2014-04-01-preview"; + this.HttpClient.Timeout = TimeSpan.FromSeconds(300); + this.Initialize(); + } + + /// + /// Initializes a new instance of the RedisManagementClient class. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The set of delegating handlers to insert in the http + /// client pipeline. + /// + public RedisManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) + : base(rootHandler, handlers) + { + this._redisOperations = new RedisOperations(this); + this._baseUri = new Uri("https://management.azure.com"); + this._apiVersion = "2014-04-01-preview"; + this.HttpClient.Timeout = TimeSpan.FromSeconds(300); + this.Initialize(); + } + + /// + /// Initializes a new instance of the RedisManagementClient class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Optional. The set of delegating handlers to insert in the http + /// client pipeline. + /// + public RedisManagementClient(Uri baseUri, params DelegatingHandler[] handlers) + : this(handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + this._baseUri = baseUri; + } + + /// + /// Initializes a new instance of the RedisManagementClient class. + /// + /// + /// Required. + /// + /// + /// Optional. The set of delegating handlers to insert in the http + /// client pipeline. + /// + public RedisManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) + : this(handlers) + { + if (credentials == null) + { + throw new ArgumentNullException("credentials"); + } + this._credentials = credentials; + + if (this.Credentials != null) + { + this.Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the RedisManagementClient class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Required. + /// + /// + /// Optional. The set of delegating handlers to insert in the http + /// client pipeline. + /// + public RedisManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) + : this(handlers) + { + if (baseUri == null) + { + throw new ArgumentNullException("baseUri"); + } + if (credentials == null) + { + throw new ArgumentNullException("credentials"); + } + this._baseUri = baseUri; + this._credentials = credentials; + + if (this.Credentials != null) + { + this.Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes client properties. + /// + private void Initialize() + { + SerializationSettings = new JsonSerializerSettings + { + Formatting = Formatting.Indented, + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver() + }; + SerializationSettings.Converters.Add(new ResourceJsonConverter()); + DeserializationSettings = new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver() + }; + DeserializationSettings.Converters.Add(new ResourceJsonConverter()); + DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); + } + } + + public static partial class RedisOperationsExtensions + { + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + public static RedisResource BeginCreateOrUpdate(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId) + { + return Task.Factory.StartNew((object s) => + { + return ((IRedisOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, name, parameters, subscriptionId); + } + , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + public static RedisSubResource BeginCreateOrUpdateSubResource(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId) + { + return Task.Factory.StartNew((object s) => + { + return ((IRedisOperations)s).BeginCreateOrUpdateSubResourceAsync(resourceGroupName, name, parameters, subscriptionId); + } + , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + public static Sku BeginCreateOrUpdateNonResource(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId) + { + return Task.Factory.StartNew((object s) => + { + return ((IRedisOperations)s).BeginCreateOrUpdateNonResourceAsync(resourceGroupName, name, parameters, subscriptionId); + } + , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public static async Task BeginCreateOrUpdateNonResourceAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + AzureOperationResponse result = await operations.BeginCreateOrUpdateNonResourceWithHttpMessagesAsync(resourceGroupName, name, parameters, subscriptionId, cancellationToken).ConfigureAwait(false); + return result.Body; + } + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public static async Task BeginCreateOrUpdateSubResourceAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + AzureOperationResponse result = await operations.BeginCreateOrUpdateSubResourceWithHttpMessagesAsync(resourceGroupName, name, parameters, subscriptionId, cancellationToken).ConfigureAwait(false); + return result.Body; + } + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public static async Task BeginCreateOrUpdateAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + AzureOperationResponse result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, name, parameters, subscriptionId, cancellationToken).ConfigureAwait(false); + return result.Body; + } + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + public static RedisResource CreateOrUpdate(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId) + { + return Task.Factory.StartNew((object s) => + { + return ((IRedisOperations)s).CreateOrUpdateAsync(resourceGroupName, name, parameters, subscriptionId); + } + , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static RedisResource Patch(this IRedisOperations operations, string resoruceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId) + { + return Task.Factory.StartNew((object s) => + { + return ((IRedisOperations)s).PatchAsync(resoruceGroupName, name, parameters, subscriptionId); + } + , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + public static Sku CreateOrUpdateNonResource(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId) + { + return Task.Factory.StartNew((object s) => + { + return ((IRedisOperations)s).CreateOrUpdateNonResourceAsync(resourceGroupName, name, parameters, subscriptionId); + } + , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + public static RedisSubResource CreateOrUpdateSubResource(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId) + { + return Task.Factory.StartNew((object s) => + { + return ((IRedisOperations)s).CreateOrUpdateSubResourceAsync(resourceGroupName, name, parameters, subscriptionId); + } + , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public static async Task CreateOrUpdateAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + AzureOperationResponse result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, name, parameters, subscriptionId, cancellationToken).ConfigureAwait(false); + return result.Body; + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static async Task PatchAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + AzureOperationResponse result = await operations.PatchWithHttpMessagesAsync(resourceGroupName, name, parameters, subscriptionId, cancellationToken).ConfigureAwait(false); + return result.Body; + } + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public static async Task CreateOrUpdateNonResourceAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + AzureOperationResponse result = await operations.CreateOrUpdateNonResourceWithHttpMessagesAsync(resourceGroupName, name, parameters, subscriptionId, cancellationToken).ConfigureAwait(false); + return result.Body; + } + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public static async Task CreateOrUpdateSubResourceAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + AzureOperationResponse result = await operations.CreateOrUpdateSubResourceWithHttpMessagesAsync(resourceGroupName, name, parameters, subscriptionId, cancellationToken).ConfigureAwait(false); + return result.Body; + } + + /// + /// Deletes a redis cache. This operation takes a while to complete. + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + public static void BeginDelete(this IRedisOperations operations, string resourceGroupName, string name, string subscriptionId) + { + Task.Factory.StartNew((object s) => + { + return ((IRedisOperations)s).BeginDeleteAsync(resourceGroupName, name, subscriptionId); + } + , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + public static void Delete(this IRedisOperations operations, string resourceGroupName, string name, string subscriptionId) + { + Task.Factory.StartNew((object s) => + { + return ((IRedisOperations)s).DeleteAsync(resourceGroupName, name, subscriptionId); + } + , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Deletes a redis cache. This operation takes a while to complete. + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public static async Task BeginDeleteAsync(this IRedisOperations operations, string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, name, subscriptionId, cancellationToken).ConfigureAwait(false); + return; + } + public static async Task DeleteAsync(this IRedisOperations operations, string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await operations.DeleteWithHttpMessagesAsync(resourceGroupName, name, subscriptionId, cancellationToken).ConfigureAwait(false); + return; + } + + public static Sku BeginPost(this IRedisOperations operations, string resourceGroupName, string name, string subscriptionId) + { + return Task.Factory.StartNew((object s) => + { + return ((IRedisOperations)s).BeginPostAsync(resourceGroupName, name, subscriptionId); + } + , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + public static Sku Post(this IRedisOperations operations, string resourceGroupName, string name, string subscriptionId) + { + return Task.Factory.StartNew((object s) => + { + return ((IRedisOperations)s).PostAsync(resourceGroupName, name, subscriptionId); + } + , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + public static async Task BeginPostAsync(this IRedisOperations operations, string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + AzureOperationResponse result = await operations.BeginPostWithHttpMessagesAsync(resourceGroupName, name, subscriptionId, cancellationToken).ConfigureAwait(false); + return result.Body; + } + public static async Task PostAsync(this IRedisOperations operations, string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + AzureOperationResponse result = await operations.PostWithHttpMessagesAsync(resourceGroupName, name, subscriptionId, cancellationToken).ConfigureAwait(false); + return result.Body; + } + + + /// + /// Gets a redis cache (resource description). + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + public static RedisResource Get(this IRedisOperations operations, string resourceGroupName, string name, string subscriptionId) + { + return Task.Factory.StartNew((object s) => + { + return ((IRedisOperations)s).GetAsync(resourceGroupName, name, subscriptionId); + } + , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Gets a redis cache (resource description). + /// + /// + /// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public static async Task GetAsync(this IRedisOperations operations, string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + AzureOperationResponse result = await operations.GetWithHttpMessagesAsync(resourceGroupName, name, subscriptionId, cancellationToken).ConfigureAwait(false); + return result.Body; + } + } + + public partial interface IRedisOperations + { + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + Task> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + Task> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + Task> PatchWithHttpMessagesAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, + CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + Task> BeginCreateOrUpdateSubResourceWithHttpMessagesAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + Task> CreateOrUpdateSubResourceWithHttpMessagesAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + Task> BeginCreateOrUpdateNonResourceWithHttpMessagesAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + Task> CreateOrUpdateNonResourceWithHttpMessagesAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Deletes a redis cache. This operation takes a while to complete. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + Task BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + Task DeleteWithHttpMessagesAsync(string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Gets a redis cache (resource description). + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + Task> GetWithHttpMessagesAsync(string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + Task> BeginPostWithHttpMessagesAsync(string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + Task> PostWithHttpMessagesAsync(string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + } + + internal partial class RedisOperations : IServiceOperations, IRedisOperations + { + /// + /// Initializes a new instance of the RedisOperations class. + /// + /// + /// Reference to the service client. + /// + internal RedisOperations(RedisManagementClient client) + { + this._client = client; + } + + private RedisManagementClient _client; + + /// + /// Gets a reference to the + /// Microsoft.Azure.Management.Redis.RedisManagementClient. + /// + public RedisManagementClient Client + { + get { return this._client; } + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public async Task> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, + string name, RedisCreateOrUpdateParameters parameters, + string subscriptionId, HttpMethod httpMethod, + CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // Validate + if (resourceGroupName == null) + { + throw new ArgumentNullException("resourceGroupName"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (parameters == null) + { + throw new ArgumentNullException("parameters"); + } + if (subscriptionId == null) + { + throw new ArgumentNullException("subscriptionId"); + } + + // Tracing + bool shouldTrace = ServiceClientTracing.IsEnabled; + string invocationId = null; + if (shouldTrace) + { + invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("resourceGroupName", resourceGroupName); + tracingParameters.Add("name", name); + tracingParameters.Add("parameters", parameters); + tracingParameters.Add("subscriptionId", subscriptionId); + ServiceClientTracing.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters); + } + + // Construct URL + string url = ""; + url = url + "/subscriptions/"; + url = url + Uri.EscapeDataString(subscriptionId); + url = url + "/resourceGroups/"; + url = url + Uri.EscapeDataString(resourceGroupName); + url = url + "/providers/Microsoft.Cache/Redis/"; + url = url + Uri.EscapeDataString(name); + string baseUrl = this.Client.BaseUri.AbsoluteUri; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl[baseUrl.Length - 1] == '/') + { + baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); + } + if (url[0] == '/') + { + url = url.Substring(1); + } + url = baseUrl + "/" + url; + url = url.Replace(" ", "%20"); + + // Create HTTP transport objects + HttpRequestMessage httpRequest = new HttpRequestMessage(); + httpRequest.Method = httpMethod; + httpRequest.RequestUri = new Uri(url); + + // Set Headers + + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); + } + + // Serialize Request + string requestContent = JsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); + httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); + httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); + + // Send Request + if (shouldTrace) + { + ServiceClientTracing.SendRequest(invocationId, httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); + if (shouldTrace) + { + ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); + } + HttpStatusCode statusCode = httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) + { + CloudError error = JsonConvert.DeserializeObject(responseContent, Client.DeserializationSettings); + CloudException ex = new CloudException(); + if (error != null) + { + ex = new CloudException(error.Message); + } + ex.Request = new HttpRequestMessageWrapper(httpRequest, requestContent); + ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); + + if (shouldTrace) + { + ServiceClientTracing.Error(invocationId, ex); + } + throw ex; + } + + // Create Result + AzureOperationResponse result = new AzureOperationResponse(); + result.Request = httpRequest; + result.Response = httpResponse; + + // Deserialize Response + if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) + { + RedisResource resultModel = JsonConvert.DeserializeObject(responseContent, this.Client.DeserializationSettings); + result.Body = resultModel; + } + + if (shouldTrace) + { + ServiceClientTracing.Exit(invocationId, result); + } + return result; + } + + public async Task> PatchWithHttpMessagesAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, + CancellationToken cancellationToken = default(CancellationToken)) + { + // Send Request + AzureOperationResponse response = await BeginCreateOrUpdateWithHttpMessagesAsync( + resourceGroupName, + name, + parameters, + subscriptionId, + new HttpMethod("PATCH"), + cancellationToken); + + Debug.Assert(response.Response.StatusCode == HttpStatusCode.OK || + response.Response.StatusCode == HttpStatusCode.Created || + response.Response.StatusCode == HttpStatusCode.Accepted); + + return await this.Client.GetPutOrPatchOperationResultAsync(response, + null, + cancellationToken); + } + public async Task> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, + RedisCreateOrUpdateParameters parameters, string subscriptionId, + CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // Send Request + AzureOperationResponse response = await BeginCreateOrUpdateWithHttpMessagesAsync( + resourceGroupName, + name, + parameters, + subscriptionId, + cancellationToken); + + Debug.Assert(response.Response.StatusCode == HttpStatusCode.OK || + response.Response.StatusCode == HttpStatusCode.Created || + response.Response.StatusCode == HttpStatusCode.Accepted); + + return await this.Client.GetPutOrPatchOperationResultAsync(response, + null, + cancellationToken); + } + + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public async Task> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, + string name, RedisCreateOrUpdateParameters parameters, + string subscriptionId, + CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + return await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, name, parameters, subscriptionId, HttpMethod.Put, cancellationToken); + } + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public async Task> BeginCreateOrUpdateNonResourceWithHttpMessagesAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // Validate + if (resourceGroupName == null) + { + throw new ArgumentNullException("resourceGroupName"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (parameters == null) + { + throw new ArgumentNullException("parameters"); + } + if (subscriptionId == null) + { + throw new ArgumentNullException("subscriptionId"); + } + + // Tracing + bool shouldTrace = ServiceClientTracing.IsEnabled; + string invocationId = null; + if (shouldTrace) + { + invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("resourceGroupName", resourceGroupName); + tracingParameters.Add("name", name); + tracingParameters.Add("parameters", parameters); + tracingParameters.Add("subscriptionId", subscriptionId); + ServiceClientTracing.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters); + } + + // Construct URL + string url = ""; + url = url + "/subscriptions/"; + url = url + Uri.EscapeDataString(subscriptionId); + url = url + "/resourceGroups/"; + url = url + Uri.EscapeDataString(resourceGroupName); + url = url + "/providers/Microsoft.Cache/Redis/"; + url = url + Uri.EscapeDataString(name); + string baseUrl = this.Client.BaseUri.AbsoluteUri; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl[baseUrl.Length - 1] == '/') + { + baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); + } + if (url[0] == '/') + { + url = url.Substring(1); + } + url = baseUrl + "/" + url; + url = url.Replace(" ", "%20"); + + // Create HTTP transport objects + HttpRequestMessage httpRequest = new HttpRequestMessage(); + httpRequest.Method = HttpMethod.Put; + httpRequest.RequestUri = new Uri(url); + + // Set Headers + + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); + } + + // Serialize Request + string requestContent = JsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); + httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); + httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); + + // Send Request + if (shouldTrace) + { + ServiceClientTracing.SendRequest(invocationId, httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); + if (shouldTrace) + { + ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); + } + HttpStatusCode statusCode = httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) + { + CloudError error = JsonConvert.DeserializeObject(responseContent, Client.DeserializationSettings); + CloudException ex = new CloudException(); + if (error != null) + { + ex = new CloudException(error.Message); + } + ex.Request = new HttpRequestMessageWrapper(httpRequest, requestContent); + ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); + + if (shouldTrace) + { + ServiceClientTracing.Error(invocationId, ex); + } + throw ex; + } + + // Create Result + AzureOperationResponse result = new AzureOperationResponse(); + result.Request = httpRequest; + result.Response = httpResponse; + + // Deserialize Response + if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) + { + Sku resultModel = JsonConvert.DeserializeObject(responseContent, this.Client.DeserializationSettings); + result.Body = resultModel; + } + + if (shouldTrace) + { + ServiceClientTracing.Exit(invocationId, result); + } + return result; + } + + public async Task> CreateOrUpdateNonResourceWithHttpMessagesAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // Send Request + AzureOperationResponse response = await BeginCreateOrUpdateNonResourceWithHttpMessagesAsync( + resourceGroupName, + name, + parameters, + subscriptionId, + cancellationToken); + + Debug.Assert(response.Response.StatusCode == HttpStatusCode.OK || + response.Response.StatusCode == HttpStatusCode.Created || + response.Response.StatusCode == HttpStatusCode.Accepted); + + return await this.Client.GetPutOrPatchOperationResultAsync(response, + null, + cancellationToken); + } + + /// + /// Create a redis cache, or replace (overwrite/recreate, with + /// potential downtime) an existing cache + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public async Task> BeginCreateOrUpdateSubResourceWithHttpMessagesAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // Validate + if (resourceGroupName == null) + { + throw new ArgumentNullException("resourceGroupName"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (parameters == null) + { + throw new ArgumentNullException("parameters"); + } + if (subscriptionId == null) + { + throw new ArgumentNullException("subscriptionId"); + } + + // Tracing + bool shouldTrace = ServiceClientTracing.IsEnabled; + string invocationId = null; + if (shouldTrace) + { + invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("resourceGroupName", resourceGroupName); + tracingParameters.Add("name", name); + tracingParameters.Add("parameters", parameters); + tracingParameters.Add("subscriptionId", subscriptionId); + ServiceClientTracing.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters); + } + + // Construct URL + string url = ""; + url = url + "/subscriptions/"; + url = url + Uri.EscapeDataString(subscriptionId); + url = url + "/resourceGroups/"; + url = url + Uri.EscapeDataString(resourceGroupName); + url = url + "/providers/Microsoft.Cache/Redis/"; + url = url + Uri.EscapeDataString(name); + string baseUrl = this.Client.BaseUri.AbsoluteUri; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl[baseUrl.Length - 1] == '/') + { + baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); + } + if (url[0] == '/') + { + url = url.Substring(1); + } + url = baseUrl + "/" + url; + url = url.Replace(" ", "%20"); + + // Create HTTP transport objects + HttpRequestMessage httpRequest = new HttpRequestMessage(); + httpRequest.Method = HttpMethod.Put; + httpRequest.RequestUri = new Uri(url); + + // Set Headers + + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); + } + + // Serialize Request + string requestContent = JsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); + httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); + httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); + + // Send Request + if (shouldTrace) + { + ServiceClientTracing.SendRequest(invocationId, httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); + if (shouldTrace) + { + ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); + } + HttpStatusCode statusCode = httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) + { + CloudError error = JsonConvert.DeserializeObject(responseContent, Client.DeserializationSettings); + CloudException ex = new CloudException(); + if (error != null) + { + ex = new CloudException(error.Message); + } + ex.Request = new HttpRequestMessageWrapper(httpRequest, requestContent); + ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); + + if (shouldTrace) + { + ServiceClientTracing.Error(invocationId, ex); + } + throw ex; + } + + // Create Result + AzureOperationResponse result = new AzureOperationResponse(); + result.Request = httpRequest; + result.Response = httpResponse; + + // Deserialize Response + if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) + { + RedisSubResource resultModel = JsonConvert.DeserializeObject(responseContent, this.Client.DeserializationSettings); + result.Body = resultModel; + } + + if (shouldTrace) + { + ServiceClientTracing.Exit(invocationId, result); + } + return result; + } + + public async Task> CreateOrUpdateSubResourceWithHttpMessagesAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // Send Request + AzureOperationResponse response = await BeginCreateOrUpdateSubResourceWithHttpMessagesAsync( + resourceGroupName, + name, + parameters, + subscriptionId, + cancellationToken); + + Debug.Assert(response.Response.StatusCode == HttpStatusCode.OK || + response.Response.StatusCode == HttpStatusCode.Created || + response.Response.StatusCode == HttpStatusCode.Accepted); + + return await this.Client.GetPutOrPatchOperationResultAsync(response, + null, + cancellationToken); + } + + /// + /// Deletes a redis cache. This operation takes a while to complete. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public async Task BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // Validate + if (resourceGroupName == null) + { + throw new ArgumentNullException("resourceGroupName"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (subscriptionId == null) + { + throw new ArgumentNullException("subscriptionId"); + } + + // Tracing + bool shouldTrace = ServiceClientTracing.IsEnabled; + string invocationId = null; + if (shouldTrace) + { + invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("resourceGroupName", resourceGroupName); + tracingParameters.Add("name", name); + tracingParameters.Add("subscriptionId", subscriptionId); + ServiceClientTracing.Enter(invocationId, this, "BeginDeleteAsync", tracingParameters); + } + + // Construct URL + string url = ""; + url = url + "/subscriptions/"; + url = url + Uri.EscapeDataString(subscriptionId); + url = url + "/resourceGroups/"; + url = url + Uri.EscapeDataString(resourceGroupName); + url = url + "/providers/Microsoft.Cache/Redis/"; + url = url + Uri.EscapeDataString(name); + string baseUrl = this.Client.BaseUri.AbsoluteUri; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl[baseUrl.Length - 1] == '/') + { + baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); + } + if (url[0] == '/') + { + url = url.Substring(1); + } + url = baseUrl + "/" + url; + url = url.Replace(" ", "%20"); + + // Create HTTP transport objects + HttpRequestMessage httpRequest = new HttpRequestMessage(); + httpRequest.Method = HttpMethod.Delete; + httpRequest.RequestUri = new Uri(url); + + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); + } + + // Send Request + if (shouldTrace) + { + ServiceClientTracing.SendRequest(invocationId, httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); + if (shouldTrace) + { + ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); + } + HttpStatusCode statusCode = httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.Created + && statusCode != HttpStatusCode.NotFound && statusCode != HttpStatusCode.NoContent) + { + CloudError error = JsonConvert.DeserializeObject(responseContent, Client.DeserializationSettings); + CloudException ex = new CloudException(); + if (error != null) + { + ex = new CloudException(error.Message); + } + ex.Request = new HttpRequestMessageWrapper(httpRequest, null); + ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); + if (shouldTrace) + { + ServiceClientTracing.Error(invocationId, ex); + } + throw ex; + } + + // Create Result + AzureOperationResponse result = new AzureOperationResponse(); + result.Request = httpRequest; + result.Response = httpResponse; + + if (shouldTrace) + { + ServiceClientTracing.Exit(invocationId, result); + } + return result; + } + + public async Task DeleteWithHttpMessagesAsync( + string resourceGroupName, + string name, + string subscriptionId, + CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // Send Request + AzureOperationResponse response = await BeginDeleteWithHttpMessagesAsync( + resourceGroupName, + name, + subscriptionId, + cancellationToken); + + Debug.Assert(response.Response.StatusCode == HttpStatusCode.OK || + response.Response.StatusCode == HttpStatusCode.Accepted || + response.Response.StatusCode == HttpStatusCode.Created || + response.Response.StatusCode == HttpStatusCode.NoContent); + + return await this.Client.GetPostOrDeleteOperationResultAsync(response, null, cancellationToken); + } + + public async Task> BeginPostWithHttpMessagesAsync(string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // Validate + if (resourceGroupName == null) + { + throw new ArgumentNullException("resourceGroupName"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (subscriptionId == null) + { + throw new ArgumentNullException("subscriptionId"); + } + + // Tracing + bool shouldTrace = ServiceClientTracing.IsEnabled; + string invocationId = null; + if (shouldTrace) + { + invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("resourceGroupName", resourceGroupName); + tracingParameters.Add("name", name); + tracingParameters.Add("subscriptionId", subscriptionId); + ServiceClientTracing.Enter(invocationId, this, "BeginDeleteAsync", tracingParameters); + } + + // Construct URL + string url = ""; + url = url + "/subscriptions/"; + url = url + Uri.EscapeDataString(subscriptionId); + url = url + "/resourceGroups/"; + url = url + Uri.EscapeDataString(resourceGroupName); + url = url + "/providers/Microsoft.Cache/Redis/"; + url = url + Uri.EscapeDataString(name); + string baseUrl = this.Client.BaseUri.AbsoluteUri; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl[baseUrl.Length - 1] == '/') + { + baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); + } + if (url[0] == '/') + { + url = url.Substring(1); + } + url = baseUrl + "/" + url; + url = url.Replace(" ", "%20"); + + // Create HTTP transport objects + HttpRequestMessage httpRequest = new HttpRequestMessage(); + httpRequest.Method = HttpMethod.Post; + httpRequest.RequestUri = new Uri(url); + + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); + } + + // Send Request + if (shouldTrace) + { + ServiceClientTracing.SendRequest(invocationId, httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); + if (shouldTrace) + { + ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); + } + HttpStatusCode statusCode = httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NotFound) + { + CloudError error = JsonConvert.DeserializeObject(responseContent, Client.DeserializationSettings); + CloudException ex = new CloudException(); + if (error != null) + { + ex = new CloudException(error.Message); + } + ex.Request = new HttpRequestMessageWrapper(httpRequest, null); + ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); + if (shouldTrace) + { + ServiceClientTracing.Error(invocationId, ex); + } + throw ex; + } + + // Create Result + AzureOperationResponse result = new AzureOperationResponse(); + result.Request = httpRequest; + result.Response = httpResponse; + result.Body = JsonConvert.DeserializeObject(responseContent, this.Client.DeserializationSettings); + + if (shouldTrace) + { + ServiceClientTracing.Exit(invocationId, result); + } + return result; + } + + public async Task> PostWithHttpMessagesAsync( + string resourceGroupName, + string name, + string subscriptionId, + CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // Send Request + AzureOperationResponse response = await BeginPostWithHttpMessagesAsync( + resourceGroupName, + name, + subscriptionId, + cancellationToken); + + Debug.Assert(response.Response.StatusCode == HttpStatusCode.OK || + response.Response.StatusCode == HttpStatusCode.Accepted || + response.Response.StatusCode == HttpStatusCode.Created); + + return await this.Client.GetPostOrDeleteOperationResultAsync(response, null, cancellationToken); + } + + + + /// + /// Gets a redis cache (resource description). + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public async Task> GetWithHttpMessagesAsync(string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // Validate + if (resourceGroupName == null) + { + throw new ArgumentNullException("resourceGroupName"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (subscriptionId == null) + { + throw new ArgumentNullException("subscriptionId"); + } + + // Tracing + bool shouldTrace = ServiceClientTracing.IsEnabled; + string invocationId = null; + if (shouldTrace) + { + invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("resourceGroupName", resourceGroupName); + tracingParameters.Add("name", name); + tracingParameters.Add("subscriptionId", subscriptionId); + ServiceClientTracing.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters); + } + + // Construct URL + string url = ""; + url = url + "/subscriptions/"; + url = url + Uri.EscapeDataString(subscriptionId); + url = url + "/resourceGroups/"; + url = url + Uri.EscapeDataString(resourceGroupName); + url = url + "/providers/Microsoft.Cache/Redis/"; + url = url + Uri.EscapeDataString(name); + string baseUrl = this.Client.BaseUri.AbsoluteUri; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl[baseUrl.Length - 1] == '/') + { + baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); + } + if (url[0] == '/') + { + url = url.Substring(1); + } + url = baseUrl + "/" + url; + url = url.Replace(" ", "%20"); + + // Create HTTP transport objects + HttpRequestMessage httpRequest = new HttpRequestMessage(); + httpRequest.Method = HttpMethod.Get; + httpRequest.RequestUri = new Uri(url); + + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); + } + + // Send Request + if (shouldTrace) + { + ServiceClientTracing.SendRequest(invocationId, httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); + if (shouldTrace) + { + ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); + } + HttpStatusCode statusCode = httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + if (statusCode != HttpStatusCode.OK) + { + CloudError error = JsonConvert.DeserializeObject(responseContent, Client.DeserializationSettings); + CloudException ex = new CloudException(); + if (error != null) + { + ex = new CloudException(error.Message); + } + ex.Request = new HttpRequestMessageWrapper(httpRequest, null); + ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); + if (shouldTrace) + { + ServiceClientTracing.Error(invocationId, ex); + } + throw ex; + } + + // Create Result + AzureOperationResponse result = new AzureOperationResponse(); + result.Request = httpRequest; + result.Response = httpResponse; + + // Deserialize Response + if (statusCode == HttpStatusCode.OK) + { + RedisResource resultModel = JsonConvert.DeserializeObject(responseContent, this.Client.DeserializationSettings); + result.Body = resultModel; + } + + if (shouldTrace) + { + ServiceClientTracing.Exit(invocationId, result); + } + return result; + } + + /// + /// Gets a redis cache (resource description). + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public async Task> GetSkuWithHttpMessagesAsync(string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // Validate + if (resourceGroupName == null) + { + throw new ArgumentNullException("resourceGroupName"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (subscriptionId == null) + { + throw new ArgumentNullException("subscriptionId"); + } + + // Tracing + bool shouldTrace = ServiceClientTracing.IsEnabled; + string invocationId = null; + if (shouldTrace) + { + invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("resourceGroupName", resourceGroupName); + tracingParameters.Add("name", name); + tracingParameters.Add("subscriptionId", subscriptionId); + ServiceClientTracing.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters); + } + + // Construct URL + string url = ""; + url = url + "/subscriptions/"; + url = url + Uri.EscapeDataString(subscriptionId); + url = url + "/resourceGroups/"; + url = url + Uri.EscapeDataString(resourceGroupName); + url = url + "/providers/Microsoft.Cache/Redis/"; + url = url + Uri.EscapeDataString(name); + string baseUrl = this.Client.BaseUri.AbsoluteUri; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl[baseUrl.Length - 1] == '/') + { + baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); + } + if (url[0] == '/') + { + url = url.Substring(1); + } + url = baseUrl + "/" + url; + url = url.Replace(" ", "%20"); + + // Create HTTP transport objects + HttpRequestMessage httpRequest = new HttpRequestMessage(); + httpRequest.Method = HttpMethod.Get; + httpRequest.RequestUri = new Uri(url); + + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); + } + + // Send Request + if (shouldTrace) + { + ServiceClientTracing.SendRequest(invocationId, httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); + if (shouldTrace) + { + ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); + } + HttpStatusCode statusCode = httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + if (statusCode != HttpStatusCode.OK) + { + CloudError error = JsonConvert.DeserializeObject(responseContent, Client.DeserializationSettings); + CloudException ex = new CloudException(); + if (error != null) + { + ex = new CloudException(error.Message); + } + ex.Request = new HttpRequestMessageWrapper(httpRequest, null); + ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); + if (shouldTrace) + { + ServiceClientTracing.Error(invocationId, ex); + } + throw ex; + } + + // Create Result + AzureOperationResponse result = new AzureOperationResponse(); + result.Request = httpRequest; + result.Response = httpResponse; + + // Deserialize Response + if (statusCode == HttpStatusCode.OK) + { + Sku resultModel = JsonConvert.DeserializeObject(responseContent, this.Client.DeserializationSettings); + result.Body = resultModel; + } + + if (shouldTrace) + { + ServiceClientTracing.Exit(invocationId, result); + } + return result; + } + + /// + /// Gets a redis cache (resource description). + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Required. + /// + /// + /// Cancellation token. + /// + public async Task> GetSubResourceWithHttpMessagesAsync(string resourceGroupName, string name, string subscriptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // Validate + if (resourceGroupName == null) + { + throw new ArgumentNullException("resourceGroupName"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (subscriptionId == null) + { + throw new ArgumentNullException("subscriptionId"); + } + + // Tracing + bool shouldTrace = ServiceClientTracing.IsEnabled; + string invocationId = null; + if (shouldTrace) + { + invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("resourceGroupName", resourceGroupName); + tracingParameters.Add("name", name); + tracingParameters.Add("subscriptionId", subscriptionId); + ServiceClientTracing.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters); + } + + // Construct URL + string url = ""; + url = url + "/subscriptions/"; + url = url + Uri.EscapeDataString(subscriptionId); + url = url + "/resourceGroups/"; + url = url + Uri.EscapeDataString(resourceGroupName); + url = url + "/providers/Microsoft.Cache/Redis/"; + url = url + Uri.EscapeDataString(name); + string baseUrl = this.Client.BaseUri.AbsoluteUri; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl[baseUrl.Length - 1] == '/') + { + baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); + } + if (url[0] == '/') + { + url = url.Substring(1); + } + url = baseUrl + "/" + url; + url = url.Replace(" ", "%20"); + + // Create HTTP transport objects + HttpRequestMessage httpRequest = new HttpRequestMessage(); + httpRequest.Method = HttpMethod.Get; + httpRequest.RequestUri = new Uri(url); + + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); + } + + // Send Request + if (shouldTrace) + { + ServiceClientTracing.SendRequest(invocationId, httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); + if (shouldTrace) + { + ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); + } + HttpStatusCode statusCode = httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + if (statusCode != HttpStatusCode.OK) + { + CloudError error = JsonConvert.DeserializeObject(responseContent, Client.DeserializationSettings); + CloudException ex = new CloudException(); + if (error != null) + { + ex = new CloudException(error.Message); + } + ex.Request = new HttpRequestMessageWrapper(httpRequest, null); + ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); + if (shouldTrace) + { + ServiceClientTracing.Error(invocationId, ex); + } + throw ex; + } + + // Create Result + AzureOperationResponse result = new AzureOperationResponse(); + result.Request = httpRequest; + result.Response = httpResponse; + + // Deserialize Response + if (statusCode == HttpStatusCode.OK) + { + RedisSubResource resultModel = JsonConvert.DeserializeObject(responseContent, this.Client.DeserializationSettings); + result.Body = resultModel; + } + + if (shouldTrace) + { + ServiceClientTracing.Exit(invocationId, result); + } + return result; + } + } +} diff --git a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/HttpMockServer.cs b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/HttpMockServer.cs index ad9d6d8212f4..c1b2558a1fc5 100644 --- a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/HttpMockServer.cs +++ b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/HttpMockServer.cs @@ -62,21 +62,23 @@ public static void Initialize(string callerIdentity, string testIdentity, HttpRe servers = new List(); records = new Records(Matcher); Variables = new Dictionary(); + string location = string.Empty; +#if FullNetFx var asmCollection = AppDomain.CurrentDomain.GetAssemblies(); - foreach(Assembly asm in asmCollection) + foreach (Assembly asm in asmCollection) { - if(asm.GetType(CallerIdentity) != null) - { -#if FullNetFx - string location = asm.Location; -#else - string location = AppContext.BaseDirectory; -#endif - RecordsDirectory = Path.Combine(location, RecordsDirectory); + if (asm.GetType(CallerIdentity) != null) + { + location = asm.Location; + break; } } +#elif netcoreapp11 || netcoreapp20 + location = AppContext.BaseDirectory; +#endif + RecordsDirectory = Path.Combine(location, RecordsDirectory); if (Mode == HttpRecorderMode.Playback) { @@ -271,11 +273,16 @@ public void InjectRecordEntry(RecordEntry record) } } - public static void Flush(string outputPath = null) + public static string Flush(string outputPath = null) { + string fileName = string.Empty; if (Mode == HttpRecorderMode.Record && records.Count > 0) { RecordEntryPack pack = new RecordEntryPack(); + string perfImpactFileName = string.Empty; + string fileDirectory = outputPath ?? RecordsDirectory; + fileDirectory = Path.Combine(fileDirectory, CallerIdentity); + RecorderUtilities.EnsureDirectoryExists(fileDirectory); lock (records) { @@ -287,23 +294,17 @@ public static void Flush(string outputPath = null) } } + fileName = (TestIdentity ?? "record") + ".json"; + fileName = Path.Combine(fileDirectory, fileName); pack.Variables = Variables; - - string fileDirectory = outputPath ?? RecordsDirectory; - string fileName = (TestIdentity ?? "record") + ".json"; - - fileDirectory = Path.Combine(fileDirectory, CallerIdentity); - - RecorderUtilities.EnsureDirectoryExists(fileDirectory); - pack.Names = names.Names; - fileName = Path.Combine(fileDirectory, fileName); - pack.Serialize(fileName); } servers.ForEach(s => s.Dispose()); + + return fileName; } public static HttpRecorderMode GetCurrentMode() @@ -327,6 +328,5 @@ public static HttpRecorderMode GetCurrentMode() return mode; } - } } \ No newline at end of file diff --git a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/Microsoft.Azure.Test.HttpRecorder.csproj b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/Microsoft.Azure.Test.HttpRecorder.csproj index c5e8837869f8..f58bef8d6674 100644 --- a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/Microsoft.Azure.Test.HttpRecorder.csproj +++ b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/Microsoft.Azure.Test.HttpRecorder.csproj @@ -7,6 +7,7 @@ Microsoft.Azure.Test.HttpRecorder Microsoft.Azure.Test.HttpRecorder Microsoft AutoRest ClientRuntime HttpRecorder REST;$(CommonNugetPackageTags) + $(DefaultItemExcludes);HttpRecorder.csproj net452;netcoreapp1.1;netcoreapp2.0 - - @@ -30,7 +29,6 @@ - @@ -42,4 +40,5 @@ + diff --git a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Model/RequestResponseInfo.cs b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Model/RequestResponseInfo.cs new file mode 100644 index 000000000000..15c9c5eef1cf --- /dev/null +++ b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Model/RequestResponseInfo.cs @@ -0,0 +1,273 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +namespace Microsoft.Azure.Test.HttpRecorder +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public class RequestResponseInfo + { + public RecordEntry InternalRecordEntry { get; internal set; } + + public LongRunningOperationInfo LroInfo { get; internal set; } + + public RequestResponseInfo(RecordEntry entry) + { + InternalRecordEntry = entry; + LroInfo = new LongRunningOperationInfo(entry); + } + } + + + public class LongRunningOperationInfo + { + #region Private fields + const string perfImpactKey = "RecordPlaybackPerfImpact"; + const string operationKey = "LroOperation"; + + #endregion + + public string OperationVerb { get; internal set; } + + public bool IsPlaybackPerfImpacted { get; internal set; } + + public LROHeaderInfo LroHeader { get; internal set; } + + public LroInfoId LroId { get; internal set; } + + public LongRunningOperationInfo(RecordEntry entry) + { + IsPlaybackPerfImpacted = false; + + LroHeader = new LROHeaderInfo(entry.RequestHeaders); + InitDataFromHeaders(entry.RequestHeaders); + LroId = new LroInfoId(entry.RequestHeaders); + } + + void InitDataFromHeaders(Dictionary> headers) + { + foreach(KeyValuePair> kv in headers) + { + if (kv.Key.Equals(operationKey, StringComparison.OrdinalIgnoreCase)) + { + OperationVerb = kv.Value?.SingleOrDefault(); + } + + if (kv.Key.Equals(perfImpactKey, StringComparison.OrdinalIgnoreCase)) + { + IsPlaybackPerfImpacted = Convert.ToBoolean(kv.Value?.SingleOrDefault()); + } + } + } + } + + + public class LroInfoId + { + #region Private fields + const string sessionIdKey = "LroSessionId"; + const string sessionPollingIdKey = "LroPollingId"; + const string perfImpactKey = "RecordPlaybackPerfImpact"; + const string operationKey = "LroOperation"; + + string _internalSessionPollingId { get; set; } + + #endregion + + public long SessionId { get; internal set; } + public long PollingId { get; internal set; } + + public int PollingCount { get; internal set; } + + + public LroInfoId(Dictionary> headers) + { + SessionId = 0; + PollingId = 0; + PollingCount = 0; + DeconstructSessionPollingId(headers); + } + + void DeconstructSessionPollingId(Dictionary> headers) + { + foreach (KeyValuePair> kv in headers) + { + if (kv.Key.Equals(sessionIdKey, StringComparison.OrdinalIgnoreCase)) + { + SessionId = Convert.ToInt64(kv.Value?.SingleOrDefault()); + } + + if (kv.Key.Equals(sessionPollingIdKey, StringComparison.OrdinalIgnoreCase)) + { + _internalSessionPollingId = kv.Value?.Single(); + } + } + + if (!string.IsNullOrEmpty(_internalSessionPollingId)) + { + string[] sessionPollingTokens = _internalSessionPollingId.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); + + if (sessionPollingTokens != null) + { + if (sessionPollingTokens.Length == 3) + { + PollingId = Convert.ToInt64(sessionPollingTokens[1]); + PollingCount = Convert.ToInt32(sessionPollingTokens[2]); + } + } + } + } + + #region operator overloaded + public static bool operator >(LroInfoId lhId, LroInfoId rhId) + { + bool greaterThan = false; + + if ((lhId.SessionId > rhId.SessionId) && + (lhId.PollingId > rhId.PollingId) && + (lhId.PollingCount > rhId.PollingCount)) + { + greaterThan = true; + } + else if ((lhId.SessionId == rhId.SessionId) && + (lhId.PollingId > rhId.PollingId) && + (lhId.PollingCount > rhId.PollingCount)) + { + greaterThan = true; + } + else if ((lhId.SessionId == rhId.SessionId) && + (lhId.PollingId == rhId.PollingId) && + (lhId.PollingCount > rhId.PollingCount)) + { + greaterThan = true; + } + else + greaterThan = false; + + return greaterThan; + } + + public static bool operator <(LroInfoId lhId, LroInfoId rhId) + { + bool lessThan = false; + + if ((lhId.SessionId < rhId.SessionId) && + (lhId.PollingId < rhId.PollingId) && + (lhId.PollingCount < rhId.PollingCount)) + { + lessThan = true; + } + else if((lhId.SessionId == rhId.SessionId) && + (lhId.PollingId < rhId.PollingId) && + (lhId.PollingCount < rhId.PollingCount)) + { + lessThan = true; + } + else if((lhId.SessionId == rhId.SessionId) && + (lhId.PollingId == rhId.PollingId) && + (lhId.PollingCount < rhId.PollingCount)) + { + lessThan = true; + } + else + lessThan = false; + + return lessThan; + } + + #endregion + + public override string ToString() + { + return _internalSessionPollingId; + } + } + + + public class LROHeaderInfo + { + const string LocHeaderKey = "Location"; + const string AzAsyncHeaderKey = "Azure-AsyncOperation"; + + + public string LocationHeader { get; private set; } + + public string AzureAsyncOperationHeader { get; private set; } + + LroHeaderKind HeaderKind { get; set; } + + public LROHeaderInfo(Dictionary> headers) + { + LocationHeader = string.Empty; + AzureAsyncOperationHeader = string.Empty; + + + foreach (KeyValuePair> kv in headers) + { + if (kv.Key.Equals(LocHeaderKey, StringComparison.OrdinalIgnoreCase)) + { + LocationHeader = kv.Value?.FirstOrDefault(); + } + + if (kv.Key.Equals(AzAsyncHeaderKey, StringComparison.OrdinalIgnoreCase)) + { + AzureAsyncOperationHeader = kv.Value?.FirstOrDefault(); + } + } + + UpdateHeaderKind(); + } + + private void UpdateHeaderKind() + { + bool validLoc = false, validAzAsync = false; + + if (IsValidUri(LocationHeader)) + { + validLoc = true; + HeaderKind = LroHeaderKind.Location; + } + + + if (IsValidUri(AzureAsyncOperationHeader)) + { + validAzAsync = true; + HeaderKind = LroHeaderKind.AzureAsync; + } + + + if (validLoc && validAzAsync) + HeaderKind = LroHeaderKind.Location_AzureAsync; + } + + private Uri GetValidUri(string uriString) + { + Uri validUri = null; + try + { + validUri = new Uri(uriString); + } + catch { } + + return validUri; + } + + private bool IsValidUri(string uriString) + { + if (GetValidUri(uriString) == null) + return false; + else + return true; + } + + public enum LroHeaderKind + { + Location, + AzureAsync, + Location_AzureAsync + } + } + +} diff --git a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/ProcessRecordedFiles.cs b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/ProcessRecordedFiles.cs new file mode 100644 index 000000000000..642f76b16acd --- /dev/null +++ b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/ProcessRecordedFiles.cs @@ -0,0 +1,60 @@ +using Microsoft.Azure.Test.HttpRecorder.ProcessRecordings.Processors; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Microsoft.Azure.Test.HttpRecorder.ProcessRecordings +{ + public class ProcessRecordedFiles + { + public string BackupFilePath { get; set; } + + public string OriginalFilePath { get; private set; } + List ProcessorList { get; } + + public RecordEntryPack OriginalRecordedPack { get; } + + public RecordEntryPack ProcessedPack { get; internal set; } + + public ProcessRecordedFiles() + { + ProcessorList = new List(); + } + + public ProcessRecordedFiles(string recordedFilePath): this() + { + if(File.Exists(recordedFilePath)) + { + OriginalRecordedPack = RecordEntryPack.Deserialize(recordedFilePath); + OriginalFilePath = recordedFilePath; + BackupFilePath = string.Concat(Path.Combine(Path.GetDirectoryName(recordedFilePath), Path.GetFileNameWithoutExtension(recordedFilePath)), ".pijson"); + } + } + + public void CompactLroPolling() + { + CompactLroEntries compactLro = new CompactLroEntries(); + compactLro.Process(OriginalRecordedPack); + ProcessedPack = compactLro.ProcessedEntryPack; + ProcessedPack.Variables = OriginalRecordedPack.Variables; + ProcessedPack.Names = OriginalRecordedPack.Names; + } + + public void SerializeCompactData(string filePath = "") + { + if(string.IsNullOrEmpty(filePath)) + { + ProcessedPack.Serialize(OriginalFilePath); + } + else + { + ProcessedPack.Serialize(filePath); + } + + OriginalRecordedPack.Serialize(BackupFilePath); + } + } +} diff --git a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Processors/CompactLroEntries.cs b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Processors/CompactLroEntries.cs new file mode 100644 index 000000000000..c096b6c7c24a --- /dev/null +++ b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Processors/CompactLroEntries.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Microsoft.Azure.Test.HttpRecorder.ProcessRecordings.Processors +{ + public class CompactLroEntries: IRecordingProcessor + { + Queue EntryPackCloneQueue; + Stack lroStack; + + RecordEntryPack _processedEntryPack; + + public CompactLroEntries() + { + EntryPackCloneQueue = new Queue(); + lroStack = new Stack(); + } + + public string ProcessorName { get => "CompactLroEntries"; protected set => ProcessorName = value; } + + public RecordEntryPack ProcessedEntryPack + { + get + { + if(_processedEntryPack == null) + { + _processedEntryPack = new RecordEntryPack(); + } + + return _processedEntryPack; + } + } + + public void Process(RecordEntryPack recordEntryPack) + { + foreach(RecordEntry rec in recordEntryPack.Entries) + { + if(IsLroEntry(rec)) + { + lroStack.Push(rec); + } + else + { + if(lroStack.Any()) + { + UpdateCloneQueueFromStack(); + } + + EntryPackCloneQueue.Enqueue(rec); + } + } + + + if(lroStack.Any()) + { + UpdateCloneQueueFromStack(); + } + + if(EntryPackCloneQueue.Any()) + { + ProcessedEntryPack.Entries = EntryPackCloneQueue.ToList(); + } + } + + + private void UpdateCloneQueueFromStack() + { + int takeLastCount = 2; + if (lroStack.Any()) + { + Stack tempStack = new Stack(); + int popCount = 1; + + while (lroStack.Count > 0) + { + if (popCount <= takeLastCount) + { + tempStack.Push(lroStack.Pop()); + popCount++; + } + else + { + lroStack.Clear(); + break; + } + } + + while(tempStack.Count > 0) + { + EntryPackCloneQueue.Enqueue(tempStack.Pop()); + } + } + } + + + internal bool IsLroEntry(RecordEntry re) + { + return re.RequestHeaders.ContainsKey("RecordPlaybackPerfImpact"); + } + } + + public interface IRecordingProcessor + { + string ProcessorName { get; } + + void Process(RecordEntryPack recordEntryPack); + + RecordEntryPack ProcessedEntryPack { get; } + } +} diff --git a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Startup.cs b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Startup.cs new file mode 100644 index 000000000000..e97eec26a551 --- /dev/null +++ b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Startup.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Microsoft.Azure.Test.HttpRecorder.ProcessRecordings +{ + public class Startup + { + static void Main(string[] args) + { + + } + } +} diff --git a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Utilities/Logger.cs b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Utilities/Logger.cs new file mode 100644 index 000000000000..7f37634522bc --- /dev/null +++ b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/ProcessRecordings/Utilities/Logger.cs @@ -0,0 +1,187 @@ +#if FullNetFx && NETCOREAPP2_0 + +namespace Microsoft.Azure.Test.HttpRecorder.ProcessRecordings.Utilities +{ + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + /// + /// Exposes static methods for logging various events (e.g. debug, + /// informational, warning, etc.). This class cannot be inherited. + /// + /// + /// All methods of the Logger class are static + /// and can therefore be called without creating an instance of the class. + /// + + + public sealed class Logger + { + private static TraceSource defaultTraceSource = new TraceSource("defaultTraceSource"); + + private Logger() { } // all members are static + + /// + /// Flushes all the trace listeners in the trace listener collection. + /// + + public static void Flush() + { + defaultTraceSource.Flush(); + } + + /// + /// Logs an event to the trace listeners using the specified + /// event type and message. + /// + /// One of the System.Diagnostics.TraceEventType + /// values that specifies the type of event being logged. + /// The message to log. + + public static void Log(TraceEventType eventType, string message) + { +#if DEBUG + // Some debug listeners (e.g. DbgView.exe) don't buffer output, so + // Debug.Write() is effectively the same as Debug.WriteLine(). + // For optimal appearance in these listeners, format the output + // for a single call to Debug.WriteLine(). + StringBuilder sb = new StringBuilder(); + + sb.Append(eventType.ToString()); + sb.Append(": "); + sb.Append(message); + + string formattedMessage = sb.ToString(); + Debug.WriteLine(formattedMessage); +#endif + defaultTraceSource.TraceEvent(eventType, 0, message); + } + + /// + /// Logs a debug event to the trace listeners using the specified + /// format string and arguments. + /// + /// An System.IFormatProvider that supplies + /// culture-specific formatting information. + /// A composite format string. + /// An System.Object array containing zero or more + /// objects to format. + + public static void LogDebug(IFormatProvider provider, string format, params object[] args) + { + string message = string.Format(provider, format, args); + LogDebug(message); + } + + /// + /// Logs a debug event to the trace listeners. + /// + /// The message to log. + public static void LogDebug(string message) + { + Log(TraceEventType.Verbose, message); + } + + /// + /// Logs a critical event to the trace listeners using the specified + /// format string and arguments. + /// + /// An System.IFormatProvider that supplies + /// culture-specific formatting information. + /// A composite format string. + /// An System.Object array containing zero or more + /// objects to format. + public static void LogCritical(IFormatProvider provider, string format, params object[] args) + { + string message = string.Format(provider, format, args); + LogCritical(message); + } + + /// + /// Logs a critical event to the trace listeners. + /// + /// The message to log. + public static void LogCritical(string message) + { + Log(TraceEventType.Critical, message); + } + + /// + /// Logs an error event to the trace listeners using the specified + /// format string and arguments. + /// + /// An System.IFormatProvider that supplies + /// culture-specific formatting information. + /// A composite format string. + /// An System.Object array containing zero or more + /// objects to format. + public static void LogError(IFormatProvider provider, string format, params object[] args) + { + string message = string.Format(provider, format, args); + LogError(message); + } + + /// + /// Logs an error event to the trace listeners. + /// + /// The message to log. + public static void LogError(string message) + { + Log(TraceEventType.Error, message); + } + + /// + /// Logs an informational event to the trace listeners using the specified + /// format string and arguments. + /// + /// An System.IFormatProvider that supplies + /// culture-specific formatting information. + /// A composite format string. + /// An System.Object array containing zero or more + /// objects to format. + public static void LogInfo(IFormatProvider provider, string format, params object[] args) + { + string message = string.Format(provider, format, args); + LogInfo(message); + } + + + /// + /// Logs an informational event to the trace listeners. + /// + /// The message to log. + public static void LogInfo(string message) + { + Log(TraceEventType.Information, message); + } + + /// + /// Logs a warning event to the trace listeners using the specified + /// format string and arguments. + /// + /// An System.IFormatProvider that supplies + /// culture-specific formatting information. + /// A composite format string. + /// An System.Object array containing zero or more + /// objects to format. + public static void LogWarning(IFormatProvider provider, string format, params object[] args) + { + string message = string.Format(provider, format, args); + LogWarning(message); + } + + /// + /// Logs a warning event to the trace listeners. + /// + /// The message to log. + public static void LogWarning(string message) + { + Log(TraceEventType.Warning, message); + } + } +} +#endif \ No newline at end of file diff --git a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/Properties/AssemblyInfo.cs b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/Properties/AssemblyInfo.cs index e9635340e46e..ce79d2be18d3 100644 --- a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/Properties/AssemblyInfo.cs +++ b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/Properties/AssemblyInfo.cs @@ -7,19 +7,33 @@ // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: ComVisible(false)] -[assembly: Guid("c77934b2-fc7c-4f23-b2e1-12da90bfe716")] +#if HttpRecorderApp + [assembly: Guid("5FE894DE-2618-4048-ACC1-0E215D8B2B69")] + [assembly: AssemblyVersion("1.0.0.0")] + [assembly: AssemblyFileVersion("1.0.0.0")] + [assembly: AssemblyTitle("HttpRecorder")] + [assembly: AssemblyDescription("")] + [assembly: AssemblyConfiguration("")] + [assembly: AssemblyCompany("")] + [assembly: AssemblyProduct("HttpRecorder")] + [assembly: AssemblyCopyright("Copyright ©")] + [assembly: AssemblyTrademark("")] + [assembly: AssemblyCulture("")] +#else + [assembly: ComVisible(false)] + [assembly: Guid("c77934b2-fc7c-4f23-b2e1-12da90bfe716")] + [assembly: AssemblyVersion("1.0.0.0")] + [assembly: AssemblyFileVersion("1.10.99.0")] + [assembly: AssemblyTitle("Microsoft.Azure.Test.HttpRecorder")] + [assembly: AssemblyDescription("")] + [assembly: AssemblyConfiguration("")] + [assembly: AssemblyCompany("")] + [assembly: AssemblyProduct("Microsoft.Azure.Test.HttpRecorder")] + [assembly: AssemblyCopyright("Copyright ©")] + [assembly: AssemblyTrademark("")] + [assembly: AssemblyCulture("")] +#endif -[assembly: AssemblyTitle("HttpRecorder")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("HttpRecorder")] -[assembly: AssemblyCopyright("Copyright ©")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.10.99.0")] \ No newline at end of file diff --git a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/RecordEntry.cs b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/RecordEntry.cs index d27147eb3aac..a24ff56ba38f 100644 --- a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/RecordEntry.cs +++ b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/RecordEntry.cs @@ -20,7 +20,6 @@ public class RecordEntry public string RequestMethod { get; set; } - //[JsonConverter(typeof(StringEnumConverter))] [JsonIgnore] public RecordEntryContentType RequestContentType { get; set; } @@ -28,7 +27,6 @@ public class RecordEntry public Dictionary> RequestHeaders { get; set; } - //[JsonConverter(typeof(StringEnumConverter))] [JsonIgnore] public RecordEntryContentType ResponseContentType { get; set; } public Dictionary> ResponseHeaders { get; set; } @@ -42,6 +40,9 @@ public RecordEntry() } + public RecordEntry(RecordEntry recEntry) : this(recEntry.GetResponse()) + { } + public RecordEntry(HttpResponseMessage response) { HttpRequestMessage request = response.RequestMessage; @@ -108,6 +109,9 @@ private RecordEntryContentType DetectContentType(HttpContent content) } } + /// + /// Request/Response content type enum + /// public enum RecordEntryContentType { Binary, diff --git a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/RecordEntryPack.cs b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/RecordEntryPack.cs index 6519fb66b60c..45e3f21c34ba 100644 --- a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/RecordEntryPack.cs +++ b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/RecordEntryPack.cs @@ -1,12 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. +using Newtonsoft.Json; using System.Collections.Generic; +using System.Linq; namespace Microsoft.Azure.Test.HttpRecorder { public class RecordEntryPack { + [JsonIgnore] + public List RRInfoRecordEntry { get; set; } + public List Entries { get; set; } public Dictionary> Names { get; set; } public Dictionary Variables { get; set; } @@ -14,6 +19,7 @@ public class RecordEntryPack public RecordEntryPack() { Entries = new List(); + RRInfoRecordEntry = new List(); } public static RecordEntryPack Deserialize(string path) @@ -21,6 +27,18 @@ public static RecordEntryPack Deserialize(string path) return RecorderUtilities.DeserializeJson(path); } + public RecordEntryPack Deserialize(string path, bool extractMetaData) + { + RecordEntryPack rePack = Deserialize(path); + + if (rePack != null && extractMetaData) + { + RRInfoRecordEntry.AddRange(rePack.Entries.Select((re) => new RequestResponseInfo(re))); + } + + return rePack; + } + public void Serialize(string path) { RecorderUtilities.SerializeJson(this, path); diff --git a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/RecorderUtilities.cs b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/RecorderUtilities.cs index 4c9b9117dc17..7b1198239cfb 100644 --- a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/RecorderUtilities.cs +++ b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/RecorderUtilities.cs @@ -184,7 +184,7 @@ public static void SerializeJson(T data, string path) path, JsonConvert.SerializeObject(data, Formatting.Indented, new JsonSerializerSettings { TypeNameAssemblyFormat = 0, // Simple = 0, Full = 1 (we have an issue with duplicate namespace between newtonsoft and System.Runtime.Serialization. Once we upgrade to newtonsoft 11.x, we can start using TypeNameAssemblyFormatHandling instead) - TypeNameHandling = TypeNameHandling.None, + TypeNameHandling = TypeNameHandling.None })); } @@ -219,8 +219,7 @@ public static void EnsureDirectoryExists(string dir) { HttpMockServer.FileSystemUtilsObject.CreateDirectory(dir); } - } - + } public static string EncodeUriAsBase64(Uri requestUri) { return RecorderUtilities.EncodeUriAsBase64(requestUri.PathAndQuery); diff --git a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/Records.cs b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/Records.cs index e30f43628d53..1e204f76c06e 100644 --- a/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/Records.cs +++ b/src/SdkCommon/TestFramework/Microsoft.Azure.Test.HttpRecorder/Records.cs @@ -5,7 +5,6 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Runtime.CompilerServices; namespace Microsoft.Azure.Test.HttpRecorder { diff --git a/src/SdkCommon/TestFramework/TestFramework.Tests/TestEnvironment/ConnectionStringParseTests.cs b/src/SdkCommon/TestFramework/TestFramework.Tests/TestEnvironment/ConnectionStringParseTests.cs index 21788736c066..85c60fc595c6 100644 --- a/src/SdkCommon/TestFramework/TestFramework.Tests/TestEnvironment/ConnectionStringParseTests.cs +++ b/src/SdkCommon/TestFramework/TestFramework.Tests/TestEnvironment/ConnectionStringParseTests.cs @@ -44,6 +44,19 @@ public void EmptyString() Assert.False(string.IsNullOrEmpty(connStr.ParseErrors)); } + [Fact] + public void OptimizeRecordedFileKVPair() + { + string emptyStr = CreateConnStrWithAllPossibleValues(); + ConnectionString cs = new ConnectionString(); + cs.Parse(emptyStr); + Assert.False(cs.GetValue(ConnectionStringKeys.OptimizeRecordedFileKey)); + + cs.KeyValuePairs[ConnectionStringKeys.OptimizeRecordedFileKey] = "true"; + Assert.True(cs.GetValue(ConnectionStringKeys.OptimizeRecordedFileKey)); + } + + [Fact] public void NullString() { diff --git a/src/SdkCommon/TestFramework/TestRecordAndFramework.sln b/src/SdkCommon/TestFramework/TestRecordAndFramework.sln index fb016ae17cc1..19b933002165 100644 --- a/src/SdkCommon/TestFramework/TestRecordAndFramework.sln +++ b/src/SdkCommon/TestFramework/TestRecordAndFramework.sln @@ -19,10 +19,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestFramework.Tests", "Test EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Rest.ClientRuntime.Azure", "..\ClientRuntime.Azure\ClientRuntime.Azure\Microsoft.Rest.ClientRuntime.Azure.csproj", "{4432CB88-1E91-4F61-8F74-D792A7919898}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Rest.ClientRuntime.Azure.Authentication", "..\ClientRuntime.Azure.Authentication\Microsoft.Rest.ClientRuntime.Azure.Authentication.csproj", "{FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestFramework.Net45Tests", "TestFramework.Net45Tests\TestFramework.Net45Tests.csproj", "{BF15E4C6-C018-4F42-B315-5841DB505FE4}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Rest.ClientRuntime.Azure.Authentication", "..\Auth\Az.Auth\Az.Authentication\Microsoft.Rest.ClientRuntime.Azure.Authentication.csproj", "{84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -131,22 +131,6 @@ Global {4432CB88-1E91-4F61-8F74-D792A7919898}.Portable-Release|Any CPU.Build.0 = Release|Any CPU {4432CB88-1E91-4F61-8F74-D792A7919898}.Release|Any CPU.ActiveCfg = Release|Any CPU {4432CB88-1E91-4F61-8F74-D792A7919898}.Release|Any CPU.Build.0 = Release|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Net40-Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Net40-Debug|Any CPU.Build.0 = Debug|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Net40-Release|Any CPU.ActiveCfg = Release|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Net40-Release|Any CPU.Build.0 = Release|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Net45-Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Net45-Debug|Any CPU.Build.0 = Debug|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Net45-Release|Any CPU.ActiveCfg = Release|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Net45-Release|Any CPU.Build.0 = Release|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Portable-Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Portable-Debug|Any CPU.Build.0 = Debug|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Portable-Release|Any CPU.ActiveCfg = Release|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Portable-Release|Any CPU.Build.0 = Release|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8}.Release|Any CPU.Build.0 = Release|Any CPU {BF15E4C6-C018-4F42-B315-5841DB505FE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BF15E4C6-C018-4F42-B315-5841DB505FE4}.Debug|Any CPU.Build.0 = Debug|Any CPU {BF15E4C6-C018-4F42-B315-5841DB505FE4}.Net40-Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -163,6 +147,22 @@ Global {BF15E4C6-C018-4F42-B315-5841DB505FE4}.Portable-Release|Any CPU.Build.0 = Release|Any CPU {BF15E4C6-C018-4F42-B315-5841DB505FE4}.Release|Any CPU.ActiveCfg = Release|Any CPU {BF15E4C6-C018-4F42-B315-5841DB505FE4}.Release|Any CPU.Build.0 = Release|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Net40-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Net40-Debug|Any CPU.Build.0 = Debug|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Net40-Release|Any CPU.ActiveCfg = Release|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Net40-Release|Any CPU.Build.0 = Release|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Net45-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Net45-Debug|Any CPU.Build.0 = Debug|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Net45-Release|Any CPU.ActiveCfg = Release|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Net45-Release|Any CPU.Build.0 = Release|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Portable-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Portable-Debug|Any CPU.Build.0 = Debug|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Portable-Release|Any CPU.ActiveCfg = Release|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Portable-Release|Any CPU.Build.0 = Release|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -172,7 +172,10 @@ Global {0C5B4DEE-560F-4C86-810E-9BB1F32B8F3C} = {BF007157-DF27-4FDC-849C-1F0E19D630B2} {6A242C2E-019F-4300-B874-5E365EB43041} = {BF007157-DF27-4FDC-849C-1F0E19D630B2} {4432CB88-1E91-4F61-8F74-D792A7919898} = {DAFBDA03-D3BB-4ADB-8A0E-D2D60E99FFB8} - {FBF4BD4B-447D-442B-A2C1-46DB2F00AAC8} = {DAFBDA03-D3BB-4ADB-8A0E-D2D60E99FFB8} {BF15E4C6-C018-4F42-B315-5841DB505FE4} = {BF007157-DF27-4FDC-849C-1F0E19D630B2} + {84E4B6AC-0C58-4A80-B251-3C9BCF18FA9D} = {DAFBDA03-D3BB-4ADB-8A0E-D2D60E99FFB8} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {C2C7B386-8BD7-49E1-8995-EED30D7113D2} EndGlobalSection EndGlobal