public async Task RemoveAsync_FunctionWithoutParameters_ShouldBeRemoved()
        {
            var key = _distributedCacheService.GetKey(() => _testFunctions.FunctionWithoutParameters());

            await _memoryDistributedCache.SetStringAsync(key, JsonConvert.SerializeObject(Value));

            var beforeRemove = await _memoryDistributedCache.GetStringAsync(key);

            await _distributedCacheService.RemoveAsync(() => _testFunctions.FunctionWithoutParameters());

            var afterRemove = await _memoryDistributedCache.GetStringAsync(key);

            beforeRemove.Should().NotBeNull();
            afterRemove.Should().BeNull();
        }
        public async Task NewUserBeginsWatchingStream(bool ongoing)
        {
            string connectionId = Guid.NewGuid().ToString();

            Mock <IHubCallerClients <ISpectatorClient> > mockClients = new Mock <IHubCallerClients <ISpectatorClient> >();
            Mock <ISpectatorClient> mockCaller = new Mock <ISpectatorClient>();

            mockClients.Setup(clients => clients.Caller).Returns(mockCaller.Object);

            Mock <IGroupManager> mockGroups = new Mock <IGroupManager>();

            Mock <HubCallerContext> mockContext = new Mock <HubCallerContext>();

            mockContext.Setup(context => context.UserIdentifier).Returns(watcher_id);
            mockContext.Setup(context => context.ConnectionId).Returns(connectionId);

            hub.Context = mockContext.Object;
            hub.Clients = mockClients.Object;
            hub.Groups  = mockGroups.Object;

            if (ongoing)
            {
                await cache.SetStringAsync(SpectatorHub.GetStateId(streamer_id), JsonConvert.SerializeObject(state));
            }

            await hub.StartWatchingUser(streamer_id);

            mockGroups.Verify(groups => groups.AddToGroupAsync(connectionId, SpectatorHub.GetGroupId(streamer_id), default));

            mockCaller.Verify(clients => clients.UserBeganPlaying(streamer_id, It.Is <SpectatorState>(m => m.Equals(state))), ongoing ? Times.Once : Times.Never);
        }
Ejemplo n.º 3
0
        public async Task GetOrCreateStringAsync_MemoryEmpty_RedisContains_CallTwice()
        {
            const string generatedKey = "key1";

            IMemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions());

            var options    = Options.Create(new MemoryDistributedCacheOptions());
            var redisCache = new MemoryDistributedCache(options);
            await redisCache.SetStringAsync(generatedKey, Test);

            var logger = Substitute.For <ILogger <CommonCachingService> >();

            var cacheService = new CommonCachingService(memoryCache, redisCache, logger);

            var result = await cacheService.GetOrCreateStringAsync(generatedKey, () => Task.FromResult(Test), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(5));

            Assert.AreEqual(Test, result);

            result = await cacheService.GetOrCreateStringAsync(generatedKey, () => Task.FromResult(Test), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(5));

            Assert.AreEqual(Test, result);

            logger.Received(1).Log(LogLevel.Debug, Arg.Any <EventId>(), Arg.Is <Microsoft.Extensions.Logging.Internal.FormattedLogValues>(flv => flv.ToString() == $"Getting cached value from Distributed cache for key {generatedKey}"), null, Arg.Any <Func <Object, Exception, string> >());
            logger.Received(1).Log(LogLevel.Debug, Arg.Any <EventId>(), Arg.Is <Microsoft.Extensions.Logging.Internal.FormattedLogValues>(flv => flv.ToString() == $"Read cached value from Distributed cache for key {generatedKey}"), null, Arg.Any <Func <Object, Exception, string> >());
            logger.Received(0).Log(LogLevel.Debug, Arg.Any <EventId>(), Arg.Is <Microsoft.Extensions.Logging.Internal.FormattedLogValues>(flv => flv.ToString() == $"Stored in Distributed cache for key {generatedKey}"), null, Arg.Any <Func <Object, Exception, string> >());
        }
