-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathWhen_starting_the_function_host.cs
More file actions
203 lines (173 loc) · 8.09 KB
/
When_starting_the_function_host.cs
File metadata and controls
203 lines (173 loc) · 8.09 KB
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
namespace ServiceBus.Tests;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus.Administration;
using Microsoft.Extensions.Configuration;
using NUnit.Framework;
[TestFixture]
public class When_starting_the_function_host
{
[Test]
public async Task Should_not_blow_up()
{
var configBuilder = new ConfigurationBuilder();
configBuilder.SetBasePath(Directory.GetCurrentDirectory());
configBuilder.AddEnvironmentVariables();
configBuilder.AddJsonFile("local.settings.json", true);
var config = configBuilder.Build();
var pathToFuncExe = config.GetValue<string>("PathToFuncExe");
if (pathToFuncExe == null)
{
Console.WriteLine("Environment variable 'PathToFuncExe' not defined. Going to try to find the latest version.");
var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var sdkPath = Path.Combine(userProfile, "AppData", "Local", "AzureFunctionsTools", "Releases");
if (Directory.Exists(sdkPath))
{
var mostRecent = Directory.GetDirectories(sdkPath)
.Select(path =>
{
var name = Path.GetFileName(path);
Version.TryParse(name, out var version);
return new { Name = name, Version = version };
})
.Where(x => x.Version is not null)
.OrderByDescending(x => x.Version)
.FirstOrDefault()
?.Name;
if (mostRecent is not null)
{
var exePath = Path.Combine(sdkPath, mostRecent, "cli_x64", "func.exe");
if (File.Exists(exePath))
{
Console.WriteLine("Found " + exePath);
pathToFuncExe = exePath;
}
}
}
}
Assert.That(pathToFuncExe, Is.Not.Null, "Environment variable 'PathToFuncExe' should be defined to run tests. When running locally this is usually 'C:\\Users\\<username>\\AppData\\Local\\AzureFunctionsTools\\Releases\\<version>\\cli_x64\\func.exe'");
var connectionString = config.GetValue<string>("AzureWebJobsServiceBus") ?? config.GetValue<string>("Values:AzureWebJobsServiceBus");
Assert.That(connectionString, Is.Not.Null, "Environment variable 'AzureWebJobsServiceBus' should be defined to run tests.");
var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(60));
var client = new ServiceBusAdministrationClient(connectionString);
const string queueName = "inprocess-hostv4";
const string topicName = "bundle-1";
if (!await client.QueueExistsAsync(queueName, cancellationTokenSource.Token))
{
await client.CreateQueueAsync(queueName, cancellationTokenSource.Token);
}
if (!await client.TopicExistsAsync(topicName, cancellationTokenSource.Token))
{
await client.CreateTopicAsync(topicName, cancellationTokenSource.Token);
}
if (!await client.SubscriptionExistsAsync(topicName, queueName, cancellationTokenSource.Token))
{
var subscription = new CreateSubscriptionOptions(topicName, queueName)
{
LockDuration = TimeSpan.FromMinutes(5),
ForwardTo = queueName,
EnableDeadLetteringOnFilterEvaluationExceptions = false,
MaxDeliveryCount = int.MaxValue,
EnableBatchedOperations = true,
UserMetadata = queueName
};
await client.CreateSubscriptionAsync(subscription, cancellationTokenSource.Token);
}
var functionRootDir = new DirectoryInfo(TestContext.CurrentContext.TestDirectory);
var port = 7076; //Use non-standard port to avoid clashing when debugging locally
var funcProcess = new Process();
var httpClient = new HttpClient();
var hasResult = false;
var hostFailed = false;
var eventHandlerCalled = false;
var commandHandlerCalled = false;
var someEventTaskCompletionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var someOtherMessageTaskCompletionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
cancellationTokenSource.Token.Register(state => ((TaskCompletionSource<bool>)state).TrySetResult(false), someEventTaskCompletionSource);
cancellationTokenSource.Token.Register(state => ((TaskCompletionSource<bool>)state).TrySetResult(false), someOtherMessageTaskCompletionSource);
funcProcess.StartInfo.WorkingDirectory = functionRootDir.FullName;
funcProcess.StartInfo.Arguments = $"start --port {port} --no-build --verbose";
funcProcess.StartInfo.FileName = pathToFuncExe;
funcProcess.StartInfo.UseShellExecute = false;
funcProcess.StartInfo.RedirectStandardOutput = true;
funcProcess.StartInfo.RedirectStandardError = true;
funcProcess.StartInfo.CreateNoWindow = true;
funcProcess.ErrorDataReceived += (_, e) =>
{
if (e.Data == null)
{
return;
}
hostFailed = true;
TestContext.Out.WriteLine(e.Data);
cancellationTokenSource.Cancel();
};
funcProcess.OutputDataReceived += (_, e) =>
{
if (e.Data == null)
{
return;
}
TestContext.Out.WriteLine(e.Data);
if (e.Data.Contains($"Handling {nameof(SomeOtherMessage)}"))
{
someOtherMessageTaskCompletionSource.SetResult(true);
}
if (e.Data.Contains($"Handling {nameof(SomeEvent)}"))
{
someEventTaskCompletionSource.SetResult(true);
}
};
funcProcess.EnableRaisingEvents = true;
funcProcess.Start();
funcProcess.BeginOutputReadLine();
funcProcess.BeginErrorReadLine();
try
{
while (!cancellationTokenSource.IsCancellationRequested && !hasResult)
{
try
{
var result = await httpClient.GetAsync($"http://localhost:{port}/api/InProcessHttpSenderV4", cancellationTokenSource.Token);
result.EnsureSuccessStatusCode();
hasResult = true;
}
catch (OperationCanceledException) when (cancellationTokenSource.Token.IsCancellationRequested)
{
}
catch (Exception ex)
{
await TestContext.Out.WriteLineAsync(ex.Message);
await Task.Delay(TimeSpan.FromSeconds(1), cancellationTokenSource.Token);
}
}
await Task.WhenAll(someEventTaskCompletionSource.Task, someOtherMessageTaskCompletionSource.Task);
eventHandlerCalled = await someEventTaskCompletionSource.Task;
commandHandlerCalled = await someOtherMessageTaskCompletionSource.Task;
funcProcess.Kill();
}
finally
{
try
{
await funcProcess.WaitForExitAsync(cancellationTokenSource.Token);
}
catch (OperationCanceledException) when (cancellationTokenSource.Token.IsCancellationRequested)
{
funcProcess.Kill();
}
}
Assert.Multiple(() =>
{
Assert.That(hostFailed, Is.False, "Host should startup without errors");
Assert.That(hasResult, Is.True, "Http trigger should respond successfully");
Assert.That(commandHandlerCalled, Is.True, $"{nameof(SomeOtherMessageHandler)} should have been called");
Assert.That(eventHandlerCalled, Is.True, $"{nameof(SomeEventMessageHandler)} should have been called");
});
}
}