-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathAppServiceIntegrationTest.cs
210 lines (179 loc) · 11.3 KB
/
AppServiceIntegrationTest.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.ResourceManager;
using Azure.ResourceManager.AppService;
using Azure.ResourceManager.AppService.Models;
using Azure.ResourceManager.Resources;
using Calamari.Azure;
using Calamari.Azure.AppServices;
using Calamari.AzureAppService.Azure;
using Calamari.AzureAppService.Json;
using Calamari.CloudAccounts;
using Calamari.Testing;
using FluentAssertions;
using Newtonsoft.Json;
using NUnit.Framework;
using Octostache;
using AccountVariables = Calamari.AzureAppService.Azure.AccountVariables;
namespace Calamari.AzureAppService.Tests
{
public abstract class AppServiceIntegrationTest
{
protected string ClientId { get; private set; }
protected string ClientSecret { get; private set; }
protected string TenantId { get; private set; }
protected string SubscriptionId { get; private set; }
protected string ResourceGroupName { get; private set; }
protected string ResourceGroupLocation { get; private set; }
protected string greeting = "Calamari";
protected ArmClient ArmClient { get; private set; }
protected SubscriptionResource SubscriptionResource { get; private set; }
protected ResourceGroupResource ResourceGroupResource { get; private set; }
protected WebSiteResource WebSiteResource { get; private protected set; }
private readonly HttpClient client = new HttpClient();
protected virtual string DefaultResourceGroupLocation => RandomAzureRegion.GetRandomRegionWithExclusions();
static readonly CancellationTokenSource CancellationTokenSource = new CancellationTokenSource();
readonly CancellationToken cancellationToken = CancellationTokenSource.Token;
[OneTimeSetUp]
public async Task Setup()
{
var resourceManagementEndpointBaseUri =
Environment.GetEnvironmentVariable(AccountVariables.ResourceManagementEndPoint) ?? DefaultVariables.ResourceManagementEndpoint;
var activeDirectoryEndpointBaseUri =
Environment.GetEnvironmentVariable(AccountVariables.ActiveDirectoryEndPoint) ?? DefaultVariables.ActiveDirectoryEndpoint;
ResourceGroupName = $"{DateTime.UtcNow:yyyyMMdd}-{Guid.NewGuid():N}";
ClientId = await ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId, cancellationToken);
ClientSecret = await ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword, cancellationToken);
TenantId = await ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId, cancellationToken);
SubscriptionId = await ExternalVariables.Get(ExternalVariable.AzureSubscriptionId, cancellationToken);
ResourceGroupLocation = Environment.GetEnvironmentVariable("AZURE_NEW_RESOURCE_REGION") ?? DefaultResourceGroupLocation;
TestContext.Progress.WriteLine($"Resource group location: {ResourceGroupLocation}");
var servicePrincipalAccount = new AzureServicePrincipalAccount(SubscriptionId,
ClientId,
TenantId,
ClientSecret,
"AzureGlobalCloud",
resourceManagementEndpointBaseUri,
activeDirectoryEndpointBaseUri);
ArmClient = servicePrincipalAccount.CreateArmClient(retryOptions =>
{
retryOptions.MaxRetries = 5;
retryOptions.Mode = RetryMode.Exponential;
retryOptions.Delay = TimeSpan.FromSeconds(2);
// AzureAppServiceDeployContainerBehaviorFixture.AzureLinuxContainerSlotDeploy occasional timeout at default 100 seconds
retryOptions.NetworkTimeout = TimeSpan.FromSeconds(200);
});
//create the resource group
SubscriptionResource = ArmClient.GetSubscriptionResource(SubscriptionResource.CreateResourceIdentifier(SubscriptionId));
var response = await SubscriptionResource
.GetResourceGroups()
.CreateOrUpdateAsync(WaitUntil.Completed,
ResourceGroupName,
new ResourceGroupData(new AzureLocation(ResourceGroupLocation))
{
Tags =
{
// give them an expiry of 14 days so if the tests fail to clean them up
// they will be automatically cleaned up by the Sandbox cleanup process
// We keep them for 14 days just in case we need to do debugging/investigation
["LifetimeInDays"] = "14"
}
},
cancellationToken);
ResourceGroupResource = response.Value;
await ConfigureTestResources(ResourceGroupResource);
}
protected abstract Task ConfigureTestResources(ResourceGroupResource resourceGroup);
[OneTimeTearDown]
public virtual async Task Cleanup()
{
await ArmClient.GetResourceGroupResource(ResourceGroupResource.CreateResourceIdentifier(SubscriptionId, ResourceGroupName))
.DeleteAsync(WaitUntil.Started, cancellationToken: cancellationToken);
}
protected async Task AssertContent(string hostName, string actualText, string rootPath = null)
{
var response = await RetryPolicies.TestsTransientHttpErrorsPolicy.ExecuteAsync(async context =>
{
var r = await client.GetAsync($"https://{hostName}/{rootPath}");
if (!r.IsSuccessStatusCode)
{
var messageContent = await r.Content.ReadAsStringAsync();
TestContext.WriteLine($"Unable to retrieve content from https://{hostName}/{rootPath}, failed with: {messageContent}");
}
r.EnsureSuccessStatusCode();
return r;
},
contextData: new Dictionary<string, object>());
var result = await response.Content.ReadAsStringAsync();
result.Should().Contain(actualText);
}
protected static async Task DoWithRetries(int retries, Func<Task> action, int secondsBetweenRetries)
{
foreach (var retry in Enumerable.Range(1, retries))
{
try
{
await action();
break;
}
catch
{
if (retry == retries)
throw;
await Task.Delay(secondsBetweenRetries * 1000);
}
}
}
protected void AddAzureVariables(CommandTestBuilderContext context)
{
AddAzureVariables(context.Variables);
}
protected void AddAzureVariables(VariableDictionary variables)
{
variables.Add(AccountVariables.ClientId, ClientId);
variables.Add(AccountVariables.Password, ClientSecret);
variables.Add(AccountVariables.TenantId, TenantId);
variables.Add(AccountVariables.SubscriptionId, SubscriptionId);
variables.Add(SpecialVariables.Action.Azure.ResourceGroupName, ResourceGroupName);
variables.Add(SpecialVariables.Action.Azure.WebAppName, WebSiteResource.Data.Name);
}
protected async Task<(AppServicePlanResource, WebSiteResource)> CreateAppServicePlanAndWebApp(
ResourceGroupResource resourceGroup,
AppServicePlanData appServicePlanData = null,
WebSiteData webSiteData = null)
{
appServicePlanData ??= new AppServicePlanData(resourceGroup.Data.Location)
{
Sku = new AppServiceSkuDescription
{
Name = "P1V3",
Tier = "PremiumV3"
}
};
var servicePlanResponse = await resourceGroup.GetAppServicePlans()
.CreateOrUpdateAsync(WaitUntil.Completed,
resourceGroup.Data.Name,
appServicePlanData);
webSiteData ??= new WebSiteData(resourceGroup.Data.Location);
webSiteData.AppServicePlanId = servicePlanResponse.Value.Id;
var webSiteResponse = await resourceGroup.GetWebSites()
.CreateOrUpdateAsync(WaitUntil.Completed,
resourceGroup.Data.Name,
webSiteData);
return (servicePlanResponse.Value, webSiteResponse.Value);
}
protected (string json, IEnumerable<AppSetting> setting) BuildAppSettingsJson(IEnumerable<(string name, string value, bool isSlotSetting)> settings)
{
var appSettings = settings.Select(setting => new AppSetting
{ Name = setting.name, Value = setting.value, SlotSetting = setting.isSlotSetting });
return (JsonConvert.SerializeObject(appSettings), appSettings);
}
}
}