You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MongoDBTransactionTest.cs 2.8 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using FluentAssertions;
  3. using MongoDB.Bson;
  4. using MongoDB.Driver;
  5. using Xunit;
  6. namespace DotNetCore.CAP.MongoDB.Test
  7. {
  8. [Collection("MongoDB")]
  9. public class MongoDBTransactionTest : DatabaseTestHost
  10. {
  11. [Fact]
  12. public void MongoDB_Connection_Test()
  13. {
  14. var names = MongoClient.ListDatabaseNames();
  15. names.ToList().Should().NotBeNullOrEmpty();
  16. }
  17. [Fact(Skip = "Because of Appveyor dose not support MongoDB 4.0, so we skip this test for now.")]
  18. public void Transaction_Test()
  19. {
  20. var document = new BsonDocument
  21. {
  22. { "name", "MongoDB" },
  23. { "type", "Database" },
  24. { "count", 1 },
  25. { "info", new BsonDocument
  26. {
  27. { "x", 203 },
  28. { "y", 102 }
  29. }}
  30. };
  31. var db = MongoClient.GetDatabase("test");
  32. var collection1 = db.GetCollection<BsonDocument>("test1");
  33. var collection2 = db.GetCollection<BsonDocument>("test2");
  34. using (var sesstion = MongoClient.StartSession())
  35. {
  36. sesstion.StartTransaction();
  37. collection1.InsertOne(document);
  38. collection2.InsertOne(document);
  39. sesstion.CommitTransaction();
  40. }
  41. var filter = new BsonDocument("name", "MongoDB");
  42. collection1.CountDocuments(filter).Should().BeGreaterThan(0);
  43. collection2.CountDocuments(filter).Should().BeGreaterThan(0);
  44. }
  45. [Fact(Skip = "Because of Appveyor dose not support MongoDB 4.0, so we skip this test for now.")]
  46. public void Transaction_Rollback_Test()
  47. {
  48. var document = new BsonDocument
  49. {
  50. {"name", "MongoDB"},
  51. {"date", DateTimeOffset.Now.ToString()}
  52. };
  53. var db = MongoClient.GetDatabase("test");
  54. var collection = db.GetCollection<BsonDocument>("test3");
  55. var collection4 = db.GetCollection<BsonDocument>("test4");
  56. using (var session = MongoClient.StartSession())
  57. {
  58. session.IsInTransaction.Should().BeFalse();
  59. session.StartTransaction();
  60. session.IsInTransaction.Should().BeTrue();
  61. collection.InsertOne(session, document);
  62. collection4.InsertOne(session, new BsonDocument { { "name", "MongoDB" } });
  63. session.AbortTransaction();
  64. }
  65. var filter = new BsonDocument("name", "MongoDB");
  66. collection.CountDocuments(filter).Should().Be(0);
  67. collection4.CountDocuments(filter).Should().Be(0);
  68. }
  69. }
  70. }