Ejemplo n.º 1
0
		public void Setup()
		{
			CacheBuilder = new CacheBuilder(ProxyFactory)
					.SetCache(CreateCache())
					.SetCacheKey(CreateCacheKey());
			TestSetup();
		}
 /// <summary>
 /// Creates a instance of the <see cref="IQueryExecutor"/> class by using
 /// the specified application settings.
 /// </summary>
 /// <param name="options">
 /// A <see cref="IDictionary{TKey,TValue}"/> containing the specific
 /// options configured for the query processor.
 /// </param>
 /// <returns>
 /// An instance of the <see cref="IQueryExecutor"/> class.
 /// </returns>
 public IQueryExecutor CreateQueryExecutor(
   IDictionary<string, string> options) {
   ICacheProvider cache_provider = GetCacheProvider();
   ICache<IConnectionProvider> cache = new CacheBuilder<IConnectionProvider>()
     .ExpireAfterAccess(settings_.QueryCacheDuration*3, TimeUnit.Seconds)
     .Build(cache_provider);
   IJsonCollectionFactory json_collection_factory =
     GetJsonCollectionFactory();
   return new SqlQueryExecutor(json_collection_factory, cache);
 }
Ejemplo n.º 3
0
 internal CacheExtension(KeyProvider prov, long keyTimeoutMillis, long currKeyTimeoutMillis
                         )
 {
     this.provider   = prov;
     keyVersionCache = CacheBuilder.NewBuilder().ExpireAfterAccess(keyTimeoutMillis, TimeUnit
                                                                   .Milliseconds).Build(new _CacheLoader_49(this));
     keyMetadataCache = CacheBuilder.NewBuilder().ExpireAfterAccess(keyTimeoutMillis,
                                                                    TimeUnit.Milliseconds).Build(new _CacheLoader_62(this));
     currentKeyCache = CacheBuilder.NewBuilder().ExpireAfterWrite(currKeyTimeoutMillis
                                                                  , TimeUnit.Milliseconds).Build(new _CacheLoader_75(this));
 }
Ejemplo n.º 4
0
    public void ShouldSetExpirationAndRefreshToGivenValues() {
      CacheBuilder<string> builder = new CacheBuilder<string>();

      builder.ExpireAfterWrite(1, TimeUnit.Seconds);
      Assert.AreEqual(builder.ExpiryAfterWriteNanos,
        TimeUnitHelper.ToNanos(1, TimeUnit.Seconds));

      builder.ExpireAfterAccess(2, TimeUnit.Seconds);
      Assert.AreEqual(builder.ExpiryAfterAccessNanos,
        TimeUnitHelper.ToNanos(2, TimeUnit.Seconds));
    }
        public void InvalidateAllByDispose()
        {
            var obj   = factory.Create <IObjectReturningNewGuids>();
            var value = obj.CachedMethod();

            factory.Dispose();
            var newFactory = CacheBuilder.BuildFactory();

            newFactory.Create <IObjectReturningNewGuids>().CachedMethod()
            .Should().Not.Be.EqualTo(value);
        }
Ejemplo n.º 6
0
        protected override void TestSetup()
        {
            eventListener = new StatisticsEventListener();
            CacheBuilder
            .For <ObjectReturningNewGuids>()
            .CacheMethod(c => c.CachedMethod())
            .As <IObjectReturningNewGuids>()
            .AddEventListener(eventListener);

            factory = CacheBuilder.BuildFactory();
        }
Ejemplo n.º 7
0
        public void CreatingProxiesOfSameDeclaredTypeShouldReturnIdenticalTypes()
        {
            CacheBuilder
            .For <ObjectReturningNewGuids>()
            .CacheMethod(c => c.CachedMethod())
            .As <IObjectReturningNewGuids>();

            var factory = CacheBuilder.BuildFactory();

            Assert.AreEqual(factory.Create <IObjectReturningNewGuids>().GetType(), factory.Create <IObjectReturningNewGuids>().GetType());
        }
