/
CSharpEndToEndTests.cs
432 lines (364 loc) · 16.4 KB
/
CSharpEndToEndTests.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
// Copyright (c) .NET Foundation. 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.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Logging;
using Microsoft.Azure.WebJobs.Script.Diagnostics;
using Microsoft.Azure.WebJobs.Script.Rpc;
using Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.WebJobs.Script.Tests;
using Newtonsoft.Json.Linq;
using Xunit;
namespace Microsoft.Azure.WebJobs.Script.Tests.EndToEnd
{
[Trait(TestTraits.Category, TestTraits.EndToEnd)]
[Trait(TestTraits.Group, nameof(CSharpEndToEndTests))]
public class CSharpEndToEndTests : EndToEndTestsBase<CSharpEndToEndTests.TestFixture>
{
public CSharpEndToEndTests(TestFixture fixture) : base(fixture)
{
}
[Fact]
public async Task ManualTrigger_Invoke_Succeeds()
{
await ManualTrigger_Invoke_SucceedsTest();
}
[Fact]
public async Task QueueTriggerToBlob()
{
await QueueTriggerToBlobTest();
}
[Fact(Skip = "Not yet enabled.")]
public void MobileTables()
{
// await MobileTablesTest(isDotNet: true);
}
[Fact(Skip = "Not yet enabled.")]
public void NotificationHub()
{
// await NotificationHubTest("NotificationHubOut");
}
[Fact(Skip = "Not yet enabled.")]
public void NotificationHub_Out_Notification()
{
// await NotificationHubTest("NotificationHubOutNotification");
}
[Fact(Skip = "Not yet enabled.")]
public void NotificationHubNative()
{
// await NotificationHubTest("NotificationHubNative");
}
[Fact(Skip = "Not yet enabled.")]
public void MobileTablesTable()
{
//var id = Guid.NewGuid().ToString();
//Dictionary<string, object> arguments = new Dictionary<string, object>()
//{
// { "input", id }
//};
//await Fixture.Host.CallAsync("MobileTableTable", arguments);
//await WaitForMobileTableRecordAsync("Item", id);
}
[Fact]
public async Task FunctionLogging_Succeeds()
{
Fixture.Host.ClearLogMessages();
string functionName = "Scenarios";
string guid1 = Guid.NewGuid().ToString();
string guid2 = Guid.NewGuid().ToString();
var inputObject = new JObject
{
{ "Scenario", "logging" },
{ "Container", "scenarios-output" },
{ "Value", $"{guid1};{guid2}" }
};
await Fixture.Host.BeginFunctionAsync(functionName, inputObject);
IList<string> logs = null;
await TestHelpers.Await(() =>
{
logs = Fixture.Host.GetLogMessages().Select(p => p.FormattedMessage).Where(p => p != null).ToArray();
return logs.Any(p => p.Contains(guid2));
});
logs.Single(p => p.EndsWith($"From TraceWriter: {guid1}"));
logs.Single(p => p.EndsWith($"From ILogger: {guid2}"));
// Make sure we get a metric logged from both ILogger and TraceWriter
var key = MetricsEventManager.GetAggregateKey(MetricEventNames.FunctionUserLog, "Scenarios");
Assert.Equal(2, Fixture.MetricsLogger.LoggedEvents.Where(p => p == key).Count());
// Make sure we've gotten a log from the aggregator
IEnumerable<LogMessage> getAggregatorLogs() => Fixture.Host.GetLogMessages().Where(p => p.Category == LogCategories.Aggregator);
await TestHelpers.Await(() => getAggregatorLogs().Any());
var aggregatorLogs = getAggregatorLogs();
Assert.Equal(1, aggregatorLogs.Count());
}
[Fact]
public async Task VerifyHostHeader()
{
const string actualHost = "actual-host";
const string actualProtocol = "https";
const string path = "api/httptrigger-scenarios";
var request = new HttpRequestMessage
{
RequestUri = new Uri(string.Format($"http://localhost/{path}")),
Method = HttpMethod.Post
};
request.Headers.TryAddWithoutValidation("DISGUISED-HOST", actualHost);
request.Headers.TryAddWithoutValidation("X-Forwarded-Proto", actualProtocol);
var input = new JObject
{
{ "scenario", "appServiceFixupMiddleware" }
};
request.Content = new StringContent(input.ToString(), Encoding.UTF8, "application/json");
var response = await Fixture.Host.HttpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var url = await response.Content.ReadAsStringAsync();
Assert.Equal($"{actualProtocol}://{actualHost}/{path}", url);
}
[Fact]
public async Task MultipleOutputs()
{
string id1 = Guid.NewGuid().ToString();
string id2 = Guid.NewGuid().ToString();
string id3 = Guid.NewGuid().ToString();
JObject input = new JObject
{
{ "Id1", id1 },
{ "Id2", id2 },
{ "Id3", id3 }
};
await Fixture.Host.BeginFunctionAsync("MultipleOutputs", input);
// verify all 3 output blobs were written
var blob = Fixture.TestOutputContainer.GetBlockBlobReference(id1);
await TestHelpers.WaitForBlobAsync(blob);
string blobContent = await blob.DownloadTextAsync();
Assert.Equal("Test Blob 1", Utility.RemoveUtf8ByteOrderMark(blobContent));
blob = Fixture.TestOutputContainer.GetBlockBlobReference(id2);
await TestHelpers.WaitForBlobAsync(blob);
blobContent = await blob.DownloadTextAsync();
Assert.Equal("Test Blob 2", Utility.RemoveUtf8ByteOrderMark(blobContent));
blob = Fixture.TestOutputContainer.GetBlockBlobReference(id3);
await TestHelpers.WaitForBlobAsync(blob);
blobContent = await blob.DownloadTextAsync();
Assert.Equal("Test Blob 3", Utility.RemoveUtf8ByteOrderMark(blobContent));
}
[Fact]
public async Task ScriptReference_LoadsScript()
{
HttpResponseMessage response = await Fixture.Host.HttpClient.GetAsync($"api/LoadScriptReference");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("TestClass", await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task ExecutionContext_IsPopulated()
{
string functionName = "FunctionExecutionContext";
HttpResponseMessage response = await Fixture.Host.HttpClient.GetAsync($"api/{functionName}");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
ExecutionContext context = await response.Content.ReadAsAsync<ExecutionContext>();
Assert.NotNull(context);
Assert.Equal(functionName, context.FunctionName);
Assert.Equal(Path.Combine(Fixture.Host.ScriptOptions.RootScriptPath, functionName), context.FunctionDirectory);
}
[Fact]
public async Task SharedAssemblyDependenciesAreLoaded()
{
HttpResponseMessage response = await Fixture.Host.HttpClient.GetAsync("api/AssembliesFromSharedLocation");
Assert.Equal("secondary type value", await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task RandGuidBinding_GeneratesRandomIDs()
{
var blobs = await Scenario_RandGuidBinding_GeneratesRandomIDs();
foreach (var blob in blobs)
{
string content = await blob.DownloadTextAsync();
int blobInt = int.Parse(content.Trim(new char[] { '\uFEFF', '\u200B' }));
Assert.True(blobInt >= 0 && blobInt <= 3);
}
}
[Fact]
public async Task HttpTrigger_Post_Dynamic()
{
var input = new JObject
{
{ "name", "Mathew Charles" },
{ "location", "Seattle" }
};
HttpRequestMessage request = new HttpRequestMessage
{
RequestUri = new Uri(string.Format("http://localhost/api/httptrigger-dynamic")),
Method = HttpMethod.Post,
Content = new StringContent(input.ToString())
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await Fixture.Host.HttpClient.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string body = await response.Content.ReadAsStringAsync();
Assert.Equal("Name: Mathew Charles, Location: Seattle", body);
}
[Fact]
public async Task HttpTriggerToBlob()
{
var request = new HttpRequestMessage
{
RequestUri = new Uri($"http://localhost/api/HttpTriggerToBlob?Suffix=TestSuffix"),
Method = HttpMethod.Post,
};
request.Headers.Add("Prefix", "TestPrefix");
request.Headers.Add("Value", "TestValue");
var id = Guid.NewGuid().ToString();
var metadata = new JObject()
{
{ "M1", "AAA" },
{ "M2", "BBB" }
};
var input = new JObject()
{
{ "Id", id },
{ "Value", "TestInput" },
{ "Metadata", metadata }
};
request.Content = new StringContent(input.ToString());
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
HttpResponseMessage response = await Fixture.Host.HttpClient.SendAsync(request);
string body = await response.Content.ReadAsStringAsync();
string expectedValue = $"TestInput{id}TestValue";
Assert.Equal(expectedValue, body);
// verify blob was written
string blobName = $"TestPrefix-{id}-TestSuffix-BBB";
var outBlob = Fixture.TestOutputContainer.GetBlockBlobReference(blobName);
string result = await TestHelpers.WaitForBlobAndGetStringAsync(outBlob);
Assert.Equal(expectedValue, Utility.RemoveUtf8ByteOrderMark(result));
}
//[Theory(Skip = "Not yet enabled.")]
//[InlineData("application/json", "\"Name: Fabio Cavalcante, Location: Seattle\"")]
//[InlineData("application/xml", "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Name: Fabio Cavalcante, Location: Seattle</string>")]
//[InlineData("text/plain", "Name: Fabio Cavalcante, Location: Seattle")]
//public async Task HttpTrigger_GetWithAccept_NegotiatesContent(string accept, string expectedBody)
//{
//var input = new JObject
//{
// { "name", "Fabio Cavalcante" },
// { "location", "Seattle" }
//};
//HttpRequestMessage request = new HttpRequestMessage
//{
// RequestUri = new Uri(string.Format("http://localhost/api/httptrigger-dynamic")),
// Method = HttpMethod.Post,
// Content = new StringContent(input.ToString())
//};
//request.SetConfiguration(Fixture.RequestConfiguration);
//request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept));
//request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
//Dictionary<string, object> arguments = new Dictionary<string, object>
//{
// { "input", request },
// { ScriptConstants.SystemTriggerParameterName, request }
//};
//await Fixture.Host.CallAsync("HttpTrigger-Dynamic", arguments);
//HttpResponseMessage response = (HttpResponseMessage)request.Properties[ScriptConstants.AzureFunctionsHttpResponseKey];
//Assert.Equal(HttpStatusCode.OK, response.StatusCode);
//Assert.Equal(accept, response.Content.Headers.ContentType.MediaType);
//string body = await response.Content.ReadAsStringAsync();
//Assert.Equal(expectedBody, body);
//}
public class TestFixture : EndToEndTestFixture
{
private const string ScriptRoot = @"TestScripts\CSharp";
static TestFixture()
{
CreateSharedAssemblies();
}
public TestFixture() : base(ScriptRoot, "csharp", LanguageWorkerConstants.DotNetLanguageWorkerName)
{
}
private static void CreateSharedAssemblies()
{
string sharedAssembliesPath = Path.Combine(ScriptRoot, "SharedAssemblies");
if (Directory.Exists(sharedAssembliesPath))
{
Directory.Delete(sharedAssembliesPath, true);
}
Directory.CreateDirectory(sharedAssembliesPath);
string secondaryDependencyPath = Path.Combine(sharedAssembliesPath, "SecondaryDependency.dll");
string primaryReferenceSource = @"
using SecondaryDependency;
namespace PrimaryDependency
{
public class Primary
{
public string GetValue()
{
var secondary = new Secondary();
return secondary.GetSecondaryValue();
}
}
}";
string secondaryReferenceSource = @"
namespace SecondaryDependency
{
public class Secondary
{
public string GetSecondaryValue()
{
return ""secondary type value"";
}
}
}";
var secondarySyntaxTree = CSharpSyntaxTree.ParseText(secondaryReferenceSource);
Compilation secondaryCompilation = CSharpCompilation.Create("SecondaryDependency", new[] { secondarySyntaxTree })
.WithReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
secondaryCompilation.Emit(secondaryDependencyPath);
var primarySyntaxTree = CSharpSyntaxTree.ParseText(primaryReferenceSource);
Compilation primaryCompilation = CSharpCompilation.Create("PrimaryDependency", new[] { primarySyntaxTree })
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.WithReferences(MetadataReference.CreateFromFile(secondaryDependencyPath), MetadataReference.CreateFromFile(typeof(object).Assembly.Location));
primaryCompilation.Emit(Path.Combine(sharedAssembliesPath, "PrimaryDependency.dll"));
}
public override void ConfigureJobHost(IWebJobsBuilder webJobsBuilder)
{
base.ConfigureJobHost(webJobsBuilder);
webJobsBuilder.AddAzureStorage();
webJobsBuilder.Services.Configure<ScriptJobHostOptions>(o =>
{
// Only load the functions we care about
o.Functions = new[]
{
"AssembliesFromSharedLocation",
"HttpTrigger-Dynamic",
"HttpTrigger-Scenarios",
"HttpTriggerToBlob",
"FunctionExecutionContext",
"LoadScriptReference",
"ManualTrigger",
"MultipleOutputs",
"QueueTriggerToBlob",
"Scenarios"
};
});
webJobsBuilder.Services.Configure<FunctionResultAggregatorOptions>(o =>
{
o.BatchSize = 1;
});
}
}
public class TestInput
{
public int Id { get; set; }
public string Value { get; set; }
}
}
}