public void CachingReloadableEntry_CachedAndRenewed_Exist() { var expirationTime = 300; var timeout = 200; var config = InitConfig(); config.ExpirationTime = TimeSpan.FromMilliseconds(expirationTime); var _cache = new InMemoryCache(config); var key = "test_value"; var value = new CachedModel(); var entry = new ReloadableCacheEntry(key, () => { value.Value++; return(value); }); _cache.Set(entry); Thread.Sleep(timeout); var cachedValue = _cache.Get <CachedModel>(key); Thread.Sleep(timeout); cachedValue = _cache.Get <CachedModel>(key); Assert.NotNull(cachedValue); }
public void Get_NestedGetWithoutLock_2Hits() { //Arrange var cache = new InMemoryCache("cache1", new InMemoryPolicy { SlidingExpiration = new TimeSpan(0, 2, 0), DoNotLock = true, NumberOfLocks = 1 }); int hits = 0; int Get() { cache.Get("key2", () => 0); hits++; return(hits); } //Act var result1 = cache.Get("key", (Func <int>)Get); var hits1 = hits; var result2 = cache.Get("key", (Func <int>)Get); var hits2 = hits; //Assert Assert.AreEqual(1, hits1); Assert.AreEqual(1, result1); Assert.AreEqual(1, hits2); Assert.AreEqual(1, result2); }
public void TestInMemoryCacheTimeToLive_FromInsert() { var ttl = 3; int misses = 0; string result; var stopwatch = new Stopwatch(); Func <string> getter = () => { misses++; return(misses.ToString()); }; var cache = new InMemoryCache( "insert-expire-cache", new InMemoryPolicy { ExpirationFromAdd = TimeSpan.FromSeconds(ttl), }); cache.ClearAll(); stopwatch.Start(); result = cache.Get("key", getter); Assert.AreEqual(1, misses); Assert.AreEqual("1", result); result = cache.Get("key", getter); Assert.AreEqual(1, misses); Assert.AreEqual("1", result); CacheTestTools.AssertValueDoesntChangeWithin(cache, "key", "1", getter, stopwatch, ttl); // Should expire within TTL+60sec from insert CacheTestTools.AssertValueDoesChangeWithin(cache, "key", "1", getter, stopwatch, 60.1); result = cache.Get("key", getter); Assert.AreNotEqual(1, misses); Assert.AreNotEqual("1", result); }
[Ignore] // Now reentrant locking is supported public void Get_NestedGetWithLock_Deadlock() { //Arrange var cache = new InMemoryCache("cache1", new InMemoryPolicy { SlidingExpiration = new TimeSpan(0, 2, 0), DoNotLock = false, NumberOfLocks = 1 }); int hits = 0; int Get() { cache.Get("key2", () => 0); hits++; return(hits); } var tokenSource = new CancellationTokenSource(); //Act var t = Task.Factory.StartNew(() => cache.Get("key", Get), tokenSource.Token); var finished = t.Wait(TimeSpan.FromSeconds(2)); //Assert Assert.AreEqual(false, finished); Assert.AreEqual(0, hits); tokenSource.Cancel(); }
public void CachingEntry_CachedAndRenewed_Exist() { var expirationTime = 300; var timeout = 200; var config = InitConfig(); config.ExpirationTime = TimeSpan.FromMilliseconds(expirationTime); var _cache = new InMemoryCache(config); var key = "test_value"; var value = new CachedModel(); _cache.Set(key, value); Thread.Sleep(timeout); // renew sliding expiration by _cache.Get var cachedValue = _cache.Get <CachedModel>(key); Thread.Sleep(timeout); cachedValue = _cache.Get <CachedModel>(key); Assert.NotNull(cachedValue); Assert.Equal(value, cachedValue); }
public void AddAddsItemToCache() { // arrange const string key = "key"; const string value = "value"; // act _cache.Add(key, value); // assert _cache.Get().Should().HaveCount(1); _cache.Get(key).Should().BeEquivalentTo(value); }
public void IfCacheDurationIsOrBelow0_DontInvoleCache(int expPeriod) { ICache cache = new InMemoryCache(); var obj1 = new object(); var obj2 = new object(); var key = GenerateUniqueCacheKey(); cache.Get(key, TimeSpan.FromTicks(1000000), () => obj1); // Act var cacheItem = cache.Get(key, TimeSpan.FromTicks(expPeriod), () => obj2); // Assert Assert.Equal(obj2, cacheItem); }
public void CanNotGetItemAfterExpiration() { TimedEventMock timedEventMock = null; SystemClockMock clock = new SystemClockMock(); TimerFactoryMock timerFactory = new TimerFactoryMock( timedEventMockFactory: (interval, runOnce, action) => { TimedEventMock result = new TimedEventMock(interval, runOnce, action); timedEventMock = result; return(result); }, timerMockFactory: null ); const string key = "test_key"; const string value = "test_value"; clock.UtcNow = DateTime.Now; TimeSpan expiration = TimeSpan.FromHours(1); using (InMemoryCache <string> cache = new InMemoryCache <string>(clock, timerFactory)) { cache.Set(key, value, expiration); clock.UtcNow += expiration + TimeSpan.FromSeconds(5); timedEventMock.Tick(); Assert.IsFalse(cache.HasItemWithKey(key), $"Cache contains entry with key '{key}'."); Assert.ThrowsException <KeyNotFoundException>(() => cache.Get(key)); } }
public void CanSetMultipleItems() { SystemClockMock clock = new SystemClockMock(); TimerFactoryMock timerFactory = new TimerFactoryMock( timedEventMockFactory: (x, y, z) => new EmptyDisposable(), timerMockFactory: null ); Dictionary <string, string> values = new Dictionary <string, string>() { ["key1"] = "value1", ["key2"] = "value2" }; using (InMemoryCache <string> cache = new InMemoryCache <string>(clock, timerFactory)) { foreach (var item in values) { cache.Set(item.Key, item.Value, TimeSpan.FromTicks(1)); } foreach (var item in values) { Assert.IsTrue(cache.HasItemWithKey(item.Key), $"Cache does not contain entry with key '{item.Key}'."); Assert.AreEqual(item.Value, cache.Get(item.Key)); } } }
public void CanGetItemBeforeExpiration() { TimedEventMock timedEventMock = null; SystemClockMock clock = new SystemClockMock(); TimerFactoryMock timerFactory = new TimerFactoryMock( timedEventMockFactory: (interval, runOnce, action) => { TimedEventMock result = new TimedEventMock(interval, runOnce, action); timedEventMock = result; return(result); }, timerMockFactory: null ); const string key = "test_key"; const string value = "test_value"; clock.UtcNow = DateTime.Now; TimeSpan expiration = TimeSpan.FromHours(1); using (InMemoryCache <string> cache = new InMemoryCache <string>(clock, timerFactory)) { cache.Set(key, value, expiration); clock.UtcNow += expiration - TimeSpan.FromMinutes(30); timedEventMock.Tick(); Assert.IsTrue(cache.HasItemWithKey(key), $"Cache does not contain entry with key '{key}'."); string actual = cache.Get(key); Assert.AreEqual(value, actual); } }
public void Cache_returns_old_stored_item() { // Arrange ICache cache = new InMemoryCache(); var returnObj1 = new object(); var returnObj2 = new object(); var key = GenerateUniqueCacheKey(); cache.Get(key, TimeSpan.FromSeconds(1000), () => returnObj1); // Act var cacheItem = cache.Get(key, TimeSpan.FromTicks(100), () => returnObj2); // Assert Assert.Equal(returnObj1, cacheItem); }
public Quote[] GetQuotes(string assetPairId) { OrderBook orderBook = _cache.Get(assetPairId); if (orderBook == null) { return(null); } LimitOrder[] sellLimitOrders = orderBook.LimitOrders .Where(o => o.Type == LimitOrderType.Sell) .OrderBy(o => o.Price) .ToArray(); LimitOrder[] buyLimitOrders = orderBook.LimitOrders .Where(o => o.Type == LimitOrderType.Buy) .OrderByDescending(o => o.Price) .ToArray(); if (sellLimitOrders.Length == 0 || buyLimitOrders.Length == 0) { return(null); } decimal secondAsk = sellLimitOrders[sellLimitOrders.Length - 1].Price; decimal secondBid = buyLimitOrders[buyLimitOrders.Length - 1].Price; return(new[] { CreateQuote(orderBook, sellLimitOrders[0].Price, buyLimitOrders[0].Price), CreateQuote(orderBook, secondAsk, secondBid) }); }
public static dynamic GetProductSchema(string productName) { var cacheProvider = new InMemoryCache(); string cacheKey = string.Format("productSchema-{0}", productName); return(cacheProvider.Get <dynamic>(cacheKey, PopulateProductSchema, productName)); }
public async Task <HedgeSettings> GetAsync() { HedgeSettings hedgeSettings = _cache.Get(CacheKey); if (hedgeSettings == null) { hedgeSettings = await _hedgeSettingsRepository.GetAsync(); if (hedgeSettings == null) { hedgeSettings = new HedgeSettings { MarketOrderMarkup = .02m, ThresholdDown = 1000, ThresholdUp = 5000, ThresholdDownBuy = 1000, ThresholdDownSell = 1000, ThresholdUpBuy = 5000, ThresholdUpSell = 5000, ThresholdCritical = 10000 }; } _cache.Initialize(new[] { hedgeSettings }); bool isDirty = false; if (hedgeSettings.ThresholdDownBuy == default(decimal)) { hedgeSettings.ThresholdDownBuy = hedgeSettings.ThresholdDown; isDirty = true; } if (hedgeSettings.ThresholdDownSell == default(decimal)) { hedgeSettings.ThresholdDownSell = hedgeSettings.ThresholdDown; isDirty = true; } if (hedgeSettings.ThresholdUpBuy == default(decimal)) { hedgeSettings.ThresholdUpBuy = hedgeSettings.ThresholdUp; isDirty = true; } if (hedgeSettings.ThresholdUpSell == default(decimal)) { hedgeSettings.ThresholdUpSell = hedgeSettings.ThresholdUp; isDirty = true; } if (isDirty) { await UpdateAsync(hedgeSettings); } } return(hedgeSettings); }
public void InMemoryCacheTest() { ICache cache = new InMemoryCache(new MemoryCache(new MemoryCacheOptions())); cache.Set("city", "nanjing", TimeSpan.FromSeconds(5)); Thread.Sleep(5000); Console.WriteLine(cache.Get("city")); }
public void TestInMemoryCacheStruct() { var cache = new InMemoryCache("cache1", new TimeSpan(0, 2, 0)); int hits = 0; Func <int> getter = () => { hits++; return(hits); }; int result; result = cache.Get("key", getter); Assert.AreEqual(1, hits); Assert.AreEqual(1, result); result = cache.Get("key", getter); Assert.AreEqual(1, hits); Assert.AreEqual(1, result); }
public void TestInMemoryCacheNull() { var cache = new InMemoryCache("cache1", new TimeSpan(0, 2, 0)); int misses = 0; Func <string> getter = () => { misses++; return(null); }; string result; result = cache.Get("key", getter); Assert.AreEqual(1, misses); Assert.AreEqual(null, result); result = cache.Get("key", getter); Assert.AreEqual(1, misses); Assert.AreEqual(null, result); }
public void TestInMemoryCacheObject() { var cache = new InMemoryCache("cache1", new TimeSpan(0, 2, 0)); int hits = 0; Func <string> getter = () => { hits++; return(hits.ToString()); }; string result; result = cache.Get("key", getter); Assert.AreEqual(1, hits); Assert.AreEqual("1", result); result = cache.Get("key", getter); Assert.AreEqual(1, hits); Assert.AreEqual("1", result); }
public void TestInMemoryCacheGetTwice() { var cache = new InMemoryCache("cache1", new InMemoryPolicy()); cache.ClearAll(); int misses = 0; Func <string> getter = () => { misses++; return(misses.ToString()); }; string result; result = cache.Get("key", getter); Assert.AreEqual("1", result); result = cache.Get("key", getter); Assert.AreEqual("1", result); }
public void InMemoryCacheObjectReturnsPayload() { const string VALUE = "myvalue"; ICache cache = new InMemoryCache(600); cache.Set("mykey", VALUE); Assert.Equal(VALUE, cache.Get <string>("mykey")); }
public void InMemoryCacheObjectReturnsNullWhenCacheObjectExpires() { const string VALUE = "myvalue"; ICache cache = new InMemoryCache(0); cache.Set("mykey", VALUE); Assert.Equal(null, cache.Get <string>("mykey")); }
public void TestInMemoryCacheObjectMutated() { var cache = new InMemoryCache("cache1", new TimeSpan(0, 2, 0)); List <string> value = new List <string> { "1" }; Func <IEnumerable <object> > getter = () => { return(value); }; IEnumerable <object> result; result = cache.Get("key", getter); CollectionAssert.AreEqual(new object[] { "1" }, result.ToArray()); value.Add("2"); result = cache.Get("key", getter); CollectionAssert.AreEqual(new object[] { "1", "2" }, result.ToArray()); }
public void AddGetRemove_Success() { // Arrange Customer customer = TestData.CreateCustomer(); ICache cache = new InMemoryCache(); // Add, Get and Assert cache.Add(customer.Id.ToString(), customer); object customerObject = cache.Get(customer.Id.ToString()); // Assert Assert.IsNotNull(customerObject); Assert.IsInstanceOfType(customerObject, typeof(Customer)); // Remove and Assert cache.Remove(customer.Id.ToString()); customerObject = cache.Get(customer.Id.ToString()); Assert.IsNull(customerObject); }
public void TestInMemoryCacheTimeToLive_Constant() { var ttl = 3; int misses = 0; string result; var stopwatch = new Stopwatch(); Func <string> getter = () => { misses++; return(misses.ToString()); }; var expireAt = DateTime.Now.AddSeconds(ttl); stopwatch.Start(); var cache = new InMemoryCache( "constant-expire", new InMemoryPolicy { AbsoluteExpiration = expireAt, }); cache.ClearAll(); result = cache.Get("key", getter); DateTime insertTime = DateTime.Now; Assert.AreEqual(1, misses); Assert.AreEqual("1", result); result = cache.Get("key", getter); Assert.AreEqual(1, misses); Assert.AreEqual("1", result); CacheTestTools.AssertValueDoesntChangeWithin(cache, "key", "1", getter, stopwatch, ttl); // Should expire within TTL+60sec from insert CacheTestTools.AssertValueDoesChangeWithin(cache, "key", "1", getter, stopwatch, 60.1); result = cache.Get("key", getter); Assert.AreNotEqual(1, misses); Assert.AreNotEqual("1", result); }
static Symbol() { try { Cache = new InMemoryCache <Symbol>(); Cache.Set( new[] { // <<insert symbol definitions>> }); // Redirect (BCH) Bitcoin Cash (BCC = BitConnect) Cache.Set("BCH_USDT", Cache.Get("BCC_USDT")); Cache.Set("BCH_BNB", Cache.Get("BCC_BNB")); Cache.Set("BCH_BTC", Cache.Get("BCC_BTC")); Cache.Set("BCH_ETH", Cache.Get("BCC_ETH")); } catch (Exception e) { Console.Error?.WriteLine($"{nameof(Binance)}.{nameof(Symbol)}(): \"{e.Message}\""); } }
public WheelEntity Get(WheelFilter filter) { var wheel = _inMemoryCache.Get(filter.ManufacturerName); if (wheel == null) { wheel = _repository.Get(filter); _inMemoryCache.Put(filter.ManufacturerName, wheel); } return(wheel); }
public CarEngineEntity Get(EngineFilter filter) { var engine = _inMemoryCache.Get(filter.ManufacturerName); if (engine == null) { engine = _repository.Get(filter); _inMemoryCache.Put(filter.ManufacturerName, engine); } return(engine); }
public TyreEntity Get(TyreFilter filter) { var tyre = _inMemoryCache.Get(filter.WheelManufacturerName); if (tyre == null) { tyre = _repository.Get(filter); _inMemoryCache.Put(filter.WheelManufacturerName, tyre); } return(tyre); }
public void Cache_returns_populated_item() { // Arrange ICache cache = new InMemoryCache(); var returnObj = new object(); var key = GenerateUniqueCacheKey(); // Act var cacheItem = cache.Get(key, TimeSpan.FromSeconds(1), () => returnObj); // Assert Assert.Equal(returnObj, cacheItem); }
public CarPaintEntity Get(PaintFilter filter) { var paint = _inMemoryCache.Get(filter.Name); if (paint == null) { paint = _repository.Get(filter); _inMemoryCache.Put(filter.Name, paint); } return(paint); }