Ejemplo n.º 8
0
        public void ShouldReturnCorrectTypeForClass()
        {
            CacheBuilder
            .For <ObjectWithNonInterfaceMethod>()
            .CacheMethod(c => c.ReturnsFour())
            .AsImplemented();
            var factory = CacheBuilder.BuildFactory();

            factory.ImplementationTypeFor(typeof(ObjectWithNonInterfaceMethod))
            .Should().Be.EqualTo(typeof(ObjectWithNonInterfaceMethod));
        }
Ejemplo n.º 9
0
        public void ShouldReturnCorrectTypeForInterface()
        {
            CacheBuilder
            .For <ObjectReturningNewGuids>()
            .CacheMethod(c => c.CachedMethod())
            .As <IObjectReturningNewGuids>();
            var factory = CacheBuilder.BuildFactory();

            factory.ImplementationTypeFor(typeof(IObjectReturningNewGuids))
            .Should().Be.EqualTo(typeof(ObjectReturningNewGuids));
        }
Ejemplo n.º 10
0
 public Bag(CodeFileBuilder builder)
 {
     _builder = builder;
     _orderBy = new OrderBy(builder);
     _cascade = new Cascade(builder);
     _inverse = new Inverse(builder);
     _table = new Table(builder);
     _keyColumn = new KeyColumn(builder);
     _lazyLoad = new LazyLoad(builder);
     _cacheBuilder = new CacheBuilder(builder);
 }
Ejemplo n.º 11
0
        public SearchService()
        {
            var searchBuilder = CacheBuilder.For <SearchDto>()
                                .WithIdExtractor(i => i?.NumberPlate ?? "")
                                .WithElementRetriever(i => FetchSerach(i))
                                .WithElementMaxAge(TimeSpan.FromMinutes(1))
                                .WithArrayMaxAge(TimeSpan.FromMinutes(1));

            _serachCache  = searchBuilder.ElementCache;
            _serachsCache = searchBuilder.GetArrayCache <string>(FetchSerachs);
        }
Ejemplo n.º 12
0
        public void PrivateObject_WithDefaultCtor_IsSuccess()
        {
            var target = new PrivateObjectWithDefaultCtorWrapper();

            target.Intialize(_random.Next());

            var syntax = CacheBuilder.CreateCache(target);

            var syntaxString = syntax.ToString();

            Assert.IsNotNull(syntaxString);
        }
Ejemplo n.º 13
0
        public void PublicField_IsSuccess()
        {
            var target = new PublicField();

            target.Value = _random.Next();

            var syntax = CacheBuilder.CreateCache(target);

            var syntaxString = syntax.ToString();

            Assert.IsNotNull(syntaxString);
        }
Ejemplo n.º 14
0
        protected override void TestSetup()
        {
            CacheBuilder.For <ReturningRandomNumbers>()
            .CacheMethod(c => c.CachedNumber())
            .CacheMethod(c => c.CachedNumber2())
            .As <IReturningRandomNumbers>()
            .SetLockObjectGenerator(new FixedNumberOfLockObjects(10));

            var factoryTemp = CacheBuilder.BuildFactory();

            factory = serializeAndDeserialize(factoryTemp);
        }
Ejemplo n.º 15
0
        public void TypeWithNonVirtualMethodShouldWork()
        {
            var fluentBuilder = CacheBuilder
                                .For <HasNonVirtualMethod>()
                                .CacheMethod(m => m.Virtual())
                                .AsImplemented();

            var instance = fluentBuilder.BuildFactory().Create <HasNonVirtualMethod>();

            instance.Virtual().Should().Be.EqualTo(instance.Virtual());
            instance.NonVirtual().Should().Not.Be.EqualTo(instance.NonVirtual());
        }
Ejemplo n.º 16
0
        protected override void TestSetup()
        {
            eventListener = new StatisticsEventListener();
            CacheBuilder
            .AddEventListener(eventListener)
            .For <ObjectWithParametersOnCachedMethod>()
            .CacheMethod(c => c.CachedMethod(null))
            .As <IObjectWithParametersOnCachedMethod>();

            factory   = CacheBuilder.BuildFactory();
            component = factory.Create <IObjectWithParametersOnCachedMethod>();
        }
