-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathManagementRecordedTestBase.cs
234 lines (196 loc) · 9.32 KB
/
ManagementRecordedTestBase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Azure.Core;
using Azure.Core.TestFramework;
using Azure.ResourceManager.Resources;
using Castle.DynamicProxy;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Azure.ResourceManager.TestFramework
{
public abstract class ManagementRecordedTestBase<TEnvironment> : RecordedTestBase<TEnvironment>
where TEnvironment : TestEnvironment, new()
{
protected ResourceGroupCleanupPolicy ResourceGroupCleanupPolicy = new ResourceGroupCleanupPolicy();
protected ResourceGroupCleanupPolicy OneTimeResourceGroupCleanupPolicy = new ResourceGroupCleanupPolicy();
protected ManagementGroupCleanupPolicy ManagementGroupCleanupPolicy = new ManagementGroupCleanupPolicy();
protected ManagementGroupCleanupPolicy OneTimeManagementGroupCleanupPolicy = new ManagementGroupCleanupPolicy();
protected ArmClient GlobalClient { get; private set; }
public TestEnvironment SessionEnvironment { get; private set; }
public TestRecording SessionRecording { get; private set; }
private ArmClient _cleanupClient;
private WaitUntil _waitForCleanup;
protected ManagementRecordedTestBase(bool isAsync, RecordedTestMode? mode = default) : base(isAsync, mode)
{
AdditionalInterceptors = new[] { new ManagementInterceptor(this) };
SessionEnvironment = new TEnvironment();
SessionEnvironment.Mode = Mode;
Initialize();
}
private void Initialize()
{
_waitForCleanup = Mode == RecordedTestMode.Live ? WaitUntil.Completed : WaitUntil.Started;
}
private ArmClient GetCleanupClient()
{
if (Mode != RecordedTestMode.Playback)
{
return new ArmClient(
TestEnvironment.Credential,
TestEnvironment.SubscriptionId,
new ArmClientOptions() { Environment = GetEnvironment(TestEnvironment.ResourceManagerUrl)});
}
return null;
}
protected TClient InstrumentClientExtension<TClient>(TClient client) => (TClient)InstrumentClient(typeof(TClient), client, new IInterceptor[] { new ManagementInterceptor(this) });
protected ArmClient GetArmClient(ArmClientOptions clientOptions = default, string subscriptionId = default)
{
var options = InstrumentClientOptions(clientOptions ?? new ArmClientOptions());
options.Environment = GetEnvironment(TestEnvironment.ResourceManagerUrl);
options.AddPolicy(ResourceGroupCleanupPolicy, HttpPipelinePosition.PerCall);
options.AddPolicy(ManagementGroupCleanupPolicy, HttpPipelinePosition.PerCall);
return InstrumentClient(new ArmClient(
TestEnvironment.Credential,
subscriptionId ?? TestEnvironment.SubscriptionId,
options), new IInterceptor[] { new ManagementInterceptor(this) });
}
private ArmEnvironment GetEnvironment(string endpoint)
{
if (string.IsNullOrEmpty(endpoint))
{
return ArmEnvironment.AzurePublicCloud;
}
var baseUri = new Uri(endpoint);
if (baseUri == ArmEnvironment.AzurePublicCloud.Endpoint)
return ArmEnvironment.AzurePublicCloud;
if (baseUri == ArmEnvironment.AzureChina.Endpoint)
return ArmEnvironment.AzureChina;
if (baseUri == ArmEnvironment.AzureGermany.Endpoint)
return ArmEnvironment.AzureGermany;
if (baseUri == ArmEnvironment.AzureGovernment.Endpoint)
return ArmEnvironment.AzureGovernment;
return new ArmEnvironment(new Uri(endpoint), TestEnvironment.ServiceManagementUrl ?? $"{endpoint}/.default");
}
[SetUp]
protected void CreateCleanupClient()
{
_cleanupClient ??= GetCleanupClient();
}
[TearDown]
protected void CleanupResourceGroups()
{
if (Mode != RecordedTestMode.Playback)
{
Parallel.ForEach(ResourceGroupCleanupPolicy.ResourceGroupsCreated, resourceGroup =>
{
try
{
SubscriptionResource sub = _cleanupClient.GetSubscriptions().Exists(TestEnvironment.SubscriptionId)
? _cleanupClient.GetSubscriptions().Get(TestEnvironment.SubscriptionId)
: null;
sub?.GetResourceGroups().Get(resourceGroup).Value.Delete(_waitForCleanup);
}
catch (RequestFailedException e) when (e.Status == 404)
{
//we assume the test case cleaned it up if it no longer exists.
}
});
Parallel.ForEach(ManagementGroupCleanupPolicy.ManagementGroupsCreated, mgmtGroupId =>
{
try
{
_cleanupClient.GetManagementGroupResource(new ResourceIdentifier(mgmtGroupId)).Delete(_waitForCleanup);
}
catch (RequestFailedException e) when (e.Status == 404 || e.Status == 403)
{
//we assume the test case cleaned it up if it no longer exists.
}
});
}
}
private async Task StartSessionRecordingAsync()
{
// Only create test recordings for the latest version of the service
TestContext.TestAdapter test = TestContext.CurrentContext.Test;
if (Mode != RecordedTestMode.Live &&
test.Properties.ContainsKey("SkipRecordings"))
{
throw new IgnoreException((string)test.Properties.Get("SkipRecordings"));
}
SessionRecording = await CreateTestRecordingAsync(Mode, GetSessionFilePath());
SessionEnvironment.SetRecording(SessionRecording);
ValidateClientInstrumentation = SessionRecording.HasRequests;
}
protected async Task StopSessionRecordingAsync()
{
if (ValidateClientInstrumentation)
{
throw new InvalidOperationException("The test didn't instrument any clients but had recordings. Please call InstrumentClient for the client being recorded.");
}
if (SessionRecording != null)
{
await SessionRecording.DisposeAsync();
}
GlobalClient = null;
}
[OneTimeSetUp]
public async Task OneTimeSetUp()
{
if (!HasOneTimeSetup())
return;
await StartSessionRecordingAsync();
var options = InstrumentClientOptions(new ArmClientOptions(), SessionRecording);
options.AddPolicy(OneTimeResourceGroupCleanupPolicy, HttpPipelinePosition.PerCall);
options.AddPolicy(OneTimeManagementGroupCleanupPolicy, HttpPipelinePosition.PerCall);
options.Environment = GetEnvironment(SessionEnvironment.ResourceManagerUrl);
GlobalClient = InstrumentClient(new ArmClient(
SessionEnvironment.Credential,
SessionEnvironment.SubscriptionId,
options), new IInterceptor[] { new ManagementInterceptor(this) });
}
private bool HasOneTimeSetup()
{
HashSet<Type> types = new HashSet<Type>();
Type type = GetType();
Type endType = typeof(ManagementRecordedTestBase<TEnvironment>);
while (type != endType)
{
types.Add(type);
type = type.BaseType;
}
var methods = GetType().GetMethods().Where(m => types.Contains(m.DeclaringType));
foreach (var method in methods)
{
foreach (var attr in method.GetCustomAttributes(false))
{
if (attr is OneTimeSetUpAttribute)
return true;
}
}
return false;
}
[OneTimeTearDown]
public void OneTimeCleanupResourceGroups()
{
if (Mode != RecordedTestMode.Playback)
{
Parallel.ForEach(OneTimeResourceGroupCleanupPolicy.ResourceGroupsCreated, resourceGroup =>
{
SubscriptionResource sub = _cleanupClient.GetSubscriptions().Exists(SessionEnvironment.SubscriptionId)
? _cleanupClient.GetSubscriptions().Get(SessionEnvironment.SubscriptionId)
: null;
sub?.GetResourceGroups().Get(resourceGroup).Value.Delete(_waitForCleanup);
});
Parallel.ForEach(OneTimeManagementGroupCleanupPolicy.ManagementGroupsCreated, mgmtGroupId =>
{
_cleanupClient.GetManagementGroupResource(new ResourceIdentifier(mgmtGroupId)).Delete(_waitForCleanup);
});
}
if (!(GlobalClient is null))
throw new InvalidOperationException("StopSessionRecording was never called please make sure you call that at the end of your OneTimeSetup");
}
}
}