-
Notifications
You must be signed in to change notification settings - Fork 191
/
TestHelper.cs
499 lines (444 loc) · 19.1 KB
/
TestHelper.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.AppService.Fluent;
using Microsoft.Azure.Management.Batch.Fluent;
using Microsoft.Azure.Management.BatchAI.Fluent;
using Microsoft.Azure.Management.Cdn.Fluent;
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.ContainerInstance.Fluent;
using Microsoft.Azure.Management.ContainerRegistry.Fluent;
using Microsoft.Azure.Management.ContainerService.Fluent;
using Microsoft.Azure.Management.CosmosDB.Fluent;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.Graph.RBAC.Fluent;
using Microsoft.Azure.Management.KeyVault.Fluent;
using Microsoft.Azure.Management.Locks.Fluent;
using Microsoft.Azure.Management.Network.Fluent;
using Microsoft.Azure.Management.Redis.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Search.Fluent;
using Microsoft.Azure.Management.ServiceBus.Fluent;
using Microsoft.Azure.Management.Sql.Fluent;
using Microsoft.Azure.Management.Storage.Fluent;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.Azure;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Xunit.Abstractions;
namespace Fluent.Tests.Common
{
public static class TestHelper
{
public static ITestOutputHelper TestLogger { get; set; }
private static string authFilePath = Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION");
private static string clientId = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID");
private static string tenantId = Environment.GetEnvironmentVariable("AZURE_TENANT_ID");
private static string clientSecret = Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET");
private static string subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
public static void Delay(int millisecondsTimeout)
{
if(HttpMockServer.Mode != HttpRecorderMode.Playback)
{
Thread.Sleep(millisecondsTimeout);
}
}
public static void Delay(TimeSpan timeout)
{
if (HttpMockServer.Mode != HttpRecorderMode.Playback)
{
Thread.Sleep(timeout);
}
}
public static string ReadLine()
{
if (HttpMockServer.Mode == HttpRecorderMode.Record)
{
// NOTE: This test requires a manual action to be performed before it can continue recording.
// Please go up the execution stack (or check test output window) to see what steps needs
// to be performed before you can continue execution.
if (Debugger.IsAttached)
{
Debugger.Break();
return "[Running in interactive mode]";
}
throw new NotSupportedException(
"This test requires a manual action to be performed before it can continue recording. " +
"Please run it with a debugger attached to be able to perform required steps in the Record mode.");
}
return "[Running in non interactive mode]";
}
public static void WriteLine(string format, params string[] parameters)
{
WriteLine(string.Format(format, parameters));
}
public static void WriteLine(string message)
{
if(TestLogger != null)
{
TestLogger.WriteLine(message);
}
else
{
Console.WriteLine(message);
}
}
public static IAzure CreateRollupClient()
{
return CreateMockedManager(c => Microsoft.Azure.Management.Fluent.Azure.Configure()
.WithDelegatingHandlers(GetHandlers())
.Authenticate(c)
.WithSubscription(c.DefaultSubscriptionId));
}
public static Microsoft.Azure.Management.Fluent.Azure.IAuthenticated CreateAuthenticatedClient()
{
return CreateMockedManager(c => Microsoft.Azure.Management.Fluent.Azure.Configure()
.WithDelegatingHandlers(GetHandlers())
.Authenticate(c));
}
public static INetworkManager CreateNetworkManager()
{
return CreateMockedManager(c => NetworkManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static IComputeManager CreateComputeManager()
{
return CreateMockedManager(c => ComputeManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static IAuthorizationManager CreateAuthorizationManager()
{
return CreateMockedManager(c => AuthorizationManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static IResourceManager CreateResourceManager()
{
return CreateMockedManager(c => Microsoft.Azure.Management.ResourceManager.Fluent.ResourceManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c)
.WithSubscription(c.DefaultSubscriptionId));
}
public static IBatchManager CreateBatchManager()
{
return CreateMockedManager(c => BatchManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static ISqlManager CreateSqlManager()
{
return CreateMockedManager(c => SqlManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static IAppServiceManager CreateAppServiceManager()
{
return CreateMockedManager(c => AppServiceManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static IKeyVaultManager CreateKeyVaultManager()
{
return CreateMockedManager(c => KeyVaultManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static ICdnManager CreateCdnManager()
{
return CreateMockedManager(c => CdnManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static IRedisManager CreateRedisManager()
{
return CreateMockedManager(c => RedisManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static IStorageManager CreateStorageManager()
{
return CreateMockedManager(c => StorageManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static ISearchManager CreateSearchManager()
{
return CreateMockedManager(c => SearchManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static IServiceBusManager CreateServiceBusManager()
{
return CreateMockedManager(c => ServiceBusManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static IContainerInstanceManager CreateContainerInstanceManager()
{
return CreateMockedManager(c => ContainerInstanceManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static IRegistryManager CreateRegistryManager()
{
return CreateMockedManager(c => RegistryManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static IContainerServiceManager CreateContainerServiceManager()
{
return CreateMockedManager(c => ContainerServiceManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static ICosmosDBManager CreateCosmosDB()
{
return CreateMockedManager(c => CosmosDBManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static IGraphRbacManager CreateGraphRbacManager()
{
return CreateMockedManager(c => GraphRbacManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.TenantId));
}
public static IBatchAIManager CreateBatchAIManager()
{
return CreateMockedManager(c => BatchAIManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c, c.DefaultSubscriptionId));
}
public static Microsoft.Azure.Management.ResourceManager.Fluent.ResourceManager.IAuthenticated Authenticate()
{
return CreateMockedManager(c => Microsoft.Azure.Management.ResourceManager.Fluent.ResourceManager
.Configure()
.WithDelegatingHandlers(GetHandlers())
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Authenticate(c));
}
private static T CreateMockedManager<T>(Func<AzureCredentials, T> builder)
{
AzureCredentials credentials;
if (authFilePath != null || HttpMockServer.Mode == HttpRecorderMode.Playback)
{
credentials = SdkContext.AzureCredentialsFactory.FromFile(authFilePath);
}
else
{
credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);
credentials.WithDefaultSubscription(subscriptionId);
}
var manager = builder.Invoke(credentials);
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
// In Playback mode set all the LongRunning timeouts to 0
var managersList = new List<object>();
var managerTraversalStack = new Stack<object>();
managerTraversalStack.Push(manager);
while (managerTraversalStack.Count > 0)
{
var stackedObject = managerTraversalStack.Pop();
// if not a rollup package
if (!(stackedObject is IAzure))
{
managersList.Add(stackedObject);
var resourceManager = stackedObject.GetType().GetProperty("ResourceManager");
if (resourceManager != null)
{
managersList.Add(resourceManager.GetValue(stackedObject));
}
}
foreach (var obj in stackedObject
.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(f => f.FieldType.GetInterfaces().Contains(typeof(IManagerBase)))
.Select(f => (IManagerBase)f.GetValue(stackedObject)))
{
managerTraversalStack.Push(obj);
}
}
foreach (var m in managersList)
{
m.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(f => f.FieldType.GetInterfaces().Contains(typeof(IAzureClient)))
.Select(f => (IAzureClient)f.GetValue(m))
.ToList()
.ForEach(c => c.LongRunningOperationRetryTimeout = 0);
m.GetType().GetProperties().Where(n => n.Name.Equals("Inner"))
.Select(f => (IAzureClient)f.GetValue(m))
.ToList()
.ForEach(c => c.LongRunningOperationRetryTimeout = 0);
}
}
return manager;
}
public static DelegatingHandler[] GetHandlers()
{
HttpMockServer server;
try
{
server = HttpMockServer.CreateInstance();
}
catch (InvalidOperationException)
{
// mock server has never been initialized, we will need to initialize it.
HttpMockServer.Initialize("TestEnvironment", "InitialCreation");
server = HttpMockServer.CreateInstance();
}
var handlers = new List<DelegatingHandler>();
if (!MockServerInHandlers(handlers))
{
handlers.Add(server);
}
// TODO - ans - Needs token Credential here to delete the resource group.
//ResourceGroupCleaner cleaner = new ResourceGroupCleaner(credentials);
//handlers.Add(cleaner);
// TODO - ans - We need to add this to clean resource group.
//undoHandlers.Add(cleaner);
return handlers.ToArray();
}
private static bool MockServerInHandlers(List<DelegatingHandler> handlers)
{
var result = false;
foreach (var handler in handlers)
{
if (HandlerContains<HttpMockServer>(handler))
{
result = true;
break;
}
}
return result;
}
private static bool HandlerContains<T1>(DelegatingHandler handler)
{
return (handler is T1 || (handler.InnerHandler != null
&& handler.InnerHandler is DelegatingHandler
&& HandlerContains<T1>(handler.InnerHandler as DelegatingHandler)));
}
public static void DeprovisionAgentInLinuxVM(string host, int port, string userName, string password)
{
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
return;
}
Console.WriteLine("Trying to de-provision: " + host);
Console.WriteLine("ssh connection status: " + TrySsh(
host,
port,
userName,
password,
"sudo waagent -deprovision+user --force"));
}
public static async Task<HttpResponseMessage> CheckAddress(string url)
{
if (HttpMockServer.Mode != HttpRecorderMode.Playback)
{
using (var client = new HttpClient())
{
return await client.GetAsync(url);
}
}
return new HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new StringContent("Hello world from linux 4")
};
}
public static string TrySsh(
string host,
int port,
string userName,
string password,
string commandToExecute)
{
string commandOutput = null;
var backoffTime = 30 * 1000;
var retryCount = 3;
while (retryCount > 0)
{
using (var sshClient = new SshClient(host, port, userName, password))
{
try
{
sshClient.Connect();
if (commandToExecute != null)
{
using (var command = sshClient.CreateCommand(commandToExecute))
{
commandOutput = command.Execute();
}
}
break;
}
catch (Exception exception)
{
retryCount--;
if (retryCount == 0)
{
throw exception;
}
}
finally
{
try
{
sshClient.Disconnect();
}
catch { }
}
}
TestHelper.Delay(backoffTime);
}
return commandOutput;
}
}
}