Ejemplo n.º 17
0
        public void ShouldThrowIfUnknownType()
        {
            CacheBuilder
            .For <ObjectWithNonInterfaceMethod>()
            .CacheMethod(c => c.ReturnsFour())
            .AsImplemented();
            var factory = CacheBuilder.BuildFactory();

            Assert.Throws <ArgumentException>(() =>
                                              factory.ImplementationTypeFor(typeof(IObjectReturningNewGuids))
                                              );
        }
Ejemplo n.º 18
0
        public void MruOverCapacity()
        {
            var cache = CacheBuilder.MRU_ThreadSafe <int, int>(3);

            cache[1] = 10;
            cache[2] = 20;
            cache[3] = 30;

            Assert.IsTrue(cache.ContainsKey(3));
            cache[4] = 40;
            Assert.IsFalse(cache.ContainsKey(3));
        }
Ejemplo n.º 19
0
        protected override void TestSetup()
        {
            eventListener = new EventListenerForTest();
            CacheBuilder.AddEventListener(eventListener);

            CacheBuilder
            .For <ObjectWithParametersOnCachedMethod>()
            .CacheMethod(c => c.CachedMethod(null))
            .As <IObjectWithParametersOnCachedMethod>();

            factory = CacheBuilder.BuildFactory();
        }
Ejemplo n.º 20
0
        public async Task TestArrayCacheReturnsCachedItemsOnSubsequentCallsAndHandlesRefresh()
        {
            var position = 0;

            var arrayCache = CacheBuilder.For <string>()
                             .WithIdExtractor(v => v)
                             .WithElementRetriever(v => v.InTask())
                             .GetArrayCache <string>(v =>
            {
                // ReSharper disable AccessToModifiedClosure
                // ReSharper disable once ConvertToLambdaExpression
                return(new[] { $"{v}1:{position}", $"{v}2:{position}", $"{v}3:{position}" }.ToObservable());
                // ReSharper restore AccessToModifiedClosure
            });


            var id = Guid.NewGuid()
                     .ToString();

            var manualWaitHandle = new ManualResetEvent(false);
            var actualItemsTcs   = new TaskCompletionSource <string[]>();

            arrayCache.Get(id)
            .Do(v => manualWaitHandle.Set())
            .Take(3)
            .ToArray()
            .Subscribe(v =>
            {
                actualItemsTcs.SetResult(v.SelectMany(i => i)
                                         .ToArray());
            });

            manualWaitHandle.WaitOne();
            manualWaitHandle.Reset();

            position++;
            arrayCache.Refresh(id);

            manualWaitHandle.WaitOne();
            manualWaitHandle.Reset();

            position++;
            arrayCache.Refresh(id);

            manualWaitHandle.WaitOne();
            manualWaitHandle.Reset();

            var expectedItems = new[] { $"{id}1:0", $"{id}2:0", $"{id}3:0", $"{id}1:1", $"{id}2:1", $"{id}3:1", $"{id}1:2", $"{id}2:2", $"{id}3:2" };
            var actualItems   = await actualItemsTcs.Task.ConfigureAwait(false);

            Assert.Equal(expectedItems,
                         actualItems);
        }
