-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSyncIntegrationTests.cs
More file actions
299 lines (253 loc) · 9.2 KB
/
SyncIntegrationTests.cs
File metadata and controls
299 lines (253 loc) · 9.2 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
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 Microsoft.Extensions.Logging;
using PowerSync.Common.Client;
using PowerSync.Common.Client.Sync.Stream;
namespace PowerSync.Common.IntegrationTests;
[Trait("Category", "Integration")]
public class SyncIntegrationTests : IAsyncLifetime
{
private record ListResult(string id, string name, string owner_id, string created_at);
private record TodoResult(string id, string list_id, string content, string owner_id, string created_at);
private readonly string userId = Uuid();
private NodeClient nodeClient = default!;
private PowerSyncDatabase db = default!;
public async Task InitializeAsync()
{
// Create a logger factory
ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole();
builder.SetMinimumLevel(LogLevel.Information);
});
var logger = loggerFactory.CreateLogger("PowerSyncLogger");
nodeClient = new NodeClient(userId);
db = new PowerSyncDatabase(new PowerSyncDatabaseOptions
{
Database = new SQLOpenOptions { DbFilename = "powersync-sync-tests.db" },
Schema = TestSchema.PowerSyncSchema,
Logger = logger
});
await db.Init();
var connector = new NodeConnector(userId);
Console.WriteLine($"Using User ID: {userId}");
try
{
await db.Connect(connector, new PowerSyncConnectionOptions
{
AppMetadata = new Dictionary<string, string>
{
{ "app_version", "1.0.0-integration-tests" },
{ "environment", "integration-tests" }
}
});
await db.Connect(connector);
await db.WaitForFirstSync();
}
catch (Exception ex)
{
Console.WriteLine($"Exception during InitializeAsync: {ex}");
throw;
}
}
public async Task DisposeAsync()
{
await ClearAllData();
await Task.Delay(2000);
await db.DisconnectAndClear();
await db.Close();
}
[IntegrationFact(Timeout = 3000)]
public async Task SyncDownCreateOperationTest()
{
var watched = new TaskCompletionSource<bool>();
var cts = new CancellationTokenSource();
var id = Uuid();
_ = Task.Run(async () =>
{
await foreach (var x in db.Watch<ListResult>("select * from lists where id = ?", [id], new() { Signal = cts.Token }))
{
if (x.Length == 1)
{
watched.SetResult(true);
cts.Cancel();
}
}
});
await nodeClient.CreateList(id, name: "Test List magic");
await watched.Task;
}
[IntegrationFact(Timeout = 3000)]
public async Task SyncDownDeleteOperationTest()
{
var watched = new TaskCompletionSource<bool>();
var cts = new CancellationTokenSource();
var id = Uuid();
await nodeClient.CreateList(id, name: "Test List to delete");
_ = Task.Run(async () =>
{
await foreach (var x in db.Watch<ListResult>("select * from lists where id = ?", [id], new() { Signal = cts.Token }))
{
// Verify that the item was added locally
if (x.Length == 1)
{
watched.SetResult(true);
cts.Cancel();
}
}
});
await watched.Task;
await nodeClient.DeleteList(id);
watched = new TaskCompletionSource<bool>();
cts = new CancellationTokenSource();
_ = Task.Run(async () =>
{
await foreach (var x in db.Watch<ListResult>("select * from lists where id = ?", [id], new() { Signal = cts.Token }))
{
// Verify that the item was deleted locally
if (x.Length == 0)
{
watched.SetResult(true);
cts.Cancel();
}
}
});
await watched.Task;
}
[IntegrationFact(Timeout = 5000)]
public async Task SyncDownLargeCreateOperationTest()
{
var watched = new TaskCompletionSource<bool>();
var cts = new CancellationTokenSource();
var id = Uuid();
var listName = Uuid();
_ = Task.Run(async () =>
{
await foreach (var x in db.Watch<ListResult>("select * from lists where id = ?", [id], new() { Signal = cts.Token }))
{
// Verify that the item was added locally
if (x.Length == 100)
{
watched.SetResult(true);
cts.Cancel();
}
}
});
for (int i = 0; i < 100; i++)
{
await nodeClient.CreateList(Uuid(), listName);
}
await watched.Task;
}
[IntegrationFact(Timeout = 5000)]
public async Task SyncDownCreateOperationAfterLargeUploadTest()
{
var localInsertWatch = new TaskCompletionSource<bool>();
var backendInsertWatch = new TaskCompletionSource<bool>();
var cts = new CancellationTokenSource();
var id = Uuid();
var listName = Uuid();
_ = Task.Run(async () =>
{
await foreach (var x in db.Watch<ListResult>("select * from lists where id = ?", [id], new() { Signal = cts.Token }))
{
// Verify that the items were added locally
if (x.Length == 100)
{
localInsertWatch.SetResult(true);
}
// Verify that the new item added to backend was synced down
else if (x.Length == 101)
{
backendInsertWatch.SetResult(true);
cts.Cancel();
}
}
});
for (int i = 0; i < 100; i++)
{
await db.Execute("insert into lists (id, name, owner_id, created_at) values (uuid(), ?, ?, datetime())",
[listName, userId]);
}
await localInsertWatch.Task;
// let the crud upload finish
await Task.Delay(2000);
await nodeClient.CreateList(Uuid(), listName);
await backendInsertWatch.Task;
}
/// <summary>
/// Helper that requires manual setup of the data to verify that download progress updates are working.
/// Ensure backend has 5000+ entries, then run this test to see progress updates in the console.
/// </summary>
// [IntegrationFact(Timeout = 10000)]
// public async Task InitialSyncDownloadProgressTest()
// {
// ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
// {
// builder.AddConsole();
// builder.SetMinimumLevel(LogLevel.Information);
// });
// var logger = loggerFactory.CreateLogger("PowerSyncLogger");
// nodeClient = new NodeClient(userId);
// db = new PowerSyncDatabase(new PowerSyncDatabaseOptions
// {
// Database = new SQLOpenOptions { DbFilename = "powersync-sync-progress-tests.db" },
// Schema = TestSchema.PowerSyncSchema,
// Logger = logger
// });
// await db.Init();
// await db.DisconnectAndClear();
// var clearListener = db.RunListener((update) =>
// {
// if (update.StatusChanged != null)
// {
// try
// {
// Console.WriteLine("Total: " + update.StatusChanged.DownloadProgress()?.TotalOperations + " Downloaded: " + update.StatusChanged.DownloadProgress()?.DownloadedOperations);
// Console.WriteLine("Synced: " + Math.Round((decimal)((update.StatusChanged.DownloadProgress()?.DownloadedFraction ?? 0) * 100)) + "%");
// }
// catch (Exception ex)
// {
// Console.WriteLine("Exception reading DownloadProgress: " + ex);
// }
// }
// });
// var connector = new NodeConnector(userId);
// await db.Connect(connector);
// await db.WaitForFirstSync();
// clearListener.Dispose();
// await db.DisconnectAndClear();
// await db.Close();
// }
private async Task ClearAllData()
{
if (db.Closed)
{
return;
}
// Inefficient but simple way to clear all data, avoiding payload limitations
var results = await db.GetAll<ListResult>("select * from lists");
foreach (var item in results)
{
await nodeClient.DeleteList(item.id);
}
}
static string Uuid()
{
return Guid.NewGuid().ToString();
}
}
[Trait("Category", "Integration")]
public class IntegrationFactAttribute : FactAttribute
{
public IntegrationFactAttribute()
{
if (Environment.GetEnvironmentVariable("RUN_INTEGRATION_TESTS") != "true")
{
Skip = "Integration tests are disabled. Set RUN_INTEGRATION_TESTS=true to run.";
}
// Set default timeout if not already set
if (Timeout == 0)
{
Timeout = 5000; // 5 seconds default for all integration tests
}
}
}