Beispiel #1
0
 public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
 {
     if (DisableSetAsync)
     {
         throw new InvalidOperationException();
     }
     return(_cache.SetAsync(key, value, options));
 }
        public async Task Should_be_valid_when_job_is_requested_to_clear_cache()
        {
            await _cache.SetAsync(CacheKeys.Portfolio, Array.Empty <byte>());

            _updateCacheJob = new UpdateCacheJob(_cache, _mockPortfolio.Object);
            await _updateCacheJob.ClearAsync();

            _cache.Get(CacheKeys.Portfolio).Should().BeNull();
        }
Beispiel #3
0
        public async Task SetValueToCache()
        {
            IDistributedCache cache = new MemoryDistributedCache();

            await cache.SetAsync("2", 2, new DistributedCacheEntryOptions());

            var value = await cache.GetAsync <int>("2");

            value.Should().Be(2);
        }
Beispiel #4
0
 public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default)
 {
     if (DisableSetAsync)
     {
         throw new InvalidOperationException();
     }
     if (DelaySetAsync)
     {
         token.WaitHandle.WaitOne(TimeSpan.FromSeconds(10));
         token.ThrowIfCancellationRequested();
     }
     return(_cache.SetAsync(key, value, options));
 }
Beispiel #5
0
        public async Task SetComplexValueToCache()
        {
            IDistributedCache cache = new MemoryDistributedCache();

            await cache.SetAsync("foo", new Foo()
            {
                Value = 2
            }, new DistributedCacheEntryOptions());

            var value = await cache.GetAsync <Foo>("foo");

            value.Value.Should().Be(2);
        }
        public async Task SetAsyncSerializesObjectAndStoresBytes()
        {
            var cache   = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()));
            var example = new Example
            {
                Name = "The Name"
            };

            await cache.SetAsync("test", example);

            var bytes = await cache.GetAsync("test");

            var json = Encoding.UTF8.GetString(bytes);

            Assert.Equal(@"{""Name"":""The Name""}", json);
        }
        public async Task SetAsyncUsesExpiryPolicy()
        {
            var fixedTime = new DateTimeOffset(2020, 1, 27, 21, 20, 0, TimeSpan.Zero);
            var mockTime  = Substitute.For <ISystemClock>();

            mockTime.UtcNow.Returns(fixedTime);
            var options = new MemoryDistributedCacheOptions
            {
                Clock = mockTime
            };
            var cache             = new MemoryDistributedCache(Options.Create(options));
            var expirationOptions = new DistributedCacheEntryOptions
            {
                AbsoluteExpiration = fixedTime.Subtract(TimeSpan.FromSeconds(1))
            };
            await cache.SetAsync("should_be_gone", new Example { Name = "to expire" }, expirationOptions);

            var missing = await cache.GetAsync <Example>("should_be_gone");

            Assert.Null(missing);
        }
        public async Task Load_WhenTogglesOrEtagFileDoesNotExists_ReturnsEmptyResult(
            bool toggleCollectionExists,
            bool etagExists,
            [Frozen] DistributedToggleCollectionCacheSettings settings,
            [Frozen] MemoryDistributedCache distributedCache,
            DistributedToggleCollectionCache cache
            )
        {
            var jsonSerializerSettings = new NewtonsoftJsonSerializerSettings();
            var jsonSerializer         = new NewtonsoftJsonSerializer(jsonSerializerSettings);

            settings.EtagKeyName             = "Etag";
            settings.ToggleCollectionKeyName = "Toggles";

            if (toggleCollectionExists)
            {
                var toggleCollection = new ToggleCollection();

                using (var ms = new MemoryStream())
                {
                    jsonSerializer.Serialize(ms, toggleCollection);
                    ms.Seek(0, SeekOrigin.Begin);

                    await distributedCache.SetAsync(settings.ToggleCollectionKeyName, ms.ToArray(), settings.ToggleCollectionEntryOptions, CancellationToken.None).ConfigureAwait(false);
                }
            }

            if (toggleCollectionExists && etagExists)
            {
                var etag = Guid.NewGuid().ToString();
                distributedCache.SetString(settings.EtagKeyName, etag);
            }

            var result = await cache.Load(CancellationToken.None);

            Assert.Equal(string.Empty, result.InitialETag);
            Assert.Null(result.InitialToggleCollection);
        }
        public async Task Load_WhenValidToggleAndEtagFilesExist_ReturnsExpectedResult(
            [Frozen] MemoryDistributedCache distributedCache,
            ToggleCollection toggleCollection,
            string etag
            )
        {
            var jsonSerializerSettings = new NewtonsoftJsonSerializerSettings();
            var jsonSerializer         = new NewtonsoftJsonSerializer(jsonSerializerSettings);

            var settings = new DistributedToggleCollectionCacheSettings
            {
                EtagEntryOptions =
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
                },
                ToggleCollectionEntryOptions =
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
                }
            };

            using (var ms = new MemoryStream())
            {
                jsonSerializer.Serialize(ms, toggleCollection);
                ms.Seek(0, SeekOrigin.Begin);

                await distributedCache.SetAsync(settings.ToggleCollectionKeyName, ms.ToArray(), settings.ToggleCollectionEntryOptions, CancellationToken.None).ConfigureAwait(false);

                await distributedCache.SetStringAsync(settings.EtagKeyName, etag, settings.EtagEntryOptions, CancellationToken.None).ConfigureAwait(false);
            }

            var cache  = new DistributedToggleCollectionCache(settings, distributedCache, jsonSerializer);
            var result = await cache.Load(CancellationToken.None);

            Assert.Equal(etag, result.InitialETag);

            AssertionUtils.AssertToggleCollectionsEquivalent(toggleCollection, result.InitialToggleCollection);
        }