Ejemplo n.º 4
0
        public async Task GetOrCreateStringAsync_MemoryEmpty_RedisContains_CallTwice()
        {
            const string generatedKey = "key1";

            IMemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions());

            var options    = Options.Create(new MemoryDistributedCacheOptions());
            var redisCache = new MemoryDistributedCache(options);
            await redisCache.SetStringAsync(generatedKey, Test);

            var logger = Substitute.For <LoggerMock <CommonCachingService> >();

            var cacheService = new CommonCachingService(memoryCache, redisCache, logger);

            var result = await cacheService.GetOrCreateStringAsync(generatedKey, () => Task.FromResult(Test), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(5));

            Assert.AreEqual(Test, result);

            result = await cacheService.GetOrCreateStringAsync(generatedKey, () => Task.FromResult(Test), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(5));

            Assert.AreEqual(Test, result);

            logger.Received(1).Log(LogLevel.Debug, $"Getting cached value from Distributed cache for key {generatedKey}");
            logger.Received(1).Log(LogLevel.Debug, $"Read cached value from Distributed cache for key {generatedKey}");
            logger.Received(0).Log(LogLevel.Debug, $"Stored in Distributed cache for key {generatedKey}");
        }
        public async Task RedisServerTest()
        {
            //Arrange
            var options         = Options.Create(new MemoryDistributedCacheOptions());
            var cacheRepository = new MemoryDistributedCache(options);
            var serverMock      = new Mock <IServer>();

            serverMock.Setup(x => x.KeysAsync(It.IsAny <int>(),
                                              It.IsAny <RedisValue>(),
                                              It.IsAny <int>(),
                                              It.IsAny <long>(),
                                              It.IsAny <int>(),
                                              It.IsAny <CommandFlags>())).Returns(GetTestValues);
            var loggerMock  = new Mock <ILogger <RedisServer> >();
            var redisServer = new RedisServer(serverMock.Object, cacheRepository, loggerMock.Object);

            Expression <Func <Task> > expression = () => _testClassObject.TestMethod("test", 1);
            var body    = expression.Body as MethodCallExpression;
            var argType = body.Arguments[0].GetType();

            var parameters = from parameter in body.Arguments
                             let exp = parameter as MemberExpression
                                       let valueArgument = parameter as ConstantExpression
                                                           select new MethodParameter()
            {
                TypeName = parameter.Type.FullName,
                Value    = valueArgument.Value.ToString()
            };

            var cachedObject = new CachedJob()
            {
                AssemblyName     = body.Object.Type.Assembly.GetName().FullName,
                ClassName        = body.Object.Type.FullName,
                MethodName       = body.Method.Name,
                MethodParameters = parameters.ToArray(),
                RunAt            = ((DateTimeOffset)DateTime.UtcNow.AddSeconds(2)).UtcDateTime
            };
            var jsonData = JsonConvert.SerializeObject(cachedObject);
            await cacheRepository.SetStringAsync("1", jsonData);

            var cancellationToken = new CancellationToken();
            var src = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            //Act
            await redisServer.StartAsync(cancellationToken);

            for (int i = 0; i < 3; i++)
            {
                await Task.Delay(TimeSpan.FromSeconds(1));
            }

            src.Cancel();
        }
Ejemplo n.º 6
0
    public async Task GetAsyncGeneric_Integration_OK()
    {
        // arrange
        var cache = new MemoryDistributedCache(new OptionsWrapper <MemoryDistributedCacheOptions>(new MemoryDistributedCacheOptions()));
        await cache.SetStringAsync("test", "{ \"Id\": 1, \"Name\": \"Test\" }");

        var svc = new DistributedCacheService(cache, new NullLogger <DistributedCacheService>());

        // act
        var result = await svc.GetAsync <MyClass>("test");

        // assert
        result.ShouldNotBeNull();
        result.Id.ShouldBe(1);
        result.Name.ShouldBe("Test");
    }
        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);
        }