From c1aaa4b6b2e363b7f57ff99d91724302d93e2ef4 Mon Sep 17 00:00:00 2001 From: Chomp Date: Wed, 2 Jul 2025 12:57:19 +0100 Subject: [PATCH] Added `MongoIDTests` to unit tests --- UnitTests/Tests/MongoIDTests.cs | 82 +++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 UnitTests/Tests/MongoIDTests.cs diff --git a/UnitTests/Tests/MongoIDTests.cs b/UnitTests/Tests/MongoIDTests.cs new file mode 100644 index 00000000..03063612 --- /dev/null +++ b/UnitTests/Tests/MongoIDTests.cs @@ -0,0 +1,82 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using SPTarkov.Server.Core.Extensions; +using SPTarkov.Server.Core.Models.Common; + +namespace UnitTests.Tests +{ + [TestClass] + public class MongoIDTests + { + [TestInitialize] + public void Initialize() { } + + [TestMethod] + public void GenerateTest() + { + // Generate 100 MongoId's + for (var i = 0; i < 100; i++) + { + // Invalid mongoId character + var result = new MongoId(); + + // Invalid mongoId length + var test = result.IsValidMongoId(); + + Assert.IsTrue(test, $"IsValidMongoId(): `{result}` is not a valid MongoId."); + } + } + + [TestMethod] + [DataRow( + "677ddb67406e9918a0264bbz", + false, + "677ddb67406e9918a0264bbz contains invalid char `z`, but result was true" + )] + [DataRow( + "677ddb67406e9918a0264bbcc", + false, + "677ddb67406e9918a0264bbcc is 25 characters, but result was true" + )] + [DataRow( + "677ddb67406e9918a0264bbc", + true, + "IsValidMongoId() `677ddb67406e9918a0264bbc` is a valid mongoId, but result was false" + )] + public void IsValidMongoIdTest(string mongoId, bool passes, string failMessage) + { + var result = new MongoId(mongoId); + Assert.AreEqual(passes, passes, result, failMessage); + } + + [TestMethod] + public void MultiThreadedMongoIDGenerationTest() + { + var concurrentBag = new ConcurrentBag(); + var random = new Random(); + var stopwatch = new Stopwatch(); + stopwatch.Start(); + + Parallel.For( + 0, + 1000, + i => + { + Thread.Sleep(random.Next(0, 10)); + var mongoId = new MongoId(); + concurrentBag.Add(mongoId); + } + ); + + stopwatch.Stop(); + Console.WriteLine($"Elapsed time: {stopwatch.ElapsedMilliseconds} ms"); + var uniqueCount = concurrentBag.Distinct().Count(); + var totalCount = concurrentBag.Count; + Assert.AreEqual( + totalCount, + uniqueCount, + $"Expected all generated MongoId's to be unique, but found: {totalCount - uniqueCount} duplicates." + ); + } + } +}