Ejemplo n.º 21
0
        public void FactoryReturnsNewInterfaceInstances()
        {
            CacheBuilder
            .For <ObjectWithIdentifier>()
            .As <IObjectWithIdentifier>();
            var factory = CacheBuilder.BuildFactory();
            var obj1    = factory.Create <IObjectWithIdentifier>();
            var obj2    = factory.Create <IObjectWithIdentifier>();

            Assert.AreNotSame(obj1, obj2);
            Assert.AreNotEqual(obj1.Id, obj2.Id);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Creates a instance of the <see cref="IQueryExecutor"/> class by using
        /// the specified application settings.
        /// </summary>
        /// <param name="options">
        /// A <see cref="IDictionary{TKey,TValue}"/> containing the specific
        /// options configured for the query processor.
        /// </param>
        /// <returns>
        /// An instance of the <see cref="IQueryExecutor"/> class.
        /// </returns>
        public IQueryExecutor CreateQueryExecutor(
            IDictionary <string, string> options)
        {
            ICacheProvider cache_provider      = GetCacheProvider();
            ICache <IConnectionProvider> cache = new CacheBuilder <IConnectionProvider>()
                                                 .ExpireAfterAccess(settings_.QueryCacheDuration * 3, TimeUnit.Seconds)
                                                 .Build(cache_provider);
            IJsonCollectionFactory json_collection_factory =
                GetJsonCollectionFactory();

            return(new SqlQueryExecutor(json_collection_factory, cache));
        }
Ejemplo n.º 23
0
    public void ShouldLoadTheValueForMissingKey() {
      CacheBuilder<string> cache_builder = new CacheBuilder<string>();
      LoadingCacheMock<string> cache =
        new LoadingCacheMock<string>(cache_builder);

      CacheLoader<string> loader = new StringCacheLoader();
      string cached = cache.GetIfPresent("missing-key");
      Assert.IsNull(cached);

      cached = cache.Get("missing-key", loader);
      Assert.IsNotNull(cached);
    }
        public CachedFunctionWithOuterKeyAndInnerEnumerableKeys(
            Func <TParams, ReadOnlyMemory <TInnerKey>, CancellationToken, ValueTask <IEnumerable <KeyValuePair <TInnerKey, TValue> > > > originalFunction,
            Func <TParams, TOuterKey> keySelector,
            CachedFunctionWithOuterKeyAndInnerEnumerableKeysConfiguration <TParams, TOuterKey, TInnerKey, TValue> config)
        {
            _originalFunction        = originalFunction;
            _keySelector             = keySelector;
            _maxBatchSize            = config.MaxBatchSize;
            _maxBatchSizeFactory     = config.MaxBatchSizeFactory;
            _batchBehaviour          = config.BatchBehaviour;
            _onSuccessAction         = config.OnSuccessAction;
            _onExceptionAction       = config.OnExceptionAction;
            _filterResponsePredicate = config.FilterResponsePredicate;

            if (config.DisableCaching)
            {
                _cache = NullCache <TOuterKey, TInnerKey, TValue> .Instance;
            }
            else
            {
                if (config.TimeToLive.HasValue)
                {
                    _timeToLive = config.TimeToLive.Value;
                }
                else
                {
                    _timeToLiveFactory = config.TimeToLiveFactory;
                }

                _cache       = CacheBuilder.Build(config);
                _keyComparer = config.KeyComparer ?? EqualityComparer <TInnerKey> .Default;
                _skipCacheGetOuterPredicate = config.SkipCacheGetOuterPredicate;
                _skipCacheGetInnerPredicate = config.SkipCacheGetInnerPredicate;
                _skipCacheSetOuterPredicate = config.SkipCacheSetOuterPredicate;
                _skipCacheSetInnerPredicate = config.SkipCacheSetInnerPredicate;
            }

            if (config.FillMissingKeysConstantValue.IsSet)
            {
                _shouldFillMissingKeys = true;
                _shouldFillMissingKeysWithConstantValue = true;
                _fillMissingKeysConstantValue           = config.FillMissingKeysConstantValue.Value;
            }
            else if (!(config.FillMissingKeysValueFactory is null))
            {
                _shouldFillMissingKeys       = true;
                _fillMissingKeysValueFactory = config.FillMissingKeysValueFactory;
            }

            _cacheEnabled        = _cache.LocalCacheEnabled || _cache.DistributedCacheEnabled;
            _measurementsEnabled = _onSuccessAction != null || _onExceptionAction != null;
        }
Ejemplo n.º 25
0
		public void ShouldCache()
		{
			using (var factory = new CacheBuilder(_proxyFactory)
				.For<ObjectReturningNewGuids>()
				.CacheMethod(c => c.CachedMethod())
				.As<IObjectReturningNewGuids>()
				.BuildFactory())
			{
				var component = factory.Create<IObjectReturningNewGuids>();

				component.CachedMethod().Should().Be.EqualTo(component.CachedMethod());
			}
		}
Ejemplo n.º 26
0
        public void ShouldCache()
        {
            using (var factory = new CacheBuilder(_proxyFactory)
                                 .For <ObjectReturningNewGuids>()
                                 .CacheMethod(c => c.CachedMethod())
                                 .As <IObjectReturningNewGuids>()
                                 .BuildFactory())
            {
                var component = factory.Create <IObjectReturningNewGuids>();

                component.CachedMethod().Should().Be.EqualTo(component.CachedMethod());
            }
        }
Ejemplo n.º 27
0
        public void Setup()
        {
            var lockObjectGenerator = CreateLockObjectGenerator();

            CacheBuilder = new CacheBuilder(ProxyFactory)
                           .SetCache(CreateCache())
                           .SetCacheKey(CreateCacheKey());
            if (lockObjectGenerator != null)
            {
                CacheBuilder.SetLockObjectGenerator(lockObjectGenerator);
            }
            TestSetup();
        }
Ejemplo n.º 28
0
 public old_values_in_cache()
 {
     _cache = CacheBuilder
              .With <string, DateTime>(key =>
     {
         _count++;
         return(DateTime.Now);
     })
              .RefreshEvery(TimeSpan.FromMilliseconds(400))
              .EvictUnused()
              .Preload("a", "b")
              .Build();
 }
Ejemplo n.º 29
0
        public void VerifyCacheWhenLockObjectGeneratorIsUsed()
        {
            CacheBuilder
            .For <ObjectReturningNewGuids>()
            .CacheMethod(c => c.CachedMethod())
            .As <IObjectReturningNewGuids>();

            var factory = CacheBuilder.BuildFactory();

            var value = factory.Create <IObjectReturningNewGuids>().CachedMethod();

            Assert.AreEqual(value, factory.Create <IObjectReturningNewGuids>().CachedMethod());
        }
Ejemplo n.º 30
0
        public static void AddRedisCaching(this IServiceCollection services, IConfiguration configuration)
        {
            var redisConfig = new RedisConfiguration();
            var redisConfigurationSection = configuration.GetSection("JediCacheSettings:RedisConfiguration");

            redisConfigurationSection.Bind(redisConfig);

            services.AddSingleton <IDistributedCacheService>(
                CacheBuilder.Builder()
                .WithRedisConfiguration(redisConfig)
                .BuildDistributedCache()
                );
        }
Ejemplo n.º 31
0
    public void ShouldReplaceCachedValueWhenKeyAlreadyExists() {
      CacheBuilder<string> cache_builder = new CacheBuilder<string>();
      LoadingCacheMock<string> ref_cache =
        new LoadingCacheMock<string>(cache_builder);

      ref_cache.Put("already-in-cache-key", "original-value");
      string cached = ref_cache.GetIfPresent("already-in-cache-key");
      Assert.AreEqual("original-value", cached);

      ref_cache.Put("already-in-cache-key", "new-value");
      cached = ref_cache.GetIfPresent("already-in-cache-key");
      Assert.AreEqual("new-value", cached);
    }
Ejemplo n.º 32
0
 public Bag(CodeFileBuilder builder)
 {
     _builder      = builder;
     _where        = new Where(builder);
     _orderBy      = new OrderBy(builder);
     _cascade      = new Cascade(builder);
     _fetch        = new Fetch(builder);
     _inverse      = new Inverse(builder);
     _table        = new Table(builder);
     _keyColumn    = new KeyColumn(builder);
     _lazyLoad     = new LazyLoad(builder);
     _cacheBuilder = new CacheBuilder(builder);
 }
Ejemplo n.º 33
0
        public void ShouldThrowIfMultiple()
        {
            const string key = "aklsdjf";

            CacheBuilder.For <ObjectReturningNewGuids>(key)
            .CacheMethod(x => x.CachedMethod())
            .As <IObjectReturningNewGuids>();
            CacheBuilder.For <ObjectReturningNewGuidsNoInterface>(key)
            .CacheMethod(x => x.CachedMethod())
            .AsImplemented();
            Assert.Throws <InvalidOperationException>(() =>
                                                      CacheBuilder.BuildFactory());
        }
Ejemplo n.º 34
0
 public void OnlyDeclareTypeOnce()
 {
     CacheBuilder
     .For <ObjectReturningNewGuids>()
     .CacheMethod(c => c.CachedMethod())
     .As <IObjectReturningNewGuids>();
     Assert.Throws <ArgumentException>(()
                                       =>
                                       CacheBuilder
                                       .For <ObjectReturningNewGuids>()
                                       .CacheMethod(c => c.CachedMethod2())
                                       .As <IObjectReturningNewGuids>());
 }
Ejemplo n.º 35
0
        public static Cache <TKey, TValue> Create <TKey, TValue>(
            this CacheBuilder <TKey, TValue> builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            var cache = new Cache <TKey, TValue>(builder.CacheOptions);

            cache.LoaderFunction = builder.LoaderFunc;
            return(cache);
        }
        public async Task CacheAsync_SpecificImplementation_UsesSpecificCache()
        {
            var cache = CacheBuilder
                        .For <User>(u => u.UseAsKey(KEY).Complete(_userSpecificImplementationMock.Object))
                        .Build();

            await cache.CacheAsync(User.Test);

            _userSpecificImplementationMock
            .Verify(i => i.CacheAsync(KEY, User.Test, It.IsAny <CacheOptions>()), Times.Once);
            CacheImplementationMock
            .Verify(i => i.CacheAsync(It.IsAny <string>(), It.IsAny <User>(), It.IsAny <CacheOptions>()), Times.Never);
        }
Ejemplo n.º 37
0
        public void PublicObject_WithGenerics_IsSuccess()
        {
            var target = new PublicObjectWithGenerics <int>()
            {
                Value = _random.Next()
            };

            var syntax = CacheBuilder.CreateCache(target);

            var syntaxString = syntax.ToString();

            Assert.IsNotNull(syntaxString);
        }
Ejemplo n.º 38
0
    public void ShouldReturnsDefaultValueWhenKeyIsNotFound() {
      CacheBuilder<string> ref_cache_builder = new CacheBuilder<string>();
      LoadingCacheMock<string> ref_cache =
        new LoadingCacheMock<string>(ref_cache_builder);

      string cached = ref_cache.GetIfPresent("missing-key");
      Assert.AreEqual(null, cached);

      CacheBuilder<long> val_cache_builder = new CacheBuilder<long>();
      LoadingCacheMock<long> val_cache =
        new LoadingCacheMock<long>(val_cache_builder);

      long val_cached = val_cache.GetIfPresent("missing-key");
      Assert.AreEqual(default(long), val_cached);
    }
Ejemplo n.º 39
0
    public void ShouldStoreValueInCache() {
      CacheBuilder<string> ref_cache_builder = new CacheBuilder<string>();
      LoadingCacheMock<string> ref_cache =
        new LoadingCacheMock<string>(ref_cache_builder);

      CacheBuilder<long> val_cache_builder = new CacheBuilder<long>();
      LoadingCacheMock<long> val_cache =
        new LoadingCacheMock<long>(val_cache_builder);

      ref_cache.Put("ref-cache-key", "ref-cache-value");
      string ref_cached = ref_cache.GetIfPresent("ref-cache-key");
      Assert.AreEqual(ref_cached, "ref-cache-value");

      val_cache.Put("val-cache-key", 50);
      long val_cached = val_cache.GetIfPresent("val-cache-key");
      Assert.AreEqual(50, val_cached);
    }
Ejemplo n.º 40
0
        public void TypesOfStorage_ElementsAreProperlyObtainedFromCacheAndDataBase()
        {
            var dataBase = InitializeDataBase(amountOfElements: 5);
            var cache = new CacheBuilder<string>().Build(capacity: 3, timeOfExpirationInTicks: 1000, slowDataBase: dataBase);
            var listOfId = dataBase.GetListOfId();

            for (var i = 0; i < 5; i++)
                cache.GetElementById(listOfId[i]);

            for (var i = 2; i >= 0; i--)
                cache.GetElementById(listOfId[i]);

            var listOfElementsInCache = cache.GetListOfElementsLocatedInCache();

            const int amountOfElementsInCache = 1;
            Assert.AreEqual(amountOfElementsInCache, listOfElementsInCache.Count);
            const string valueOfElementInCache = "two";
            Assert.AreEqual(valueOfElementInCache, listOfElementsInCache[0].Value);
        }
Ejemplo n.º 41
0
    public void ShouldNotAcceptNegativeExpirarionOrRefreshValues() {
      CacheBuilder<string> builder = new CacheBuilder<string>();

      Assert.Throws<ArgumentOutOfRangeException>(
        delegate()
        {
          builder.ExpireAfterAccess(-1, TimeUnit.Seconds);
        });

      Assert.Throws<ArgumentOutOfRangeException>(
        delegate()
        {
          builder.ExpireAfterWrite(-1, TimeUnit.Seconds);
        });

      Assert.Throws<ArgumentOutOfRangeException>(
        delegate()
        {
          builder.RefreshAfterWrite(-1, TimeUnit.Seconds);
        });
    }
Ejemplo n.º 42
0
    public void ShouldThrowExceptionWhenCacheLoaderReturnsNull() {
      CacheBuilder<string> ref_cache_builder = new CacheBuilder<string>();
      LoadingCacheMock<string> ref_cache =
        new LoadingCacheMock<string>(ref_cache_builder);

      CacheBuilder<long> val_cache_builder = new CacheBuilder<long>();
      LoadingCacheMock<long> val_cache =
        new LoadingCacheMock<long>(val_cache_builder);

      CacheLoader<string> ref_loader = new StringCacheLoader();
      try {
        ref_cache.Get("missing-ref-key", ref_loader);
      } catch (ExecutionException exception) {
        Assert.IsAssignableFrom<InvalidCacheLoadException>(
          exception.InnerException);
      }

      CacheLoader<long> val_loader =
        CacheLoader<long>.From(delegate(string key) { return default(long); });

      Assert.DoesNotThrow(
        delegate() { val_cache.Get("missing-ref-key", val_loader); });
    }
Ejemplo n.º 43
0
    public void ShouldThrowExceptionWhenLoadFail() {
      CacheBuilder<long> cache_builder = new CacheBuilder<long>();
      LoadingCacheMock<long> cache = new LoadingCacheMock<long>(cache_builder);

      ThrowableLongCacheLoader long_cache_loader =
        new ThrowableLongCacheLoader();
      try {
        cache.Get("missing-key", long_cache_loader);
      } catch (ExecutionException exception) {
        Assert.IsAssignableFrom<ArgumentException>(exception.InnerException);
      }
    }
Ejemplo n.º 44
0
		public void ShouldThrowWhenCreatingNotKnownComponent()
		{
			var builder = new CacheBuilder(new ProxyImplThatThrowsNotSupportedEx());
			var factory = builder.BuildFactory();
			Assert.Throws<ArgumentException>(() => factory.Create<object>());
		}
Ejemplo n.º 45
0
 public void Capacity_DecreaseValueOfCacheCapacity_ExceptionThrown()
 {
     var dataBase = new DataBase<string>();
     var cache = new CacheBuilder<string>().Build(capacity: 10, slowDataBase: dataBase);
     cache.Capacity = 5;
 }
Ejemplo n.º 46
0
 public void Capacity_NegativeValue_ExceptionThrown()
 {
     var dataBase = new DataBase<string>();
     var cache = new CacheBuilder<string>().Build(capacity: 10, slowDataBase: dataBase);
     cache.Capacity = -15;
 }
Ejemplo n.º 47
0
 public void ShouldNotThrowExceptionWhenRemovingNonExistentKey() {
   CacheBuilder<string> cache_builder = new CacheBuilder<string>();
   LoadingCacheMock<string> ref_cache =
     new LoadingCacheMock<string>(cache_builder);
   ref_cache.Remove("missing-key");
 }
Ejemplo n.º 48
0
    public void ShouldThrowExceptionWhenKeyIsNull() {
      CacheBuilder<string> cache_builder = new CacheBuilder<string>();
      LoadingCacheMock<string> cache =
        new LoadingCacheMock<string>(cache_builder);

      CacheLoader<string> loader = new StringCacheLoader();
      Assert.Throws<ArgumentNullException>(
        delegate() { cache.Get(null, loader); });

      Assert.Throws<ArgumentNullException>(
        delegate() { cache.GetIfPresent(null); });

      Assert.Throws<ArgumentNullException>(
        delegate() { cache.Put(null, string.Empty); });

      Assert.Throws<ArgumentNullException>(delegate() { cache.Remove(null); });
    }