-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathResourcesController.cs
301 lines (262 loc) · 13.3 KB
/
ResourcesController.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
using Microsoft.Azure.Graph.RBAC.Version1_6;
using Microsoft.Azure.Management.Authorization;
using Microsoft.Azure.Management.ManagementGroups;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.ServiceManagemenet.Common.Models;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using ManagedGroups = Microsoft.Azure.Management.ManagementGroups;
using TestEnvironmentFactory = Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestEnvironmentFactory;
namespace Microsoft.Azure.Commands.Resources.Test.ScenarioTests
{
public sealed class ResourcesController
{
private readonly EnvironmentSetupHelper _helper;
private const string TenantIdKey = "TenantId";
private const string DomainKey = "Domain";
private const string SubscriptionIdKey = "SubscriptionId";
public GraphRbacManagementClient GraphClient { get; private set; }
public ResourceManagementClient ResourceManagementClient { get; private set; }
public FeatureClient FeatureClient { get; private set; }
public Internal.Subscriptions.SubscriptionClient SubscriptionClient { get; private set; }
public AuthorizationManagementClient AuthorizationManagementClient { get; private set; }
public ManagedGroups.ManagementGroupsAPIClient ManagementGroupsApiClient { get; private set; }
public string UserDomain { get; private set; }
public static ResourcesController NewInstance => new ResourcesController();
public ResourcesController()
{
_helper = new EnvironmentSetupHelper();
}
public void RunPsTest(XunitTracingInterceptor interceptor, params string[] scripts)
{
var sf = new StackTrace().GetFrame(1);
var callingClassType = sf.GetMethod().ReflectedType?.ToString();
var mockName = sf.GetMethod().Name;
RunPsTestWorkflow(
interceptor,
() => scripts,
// no custom cleanup
null,
callingClassType,
mockName);
}
public void RunPsTestWorkflow(
XunitTracingInterceptor interceptor,
Func<string[]> scriptBuilder,
Action cleanup,
string callingClassType,
string mockName)
{
_helper.TracingInterceptor = interceptor;
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("Microsoft.Resources", null);
d.Add("Microsoft.Features", null);
d.Add("Microsoft.Authorization", null);
d.Add("Providers.Test", null);
var providersToIgnore = new Dictionary<string, string>();
providersToIgnore.Add("Microsoft.Azure.Management.ResourceManager.ResourceManagementClient", "2016-07-01");
providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01");
HttpMockServer.Matcher = new ResourcesRecordMatcher(true, d, providersToIgnore);
HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords");
using (MockContext context = MockContext.Start(callingClassType, mockName))
{
_helper.SetupEnvironment(AzureModule.AzureResourceManager);
SetupManagementClients(context);
var callingClassName = callingClassType
.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
.Last();
_helper.SetupModules(AzureModule.AzureResourceManager,
"ScenarioTests\\Common.ps1",
"ScenarioTests\\" + callingClassName + ".ps1",
_helper.RMProfileModule,
_helper.RMResourceModule,
_helper.RMInsightsModule);
try
{
if (scriptBuilder != null)
{
var psScripts = scriptBuilder();
if (psScripts != null)
{
_helper.RunPowerShellTest(psScripts);
}
}
}
finally
{
cleanup?.Invoke();
}
}
}
private void SetupManagementClients(MockContext context)
{
ResourceManagementClient = GetResourceManagementClient(context);
SubscriptionClient = GetSubscriptionClient(context);
AuthorizationManagementClient = GetAuthorizationManagementClient(context);
GraphClient = GetGraphClient(context);
ManagementGroupsApiClient = GetManagementGroupsApiClient(context);
FeatureClient = GetFeatureClient(context);
var testEnvironment = TestEnvironmentFactory.GetTestEnvironment();
var credentials = new SubscriptionCloudCredentialsAdapter(
testEnvironment.TokenInfo[TokenAudience.Management],
testEnvironment.SubscriptionId);
HttpClientHelperFactory.Instance = new TestHttpClientHelperFactory(credentials);
_helper.SetupManagementClients(ResourceManagementClient,
SubscriptionClient,
AuthorizationManagementClient,
GraphClient,
FeatureClient,
ManagementGroupsApiClient);
}
private GraphRbacManagementClient GetGraphClient(MockContext context)
{
var environment = TestEnvironmentFactory.GetTestEnvironment();
string tenantId = null;
if (HttpMockServer.Mode == HttpRecorderMode.Record)
{
tenantId = environment.Tenant;
UserDomain = String.IsNullOrEmpty(environment.UserName) ? String.Empty : environment.UserName.Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries).Last();
HttpMockServer.Variables[TenantIdKey] = tenantId;
HttpMockServer.Variables[DomainKey] = UserDomain;
}
else if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
if (HttpMockServer.Variables.ContainsKey(TenantIdKey))
{
tenantId = HttpMockServer.Variables[TenantIdKey];
}
if (HttpMockServer.Variables.ContainsKey(DomainKey))
{
UserDomain = HttpMockServer.Variables[DomainKey];
}
if (HttpMockServer.Variables.ContainsKey(SubscriptionIdKey))
{
AzureRmProfileProvider.Instance.Profile.DefaultContext.Subscription.Id = HttpMockServer.Variables[SubscriptionIdKey];
}
}
var client = context.GetGraphServiceClient<GraphRbacManagementClient>(environment);
client.TenantID = tenantId;
if (AzureRmProfileProvider.Instance != null &&
AzureRmProfileProvider.Instance.Profile != null &&
AzureRmProfileProvider.Instance.Profile.DefaultContext != null &&
AzureRmProfileProvider.Instance.Profile.DefaultContext.Tenant != null)
{
AzureRmProfileProvider.Instance.Profile.DefaultContext.Tenant.Id = client.TenantID;
}
return client;
}
private AuthorizationManagementClient GetAuthorizationManagementClient(MockContext context)
{
return context.GetServiceClient<AuthorizationManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
}
private FeatureClient GetFeatureClient(MockContext context)
{
return context.GetServiceClient<FeatureClient>(TestEnvironmentFactory.GetTestEnvironment());
}
private ResourceManagementClient GetResourceManagementClient(MockContext context)
{
return context.GetServiceClient<ResourceManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
}
private Internal.Subscriptions.SubscriptionClient GetSubscriptionClient(MockContext context)
{
return context.GetServiceClient<Internal.Subscriptions.SubscriptionClient>(TestEnvironmentFactory.GetTestEnvironment());
}
private ManagedGroups.ManagementGroupsAPIClient GetManagementGroupsApiClient(MockContext context)
{
return context.GetServiceClient<ManagedGroups.ManagementGroupsAPIClient>(TestEnvironmentFactory.GetTestEnvironment());
}
/// <summary>
/// The test http client helper factory.
/// </summary>
private class TestHttpClientHelperFactory : HttpClientHelperFactory
{
/// <summary>
/// The subscription cloud credentials.
/// </summary>
private readonly SubscriptionCloudCredentials credential;
/// <summary>
/// Initializes a new instance of the <see cref="TestHttpClientHelperFactory"/> class.
/// </summary>
/// <param name="credentials"></param>
public TestHttpClientHelperFactory(SubscriptionCloudCredentials credentials)
{
credential = credentials;
}
/// <summary>
/// Creates new instances of the <see cref="HttpClientHelper"/> class.
/// </summary>
/// <param name="credentials">The credentials.</param>
/// <param name="headerValues">The headers.</param>
public override HttpClientHelper CreateHttpClientHelper(SubscriptionCloudCredentials credentials, IEnumerable<ProductInfoHeaderValue> headerValues, Dictionary<string, string> cmdletHeaderValues)
{
return new HttpClientHelperImpl(credentials: credential, headerValues: headerValues, cmdletHeaderValues: cmdletHeaderValues);
}
/// <summary>
/// An implementation of the <see cref="HttpClientHelper"/> abstract class.
/// </summary>
private class HttpClientHelperImpl : HttpClientHelper
{
/// <summary>
/// Initializes new instances of the <see cref="HttpClientHelperImpl"/> class.
/// </summary>
/// <param name="credentials">The credentials.</param>
/// <param name="headerValues">The headers.</param>
public HttpClientHelperImpl(SubscriptionCloudCredentials credentials, IEnumerable<ProductInfoHeaderValue> headerValues, Dictionary<string, string> cmdletHeaderValues)
: base(credentials: credentials, headerValues: headerValues, cmdletHeaderValues: cmdletHeaderValues)
{
}
/// <summary>
/// Creates an <see cref="HttpClient"/>
/// </summary>
/// <param name="primaryHandlers">The handlers that will be added to the top of the chain.</param>
public override HttpClient CreateHttpClient(params DelegatingHandler[] primaryHandlers)
{
return base.CreateHttpClient(HttpMockServer.CreateInstance().AsArray().Concat(primaryHandlers).ToArray());
}
}
}
//https://gist.github.com/markcowl/4d907da7ce40f2e424e8d0625887b82e
public class SubscriptionCloudCredentialsAdapter : SubscriptionCloudCredentials
{
private readonly ServiceClientCredentials _wrappedCreds;
public SubscriptionCloudCredentialsAdapter(ServiceClientCredentials credentials, string subscriptionId)
{
_wrappedCreds = credentials;
SubscriptionId = subscriptionId;
}
public override string SubscriptionId { get; }
public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return _wrappedCreds.ProcessHttpRequestAsync(request, cancellationToken);
}
}
}
}