-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMutagenControllerTest.cs
299 lines (261 loc) · 12.3 KB
/
MutagenControllerTest.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
using System.Diagnostics;
using System.Runtime.InteropServices;
using Coder.Desktop.App.Models;
using Coder.Desktop.App.Services;
using NUnit.Framework.Interfaces;
namespace Coder.Desktop.Tests.App.Services;
[TestFixture]
public class MutagenControllerTest
{
[OneTimeSetUp]
public async Task DownloadMutagen()
{
var ct = new CancellationTokenSource(TimeSpan.FromSeconds(60)).Token;
var scriptDirectory = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory,
"..", "..", "..", "..", "scripts"));
var process = new Process();
process.StartInfo.FileName = "powershell.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.Arguments = $"-ExecutionPolicy Bypass -File Get-Mutagen.ps1 -arch {_arch}";
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.WorkingDirectory = scriptDirectory;
process.Start();
var output = await process.StandardOutput.ReadToEndAsync(ct);
TestContext.Out.Write(output);
var error = await process.StandardError.ReadToEndAsync(ct);
TestContext.Error.Write(error);
Assert.That(process.ExitCode, Is.EqualTo(0));
_mutagenBinaryPath = Path.Combine(scriptDirectory, "files", $"mutagen-windows-{_arch}.exe");
Assert.That(File.Exists(_mutagenBinaryPath));
}
[SetUp]
public void CreateTempDir()
{
_tempDirectory = Directory.CreateTempSubdirectory(GetType().Name);
TestContext.Out.WriteLine($"temp directory: {_tempDirectory}");
}
[TearDown]
public void DeleteTempDir()
{
// Only delete the temp directory if the test passed.
if (TestContext.CurrentContext.Result.Outcome == ResultState.Success)
_tempDirectory.Delete(true);
else
TestContext.Out.WriteLine($"persisting temp directory: {_tempDirectory}");
}
private string _mutagenBinaryPath;
private DirectoryInfo _tempDirectory;
private readonly string _arch = RuntimeInformation.ProcessArchitecture switch
{
Architecture.X64 => "x64",
Architecture.Arm64 => "arm64",
// We only support amd64 and arm64 on Windows currently.
_ => throw new PlatformNotSupportedException(
$"Unsupported architecture '{RuntimeInformation.ProcessArchitecture}'. Coder only supports x64 and arm64."),
};
/// <summary>
/// Ensures the daemon is stopped by waiting for the daemon.lock file to be released.
/// </summary>
private static async Task AssertDaemonStopped(string dataDirectory, CancellationToken ct)
{
var lockPath = Path.Combine(dataDirectory, "daemon", "daemon.lock");
// If we can lock the daemon.lock file, it means the daemon has stopped.
while (true)
{
ct.ThrowIfCancellationRequested();
try
{
await using var lockFile = new FileStream(lockPath, FileMode.Open, FileAccess.Write, FileShare.None);
}
catch (IOException e)
{
TestContext.Out.WriteLine($"Could not acquire daemon.lock (will retry): {e.Message}");
await Task.Delay(100, ct);
}
break;
}
}
[Test(Description = "Full sync test")]
[CancelAfter(30_000)]
public async Task Ok(CancellationToken ct)
{
// NUnit runs each test in a temporary directory
var dataDirectory = _tempDirectory.CreateSubdirectory("mutagen").FullName;
var alphaDirectory = _tempDirectory.CreateSubdirectory("alpha");
var betaDirectory = _tempDirectory.CreateSubdirectory("beta");
await using var controller = new MutagenController(_mutagenBinaryPath, dataDirectory);
// Initial state before calling RefreshState.
var state = controller.GetState();
Assert.That(state.Lifecycle, Is.EqualTo(SyncSessionControllerLifecycle.Uninitialized));
Assert.That(state.DaemonError, Is.Null);
Assert.That(state.DaemonLogFilePath, Is.EqualTo(Path.Combine(dataDirectory, "daemon.log")));
Assert.That(state.SyncSessions, Is.Empty);
state = await controller.RefreshState(ct);
Assert.That(state.Lifecycle, Is.EqualTo(SyncSessionControllerLifecycle.Stopped));
Assert.That(state.DaemonError, Is.Null);
Assert.That(state.DaemonLogFilePath, Is.EqualTo(Path.Combine(dataDirectory, "daemon.log")));
Assert.That(state.SyncSessions, Is.Empty);
// Ensure the daemon is stopped because all sessions are terminated.
await AssertDaemonStopped(dataDirectory, ct);
var progressMessages = new List<string>();
void OnProgress(string message)
{
TestContext.Out.WriteLine("Create session progress: " + message);
progressMessages.Add(message);
}
var session1 = await controller.CreateSyncSession(new CreateSyncSessionRequest
{
Alpha = new CreateSyncSessionRequest.Endpoint
{
Protocol = CreateSyncSessionRequest.Endpoint.ProtocolKind.Local,
Path = alphaDirectory.FullName,
},
Beta = new CreateSyncSessionRequest.Endpoint
{
Protocol = CreateSyncSessionRequest.Endpoint.ProtocolKind.Local,
Path = betaDirectory.FullName,
},
}, OnProgress, ct);
// There should've been at least one progress message.
Assert.That(progressMessages, Is.Not.Empty);
state = controller.GetState();
Assert.That(state.SyncSessions, Has.Count.EqualTo(1));
Assert.That(state.SyncSessions[0].Identifier, Is.EqualTo(session1.Identifier));
var session2 = await controller.CreateSyncSession(new CreateSyncSessionRequest
{
Alpha = new CreateSyncSessionRequest.Endpoint
{
Protocol = CreateSyncSessionRequest.Endpoint.ProtocolKind.Local,
Path = alphaDirectory.FullName,
},
Beta = new CreateSyncSessionRequest.Endpoint
{
Protocol = CreateSyncSessionRequest.Endpoint.ProtocolKind.Local,
Path = betaDirectory.FullName,
},
}, null, ct);
state = controller.GetState();
Assert.That(state.SyncSessions, Has.Count.EqualTo(2));
Assert.That(state.SyncSessions.Any(s => s.Identifier == session1.Identifier));
Assert.That(state.SyncSessions.Any(s => s.Identifier == session2.Identifier));
// Write a file to alpha.
var alphaFile = Path.Combine(alphaDirectory.FullName, "file.txt");
var betaFile = Path.Combine(betaDirectory.FullName, "file.txt");
const string alphaContent = "hello";
await File.WriteAllTextAsync(alphaFile, alphaContent, ct);
// Wait for the file to appear in beta.
while (true)
{
ct.ThrowIfCancellationRequested();
await Task.Delay(100, ct);
if (!File.Exists(betaFile))
{
TestContext.Out.WriteLine("Waiting for file to appear in beta");
continue;
}
var betaContent = await File.ReadAllTextAsync(betaFile, ct);
if (betaContent == alphaContent) break;
TestContext.Out.WriteLine($"Waiting for file contents to match, current: {betaContent}");
}
await controller.TerminateSyncSession(session1.Identifier, ct);
await controller.TerminateSyncSession(session2.Identifier, ct);
// Ensure the daemon is stopped because all sessions are terminated.
await AssertDaemonStopped(dataDirectory, ct);
state = controller.GetState();
Assert.That(state.Lifecycle, Is.EqualTo(SyncSessionControllerLifecycle.Stopped));
Assert.That(state.DaemonError, Is.Null);
Assert.That(state.DaemonLogFilePath, Is.EqualTo(Path.Combine(dataDirectory, "daemon.log")));
Assert.That(state.SyncSessions, Is.Empty);
}
[Test(Description = "Shut down daemon when no sessions")]
[CancelAfter(30_000)]
public async Task ShutdownNoSessions(CancellationToken ct)
{
// NUnit runs each test in a temporary directory
var dataDirectory = _tempDirectory.FullName;
await using var controller = new MutagenController(_mutagenBinaryPath, dataDirectory);
await controller.RefreshState(ct);
// log file tells us the daemon was started.
var logPath = Path.Combine(dataDirectory, "daemon.log");
Assert.That(File.Exists(logPath));
// Ensure the daemon is stopped.
await AssertDaemonStopped(dataDirectory, ct);
}
[Test(Description = "Daemon is restarted when we create a session")]
[CancelAfter(30_000)]
public async Task CreateRestartsDaemon(CancellationToken ct)
{
// NUnit runs each test in a temporary directory
var dataDirectory = _tempDirectory.CreateSubdirectory("mutagen").FullName;
var alphaDirectory = _tempDirectory.CreateSubdirectory("alpha");
var betaDirectory = _tempDirectory.CreateSubdirectory("beta");
await using (var controller = new MutagenController(_mutagenBinaryPath, dataDirectory))
{
await controller.RefreshState(ct);
await controller.CreateSyncSession(new CreateSyncSessionRequest
{
Alpha = new CreateSyncSessionRequest.Endpoint
{
Protocol = CreateSyncSessionRequest.Endpoint.ProtocolKind.Local,
Path = alphaDirectory.FullName,
},
Beta = new CreateSyncSessionRequest.Endpoint
{
Protocol = CreateSyncSessionRequest.Endpoint.ProtocolKind.Local,
Path = betaDirectory.FullName,
},
}, null, ct);
}
await AssertDaemonStopped(dataDirectory, ct);
var logPath = Path.Combine(dataDirectory, "daemon.log");
Assert.That(File.Exists(logPath));
var logLines = await File.ReadAllLinesAsync(logPath, ct);
// Here we're going to use the log to verify the daemon was started 2 times.
// slightly brittle, but unlikely this log line will change.
Assert.That(logLines.Count(s => s.Contains("[sync] Session manager initialized")), Is.EqualTo(2));
}
[Test(Description = "Controller kills orphaned daemon")]
[CancelAfter(30_000)]
public async Task Orphaned(CancellationToken ct)
{
// NUnit runs each test in a temporary directory
var dataDirectory = _tempDirectory.CreateSubdirectory("mutagen").FullName;
var alphaDirectory = _tempDirectory.CreateSubdirectory("alpha");
var betaDirectory = _tempDirectory.CreateSubdirectory("beta");
MutagenController? controller1 = null;
MutagenController? controller2 = null;
try
{
controller1 = new MutagenController(_mutagenBinaryPath, dataDirectory);
await controller1.RefreshState(ct);
await controller1.CreateSyncSession(new CreateSyncSessionRequest
{
Alpha = new CreateSyncSessionRequest.Endpoint
{
Protocol = CreateSyncSessionRequest.Endpoint.ProtocolKind.Local,
Path = alphaDirectory.FullName,
},
Beta = new CreateSyncSessionRequest.Endpoint
{
Protocol = CreateSyncSessionRequest.Endpoint.ProtocolKind.Local,
Path = betaDirectory.FullName,
},
}, null, ct);
controller2 = new MutagenController(_mutagenBinaryPath, dataDirectory);
await controller2.RefreshState(ct);
}
finally
{
if (controller1 != null) await controller1.DisposeAsync();
if (controller2 != null) await controller2.DisposeAsync();
}
await AssertDaemonStopped(dataDirectory, ct);
var logPath = Path.Combine(dataDirectory, "daemon.log");
Assert.That(File.Exists(logPath));
var logLines = await File.ReadAllLinesAsync(logPath, ct);
// Here we're going to use the log to verify the daemon was started 3 times.
// slightly brittle, but unlikely this log line will change.
Assert.That(logLines.Count(s => s.Contains("[sync] Session manager initialized")), Is.EqualTo(3));
}
}