forked from Giorgi/EntityFramework.Exceptions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseTests.cs
More file actions
398 lines (320 loc) · 15.3 KB
/
DatabaseTests.cs
File metadata and controls
398 lines (320 loc) · 15.3 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
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
using EFExceptionSchema.Entities.Incidents;
using EntityFramework.Exceptions.Common;
using EntityFramework.Exceptions.Tests.ConstraintTests;
using Microsoft.EntityFrameworkCore;
using MySql.EntityFrameworkCore.Extensions;
using System;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace EntityFramework.Exceptions.Tests;
public abstract class DatabaseTests : IDisposable
{
private readonly bool isMySql;
private readonly bool isSqlite;
internal DemoContext DemoContext { get; }
internal SameNameIndexesContext SameNameIndexesContext { get; }
protected DatabaseTests(DemoContext demoContext, SameNameIndexesContext sameNameIndexesContext = null)
{
DemoContext = demoContext;
SameNameIndexesContext = sameNameIndexesContext;
isMySql = MySqlDatabaseFacadeExtensions.IsMySql(DemoContext.Database) || MySQLDatabaseFacadeExtensions.IsMySql(DemoContext.Database);
isSqlite = demoContext.Database.IsSqlite();
}
[Fact]
public virtual async Task UniqueColumnViolationThrowsUniqueConstraintException()
{
DemoContext.Products.Add(new Product { Name = "GD" });
DemoContext.Products.Add(new Product { Name = "GD" });
var uniqueConstraintException = Assert.Throws<UniqueConstraintException>(() => DemoContext.SaveChanges());
await Assert.ThrowsAsync<UniqueConstraintException>(() => DemoContext.SaveChangesAsync());
if (!isSqlite)
{
Assert.False(string.IsNullOrEmpty(uniqueConstraintException.ConstraintName));
Assert.NotEmpty(uniqueConstraintException.ConstraintProperties);
Assert.Contains<string>(nameof(Product.Name), uniqueConstraintException.ConstraintProperties);
Assert.Equal(nameof(DemoContext.Products), uniqueConstraintException.SchemaQualifiedTableName);
}
}
[Fact]
public virtual async Task UniqueColumnViolationThrowsUniqueConstraintExceptionThroughExecuteUpdate()
{
DemoContext.Products.Add(new Product { Name = "Bulk Update 1" });
DemoContext.Products.Add(new Product { Name = "Bulk Update 2" });
await DemoContext.SaveChangesAsync();
Assert.Throws<UniqueConstraintException>(() => DemoContext.Products.ExecuteUpdate(p => p.SetProperty(pp => pp.Name, "Bulk Update 1")));
await Assert.ThrowsAsync<UniqueConstraintException>(async () => await DemoContext.Products.ExecuteUpdateAsync(p => p.SetProperty(pp => pp.Name, "Bulk Update 1")));
await DemoContext.Products
.Where(p => p.Name == "Bulk Update 1" || p.Name == "Bulk Update 2")
.ExecuteDeleteAsync();
}
[Fact]
public virtual async Task UniqueColumnViolationSameNamesIndexesInDifferentSchemasSetsCorrectTableName()
{
if (SameNameIndexesContext == null)
{
Assert.True(SameNameIndexesContext == null);
return;
}
SameNameIndexesContext.IncidentCategories.Add(new EFExceptionSchema.Entities.Incidents.Category
{
Name = "Rope Access"
});
SameNameIndexesContext.IncidentCategories.Add(new EFExceptionSchema.Entities.Incidents.Category
{
Name = "Rope Access"
});
var uniqueConstraintException = Assert.Throws<UniqueConstraintException>(() => SameNameIndexesContext.SaveChanges());
await Assert.ThrowsAsync<UniqueConstraintException>(() => SameNameIndexesContext.SaveChangesAsync());
if (!isSqlite)
{
Assert.False(string.IsNullOrEmpty(uniqueConstraintException.ConstraintName));
Assert.NotEmpty(uniqueConstraintException.ConstraintProperties);
Assert.Contains<string>(nameof(Category.Name), uniqueConstraintException.ConstraintProperties);
Assert.Equal("Incidents.Category", uniqueConstraintException.SchemaQualifiedTableName);
}
}
[Fact]
public virtual async Task PrimaryKeyViolationThrowsUniqueConstraintException()
{
var product1 = new Product { Name = "GD", Id = 42 };
var product2 = new Product { Name = "GD", Id = 42 };
DemoContext.Products.Add(product1);
DemoContext.SaveChanges();
CleanupContext();
DemoContext.Products.Add(product2);
var uniqueConstraintException = Assert.Throws<UniqueConstraintException>(() => DemoContext.SaveChanges());
await Assert.ThrowsAsync<UniqueConstraintException>(() => DemoContext.SaveChangesAsync());
if (!isSqlite && !isMySql)
{
Assert.False(string.IsNullOrEmpty(uniqueConstraintException.ConstraintName));
Assert.False(string.IsNullOrEmpty(uniqueConstraintException.SchemaQualifiedTableName));
Assert.NotEmpty(uniqueConstraintException.ConstraintProperties);
Assert.Contains<string>(nameof(Product.Id), uniqueConstraintException.ConstraintProperties);
}
}
[Fact]
public virtual async Task RequiredColumnViolationThrowsCannotInsertNullException()
{
DemoContext.Products.Add(new Product());
Assert.Throws<CannotInsertNullException>(() => DemoContext.SaveChanges());
await Assert.ThrowsAsync<CannotInsertNullException>(() => DemoContext.SaveChangesAsync());
}
[Fact]
public virtual async Task RequiredColumnViolationThrowsCannotInsertNullExceptionThroughExecuteUpdate()
{
DemoContext.Products.Add(new Product { Name = "Bulk Update 1" });
await DemoContext.SaveChangesAsync();
Assert.Throws<CannotInsertNullException>(() => DemoContext.Products.ExecuteUpdate(p => p.SetProperty(pp => pp.Name, (string)null)));
await Assert.ThrowsAsync<CannotInsertNullException>(async () => await DemoContext.Products.ExecuteUpdateAsync(p => p.SetProperty(pp => pp.Name, (string)null)));
await DemoContext.Products.Where(p => p.Name == "Bulk Update 1").ExecuteDeleteAsync();
}
[Fact]
public virtual async Task MaxLengthViolationThrowsMaxLengthExceededException()
{
DemoContext.Products.Add(new Product { Name = new string('G', DemoContext.ProductNameMaxLength + 5) });
Assert.Throws<MaxLengthExceededException>(() => DemoContext.SaveChanges());
await Assert.ThrowsAsync<MaxLengthExceededException>(() => DemoContext.SaveChangesAsync());
}
[Fact]
public virtual async Task MaxLengthViolationThrowsMaxLengthExceededExceptionThroughExecuteUpdate()
{
DemoContext.Products.Add(new Product { Name = "Bulk Update 1" });
await DemoContext.SaveChangesAsync();
CleanupContext();
Assert.Throws<MaxLengthExceededException>(Query);
await Assert.ThrowsAsync<MaxLengthExceededException>(QueryAsync);
await DemoContext.Products
.Where(p => p.Name == "Bulk Update 1")
.ExecuteDeleteAsync();
return;
void Query()
{
DemoContext.Products
.Where(p => p.Name == "Bulk Update 1")
.ExecuteUpdate(p => p.SetProperty(pp => pp.Name, new string('G', DemoContext.ProductNameMaxLength + 5)));
}
async Task QueryAsync()
{
await DemoContext.Products
.Where(p => p.Name == "Bulk Update 1")
.ExecuteUpdateAsync(p => p.SetProperty(pp => pp.Name, new string('G', DemoContext.ProductNameMaxLength + 5)));
}
}
[Fact]
public virtual async Task NumericOverflowViolationThrowsNumericOverflowException()
{
var product = new Product { Name = "Numeric Overflow Test" };
DemoContext.Products.Add(product);
DemoContext.ProductSales.Add(new ProductSale { Price = 3141.59265m, Product = product });
Assert.Throws<NumericOverflowException>(() => DemoContext.SaveChanges());
await Assert.ThrowsAsync<NumericOverflowException>(() => DemoContext.SaveChangesAsync());
}
[Fact]
public virtual async Task NumericOverflowViolationThrowsNumericOverflowExceptionThroughExecuteUpdate()
{
var product = new Product { Name = "Numeric Overflow Test 2" };
DemoContext.Products.Add(product);
var sale = new ProductSale { Price = 1m, Product = product };
DemoContext.ProductSales.Add(sale);
await DemoContext.SaveChangesAsync();
Assert.Throws<NumericOverflowException>(Query);
await Assert.ThrowsAsync<NumericOverflowException>(QueryAsync);
DemoContext.Remove(sale);
DemoContext.Remove(product);
await DemoContext.SaveChangesAsync();
return;
void Query()
{
DemoContext.ProductSales
.Where(s => s.Id == sale.Id)
.ExecuteUpdate(s => s.SetProperty(ss => ss.Price, 3141.59265m));
}
async Task QueryAsync()
{
await DemoContext.ProductSales
.Where(s => s.Id == sale.Id)
.ExecuteUpdateAsync(s => s.SetProperty(ss => ss.Price, 3141.59265m));
}
}
[Fact]
public virtual async Task ReferenceViolationThrowsReferenceConstraintException()
{
DemoContext.ProductSales.Add(new ProductSale { Price = 3.14m });
var referenceConstraintException = Assert.Throws<ReferenceConstraintException>(() => DemoContext.SaveChanges());
await Assert.ThrowsAsync<ReferenceConstraintException>(() => DemoContext.SaveChangesAsync());
if (!isSqlite)
{
Assert.False(string.IsNullOrEmpty(referenceConstraintException.ConstraintName));
Assert.NotEmpty(referenceConstraintException.ConstraintProperties);
Assert.Contains<string>(nameof(ProductSale.ProductId), referenceConstraintException.ConstraintProperties);
}
}
[Fact]
public virtual async Task ReferenceViolationThrowsReferenceConstraintExceptionThroughExecuteUpdate()
{
var product = new Product { Name = "RefConstraint Violation 1" };
DemoContext.Products.Add(product);
var sale = new ProductSale { Price = 1m, Product = product };
DemoContext.ProductSales.Add(sale);
await DemoContext.SaveChangesAsync();
var exception = Assert.Throws<ReferenceConstraintException>(Query);
var asyncException = await Assert.ThrowsAsync<ReferenceConstraintException>(QueryAsync);
if (!isSqlite)
{
Assert.False(string.IsNullOrEmpty(exception.ConstraintName));
Assert.NotEmpty(exception.ConstraintProperties);
Assert.Contains<string>(nameof(ProductSale.ProductId), exception.ConstraintProperties);
Assert.False(string.IsNullOrEmpty(asyncException.ConstraintName));
Assert.NotEmpty(asyncException.ConstraintProperties);
Assert.Contains<string>(nameof(ProductSale.ProductId), asyncException.ConstraintProperties);
}
return;
void Query()
{
DemoContext.ProductSales
.Where(s => s.Id == sale.Id)
.ExecuteUpdate(s => s.SetProperty(ss => ss.ProductId, 0));
}
async Task QueryAsync()
{
await DemoContext.ProductSales
.Where(s => s.Id == sale.Id)
.ExecuteUpdateAsync(s => s.SetProperty(ss => ss.ProductId, 0));
}
}
[Fact]
public virtual async Task DatabaseUnrelatedExceptionThrowsOriginalException()
{
var product = new Product { Name = "Unhandled Violation Test" };
DemoContext.Products.Add(product);
DemoContext.SaveChanges();
DemoContext.Database.ExecuteSqlInterpolated(isMySql
? $"Delete from Products where id={product.Id}"
: (FormattableString)$"Delete from \"Products\" where \"Id\"={product.Id}");
product.Name = "G";
Assert.ThrowsAny<DbUpdateException>(() => DemoContext.SaveChanges());
await Assert.ThrowsAnyAsync<DbUpdateException>(() => DemoContext.SaveChangesAsync());
}
[Fact]
public virtual async Task DeleteParentItemThrowsReferenceConstraintException()
{
var product = new Product { Name = "AN" };
var productPriceHistory = new ProductPriceHistory { Product = product, Price = 15.27m, EffectiveDate = DateTimeOffset.UtcNow };
DemoContext.ProductPriceHistories.Add(productPriceHistory);
await DemoContext.SaveChangesAsync();
CleanupContext();
product = DemoContext.Products.Find(product.Id);
DemoContext.Products.Remove(product);
Assert.Throws<ReferenceConstraintException>(() => DemoContext.SaveChanges());
await Assert.ThrowsAsync<ReferenceConstraintException>(() => DemoContext.SaveChangesAsync());
}
[Fact]
public virtual async Task DeleteParentItemThrowsReferenceConstraintExceptionThroughExecuteDelete()
{
var product = new Product { Name = "AN2" };
var productPriceHistory = new ProductPriceHistory { Product = product, Price = 15.27m, EffectiveDate = DateTimeOffset.UtcNow };
DemoContext.ProductPriceHistories.Add(productPriceHistory);
await DemoContext.SaveChangesAsync();
CleanupContext();
Assert.Throws<ReferenceConstraintException>(Query);
await Assert.ThrowsAsync<ReferenceConstraintException>(QueryAsync);
return;
void Query()
{
DemoContext.Products
.Where(p => p.Name == "AN2")
.ExecuteDelete();
}
async Task QueryAsync()
{
await DemoContext.Products
.Where(p => p.Name == "AN2")
.ExecuteDeleteAsync();
}
}
[Fact]
public async Task NotHandledViolationReThrowsOriginalException()
{
DemoContext.Customers.Add(new Customer { Fullname = "Test" });
await DemoContext.Database.ExecuteSqlRawAsync(isMySql ? "Drop table Customers" : "Drop table \"Customers\"");
Assert.Throws<DbUpdateException>(() => DemoContext.SaveChanges());
await Assert.ThrowsAsync<DbUpdateException>(() => DemoContext.SaveChangesAsync());
}
[Fact]
public virtual async Task Deadlock()
{
var p1 = DemoContext.Products.Add(new() { Name = "Test1" });
var p2 = DemoContext.Products.Add(new() { Name = "Test2" });
await DemoContext.SaveChangesAsync();
var id1 = p1.Entity.Id;
var id2 = p2.Entity.Id;
using var controlContext = new DemoContext(DemoContext.Options);
using var transaction1 = DemoContext.Database.BeginTransactionAsync();
using var transaction2 = controlContext.Database.BeginTransactionAsync();
await DemoContext.Products.Where(c => c.Id == id1)
.ExecuteUpdateAsync(c => c.SetProperty(p => p.Name, "Test11"));
await Assert.ThrowsAsync<DeadlockException>(async () =>
{
await controlContext.Products.Where(c => c.Id == id2)
.ExecuteUpdateAsync(c => c.SetProperty(p => p.Name, "Test21"));
var task1 = Task.Run(() => DemoContext.Products.Where(c => c.Id == id2)
.ExecuteUpdateAsync(c => c.SetProperty(p => p.Name, "Test22")));
await Task.Delay(100);
var task2 = controlContext.Products.Where(c => c.Id == id1)
.ExecuteUpdateAsync(c => c.SetProperty(p => p.Name, "Test12"));
await Task.WhenAll(task1, task2);
});
}
public virtual void Dispose()
{
CleanupContext();
}
protected void CleanupContext()
{
foreach (var entityEntry in DemoContext.ChangeTracker.Entries())
{
entityEntry.State = EntityState.Detached;
}
}
}