Beispiel #10
0
    public async Task PostAiMove_PreventRepeatedMoves()
    {
        var game  = HiveFactory.Create(new[] { "player1", "player2" });
        var moves = new Queue <Move>(3);

        for (var i = 0; i < 3; i++)
        {
            var player0Tile = game.Players.First().Tiles.First(t => t.Creature != Creatures.Queen && t.Moves.Any());
            game.Move(new Move(player0Tile, player0Tile.Moves.First()));

            var player1Tile = game.Players.Last().Tiles.First(t => t.Creature != Creatures.Queen && t.Moves.Any());
            game.Move(new Move(player1Tile, player1Tile.Moves.First()));
        }

        for (var i = 0; i < 2; i++)
        {
            var tileToMove = game.Players[i].Tiles.First(t => t.Moves.Any());
            game.Move(new Move(tileToMove, tileToMove.Moves.First()));
        }

        await _memoryCache.SetAsync(
            TestHelpers.ExistingGameId,
            TestHelpers.GetSerializedBytes(
                new GameState(game.Players, game.Cells, TestHelpers.ExistingGameId, GameStatus.MoveSuccess),
                TestHelpers.CreateJsonOptions()
                )
            );

        await _memoryCache.SetAsync(
            TestHelpers.ExistingGameId + "-moves-1",
            TestHelpers.GetSerializedBytes(moves, TestHelpers.CreateJsonOptions())
            );

        var actionResult = await _controller.AiMove(TestHelpers.ExistingGameId, 1);

        actionResult.Should().BeOfType <AcceptedResult>();
    }
Beispiel #11
0
        public MessageProcessorTests()
        {
            delivererMock = new Mock <IMailDeliverer>();

            delivererMock
            .Setup(d => d.DeliverAsync(It.Is <EmailMessage>(m => m.Subject == DELIVER_FAILURE)))
            .ThrowsAsync(new Exception());

            storageMock = new Mock <IMailStorage>();

            storageMock
            .Setup(s => s.SetProcessedAsync(It.Is <EmailMessage>(m => m.Subject == SET_PROCESSED_FAILURE)))
            .ThrowsAsync(new Exception());

            storageMock
            .Setup(s => s.SetErrorAsync(It.Is <EmailMessage>(m => m.Subject == SET_ERROR_FAILURE), It.IsAny <string>()))
            .ThrowsAsync(new Exception());

            storageMock
            .Setup(s => s.SetSentAsync(It.Is <EmailMessage>(m => m.Subject == SET_SENT_FAILURE)))
            .ThrowsAsync(new Exception());

            cacheMock = new Mock <IDistributedCache>();

            var internalCache = new MemoryDistributedCache(Options.Create <MemoryDistributedCacheOptions>(new MemoryDistributedCacheOptions()));

            cacheMock
            .Setup(c => c.GetAsync(It.Is <string>(m => m == CACHE_GET_EXCEPTION.ToString()), It.IsAny <CancellationToken>()))
            .ThrowsAsync(new Exception());

            cacheMock
            .Setup(c => c.GetAsync(It.Is <string>(m => m != CACHE_GET_EXCEPTION.ToString()), It.IsAny <CancellationToken>()))
            .Returns(async(string key, CancellationToken c) => await internalCache.GetAsync(key, c));

            cacheMock
            .Setup(c => c.SetAsync(It.Is <string>(m => m == CACHE_SET_EXCEPTION.ToString()), It.IsAny <byte[]>(), It.IsAny <DistributedCacheEntryOptions>(), It.IsAny <CancellationToken>()))
            .ThrowsAsync(new Exception());

            cacheMock
            .Setup(c => c.SetAsync(It.Is <string>(m => m != CACHE_SET_EXCEPTION.ToString()), It.IsAny <byte[]>(), It.IsAny <DistributedCacheEntryOptions>(), It.IsAny <CancellationToken>()))
            .Returns(async(string key, byte[] value, DistributedCacheEntryOptions o, CancellationToken c) => await internalCache.SetAsync(key, value, o, c));

            var logger = new NullLogger <MessageProcessor>();

            messageProcessor = new MessageProcessor(delivererMock.Object, storageMock.Object, cacheMock.Object, logger);
        }