|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Threading; |
| 4 | +using System.Threading.Tasks; |
| 5 | +using Npgsql; |
| 6 | +using NUnit.Framework; |
| 7 | + |
| 8 | +namespace PostgreSQLCopyHelper.Test.Issues |
| 9 | +{ |
| 10 | + [TestFixture] |
| 11 | + [Description("A Unit Test to see, if PostgreSQLCopyHelper works with Canceling Requests.")] |
| 12 | + public class Issue58_CancelRequest_Test : TransactionalTestBase |
| 13 | + { |
| 14 | + private class User |
| 15 | + { |
| 16 | + public int Id { get; set; } |
| 17 | + |
| 18 | + public string Name { get; set; } |
| 19 | + } |
| 20 | + |
| 21 | + private PostgreSQLCopyHelper<User> subject; |
| 22 | + |
| 23 | + protected override void OnSetupInTransaction() |
| 24 | + { |
| 25 | + CreateTable(); |
| 26 | + } |
| 27 | + |
| 28 | + [Test] |
| 29 | + public async Task Test_CanceledBulkInsertThrowsWhenCanceled() |
| 30 | + { |
| 31 | + subject = new PostgreSQLCopyHelper<User>("sample", "TestUsers") |
| 32 | + .MapInteger("Id", x => x.Id) |
| 33 | + .MapText("Name", x => x.Name); |
| 34 | + |
| 35 | + var cancellationTokenSource = new CancellationTokenSource(); |
| 36 | + |
| 37 | + // Try to work with the Bulk Inserter: |
| 38 | + try |
| 39 | + { |
| 40 | + cancellationTokenSource.CancelAfter(15); |
| 41 | + await subject.SaveAllAsync(connection, FetchUserData(), cancellationTokenSource.Token); |
| 42 | + Assert.Fail("Should Never Reach Here!"); |
| 43 | + } |
| 44 | + catch (TaskCanceledException) |
| 45 | + { |
| 46 | + } |
| 47 | + catch (Exception) |
| 48 | + { |
| 49 | + Assert.Fail("Should Throw Exception of Type TaskCanceledException!"); |
| 50 | + } |
| 51 | + finally |
| 52 | + { |
| 53 | + cancellationTokenSource.Dispose(); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + private static async IAsyncEnumerable<User> FetchUserData() |
| 58 | + { |
| 59 | + for (var i = 1; i <= 2; i++) |
| 60 | + { |
| 61 | + // Simulate waiting for data to come through. |
| 62 | + await Task.Delay(10); |
| 63 | + yield return new User |
| 64 | + { |
| 65 | + Id = i, |
| 66 | + Name = $"Username {i}" |
| 67 | + }; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + private int CreateTable() |
| 72 | + { |
| 73 | + var sqlStatement = @"CREATE TABLE sample.TestUsers |
| 74 | + ( |
| 75 | + Id integer, |
| 76 | + Name text |
| 77 | + );"; |
| 78 | + |
| 79 | + var sqlCommand = new NpgsqlCommand(sqlStatement, connection); |
| 80 | + |
| 81 | + return sqlCommand.ExecuteNonQuery(); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | +} |
0 commit comments