Example #1
0
        public async Task Can_AcquireLock_TimeOut()
        {
            // guid here is to prevent competition between concurrent runtime tests
            var key     = PrefixedKey("AcquireLockKeyTimeOut:" + Guid.NewGuid());
            var lockKey = PrefixedKey("Can_AcquireLock_TimeOut:" + Guid.NewGuid());
            await RedisAsync.IncrementValueAsync(key); //1

            _ = await RedisAsync.AcquireLockAsync(lockKey);

            var waitFor = TimeSpan.FromMilliseconds(1000);
            var now     = DateTime.Now;

            try
            {
                await using var client = new RedisClient(TestConfig.SingleHost).ForAsyncOnly();
                await using (await client.AcquireLockAsync(lockKey, waitFor))
                {
                    await client.IncrementValueAsync(key); //2
                }
            }
            catch (TimeoutException)
            {
                var val = await RedisAsync.GetAsync <int>(key);

                Assert.That(val, Is.EqualTo(1));

                var timeTaken = DateTime.Now - now;
                Assert.That(timeTaken.TotalMilliseconds > waitFor.TotalMilliseconds, Is.True);
                Assert.That(timeTaken.TotalMilliseconds < waitFor.TotalMilliseconds + 2000, Is.True);
                return;
            }
            finally
            {
                await RedisAsync.RemoveAsync(key);

                await RedisAsync.RemoveAsync(lockKey);
            }
            Assert.Fail("should have Timed out");
        }