Exemple #1
0
        public void SupplyingANullArrayOfAdditionalInterfacesThrows()
        {
            // arrange
            IInstanceInterceptor interceptor = new InterfaceInterceptor();
            HasSomeProperties    target      = new HasSomeProperties();

            // act
            Exception exception = null;

            try
            {
                object proxy =
                    interceptor.CreateProxy(
                        typeof(IHaveSomeProperties),
                        target,
                        (Type[])null);
            }
            catch (ArgumentNullException e)
            {
                exception = e;
            }

            // assert
            Assert.IsNotNull(exception);
        }
        public void WhenTransparentProxyIsInterceptedUsingInterfaceInterceptor()
        {
            bool intercepted = false;
            InterfaceInterceptor interceptor = new InterfaceInterceptor();

            TestProxy <ITest, TestClass> myProxy = new TestProxy <ITest, TestClass>();

            ITest instance = myProxy.CreateProxy();

            var interceptedMethodList = from i in interceptor.GetInterceptableMethods(typeof(ITest), instance.GetType())
                                        where i.InterfaceMethodInfo.Name == "TestMethod"
                                        select i;

            bool containsMethod = interceptedMethodList.Count() == 1;

            Assert.IsTrue(containsMethod);

            var interceptedProxy = interceptor.CreateProxy(typeof(ITest), instance);

            interceptedProxy.AddInterceptionBehavior(
                new ActionInterceptionBehavior(() => intercepted = true));

            int result = ((ITest)interceptedProxy).TestMethod("sample");

            Assert.IsTrue(intercepted);
        }
Exemple #3
0
        public void ParametersPassProperlyToTarget()
        {
            IInstanceInterceptor interceptor = new InterfaceInterceptor();
            MyDal target = new MyDal();

            IInterceptingProxy proxy           = interceptor.CreateProxy(typeof(IDal), target);
            CallCountHandler   depositHandler  = new CallCountHandler();
            CallCountHandler   withdrawHandler = new CallCountHandler();

            proxy.SetPipeline(typeof(IDal).GetMethod("Deposit"),
                              new HandlerPipeline(new ICallHandler[] { depositHandler }));
            proxy.SetPipeline(typeof(IDal).GetMethod("Withdraw"),
                              new HandlerPipeline(new ICallHandler[] { withdrawHandler }));

            IDal intercepted = (IDal)proxy;

            intercepted.Deposit(100.0);
            intercepted.Deposit(25.95);
            intercepted.Deposit(19.95);

            intercepted.Withdraw(15.00);
            intercepted.Withdraw(6.25);

            Assert.AreEqual(3, depositHandler.CallCount);
            Assert.AreEqual(2, withdrawHandler.CallCount);

            Assert.AreEqual(100.0 + 25.95 + 19.95 - 15.00 - 6.25, target.Balance);
        }
Exemple #4
0
        public void SupplyingOpenGenericInterfacesAsAdditionalInterfacesThrows()
        {
            // arrange
            IInstanceInterceptor interceptor = new InterfaceInterceptor();
            HasSomeProperties    target      = new HasSomeProperties();

            // act
            Exception exception = null;

            try
            {
                object proxy =
                    interceptor.CreateProxy(
                        typeof(IHaveSomeProperties),
                        target,
                        typeof(IGenericOne <>));
            }
            catch (ArgumentException e)
            {
                exception = e;
            }

            // assert
            Assert.IsNotNull(exception);
        }
Exemple #5
0
        public void CanImplementMultipleInterfacesWithSameMethodSignatures()
        {
            // arrange
            IInstanceInterceptor        interceptor = new InterfaceInterceptor();
            BaseInterfaceImplementation target      = new BaseInterfaceImplementation();
            object proxy = interceptor.CreateProxy(typeof(IBaseInterface), target, typeof(IBaseInterface2));

            object[] returnValues = new object[] { this, "return value" };
            int      returnValue  = 0;

            ((IInterceptingProxy)proxy).AddInterceptionBehavior(
                new DelegateInterceptionBehavior(
                    (mi, getNext) =>
            {
                return(mi.CreateMethodReturn(returnValues[returnValue++]));
            }));

            // act
            object value1 = ((IBaseInterface)proxy).TargetMethod();
            string value2 = ((IBaseInterface2)proxy).TargetMethod();

            // assert
            Assert.AreEqual(this, value1);
            Assert.AreEqual("return value", value2);
        }
        public void CanValidate()
        {
            var instance    = new Validatable();
            var interceptor = new InterfaceInterceptor();
            var proxy       = interceptor.Intercept(instance, typeof(IValidatable), new ValidationInterceptionHandler()) as IValidatable;

            Assert.Throws <ValidationException>(() => proxy.Try());
        }
        public void CanControlAccess()
        {
            var instance    = new ProtectedClass();
            var interceptor = new InterfaceInterceptor();
            var proxy       = interceptor.Intercept(instance, typeof(IProtectedClass), new AccessControlInterceptionHandler("")) as IProtectedClass;

            Assert.Throws <InvalidOperationException>(() =>
                                                      proxy.TryAccess()
                                                      );
        }
        public void CanCacheInterfaceGeneration()
        {
            var interceptor = new InterfaceInterceptor();
            var generator   = new RoslynInterceptedTypeGenerator().AsCached();

            var proxyType1 = generator.Generate(interceptor, typeof(MyType), typeof(ModifyResultHandler));
            var proxyType2 = generator.Generate(interceptor, typeof(MyType), typeof(ModifyResultHandler));

            Assert.Equal(proxyType1, proxyType2);
        }
        public void CanEnforceTimeout()
        {
            var instance    = new LongWait();
            var interceptor = new InterfaceInterceptor();
            var handler     = new TimeoutInterceptionHandler(3);

            var proxy = this.InstanceInterception(interceptor, instance, handler) as ILongWait;

            Assert.Throws <TimeoutException>(() => proxy.DoLongOperation());
        }
        public void CanRetry()
        {
            var instance    = new ErrorOperation();
            var interceptor = new InterfaceInterceptor();
            var proxy       = interceptor.Intercept(instance, typeof(IErrorOperation), new RetriesInterceptionHandler(3, TimeSpan.FromSeconds(5))) as IErrorOperation;

            Assert.Throws <InvalidOperationException>(() =>
                                                      proxy.Throw()
                                                      );
        }
Exemple #11
0
        public void CanGetInterceptableMethodsForProxy()
        {
            ProxiedInterfaceImpl impl     = new ProxiedInterfaceImpl();
            IProxiedInterface    instance = (IProxiedInterface) new MyProxy(typeof(IProxiedInterface), impl).GetTransparentProxy();

            IInstanceInterceptor interceptor = new InterfaceInterceptor();

            var interceptableMethods = interceptor.GetInterceptableMethods(typeof(IProxiedInterface), instance.GetType()).ToArray();

            interceptableMethods.Where(x => x.InterfaceMethodInfo.Name == "DoSomething").AssertHasItems();
        }
        public void CanGetInterceptableMethodsForProxy()
        {
            ProxiedInterfaceImpl impl = new ProxiedInterfaceImpl();
            IProxiedInterface instance = (IProxiedInterface)new MyProxy(typeof(IProxiedInterface), impl).GetTransparentProxy();

            IInstanceInterceptor interceptor = new InterfaceInterceptor();

            var interceptableMethods = interceptor.GetInterceptableMethods(typeof(IProxiedInterface), instance.GetType()).ToArray();

            interceptableMethods.Where(x => x.InterfaceMethodInfo.Name == "DoSomething").AssertHasItems();
        }
Exemple #13
0
        public void InterceptorMapsGenericMethodsOnClosedGenericInterfaces()
        {
            IInstanceInterceptor interceptor = new InterfaceInterceptor();

            List <MethodImplementationInfo> methods = Seq.Make(interceptor.GetInterceptableMethods(typeof(IGenericOne <string>), typeof(GenericImplementationOne <string>))).ToList();

            List <MethodImplementationInfo> expected = Sequence.ToList(
                GetExpectedMethods <IGenericOne <string>, GenericImplementationOne <string> >("DoSomething"));

            CollectionAssert.AreEquivalent(expected, methods);
        }
Exemple #14
0
        public void ReflectingOverProxyTypeReturnsProperties()
        {
            IInstanceInterceptor interceptor = new InterfaceInterceptor();
            HasSomeProperties    target      = new HasSomeProperties();
            IInterceptingProxy   proxy       = interceptor.CreateProxy(typeof(IHaveSomeProperties), target);

            List <PropertyInfo> interfaceProperties = new List <PropertyInfo>(typeof(IHaveSomeProperties).GetProperties());
            List <PropertyInfo> proxyProperties     = new List <PropertyInfo>(proxy.GetType().GetProperties());

            Assert.AreEqual(interfaceProperties.Count, proxyProperties.Count);
        }
Exemple #15
0
        public void InterceptorReturnsCorrectMethodsForInterceptableType()
        {
            IInstanceInterceptor            interceptor = new InterfaceInterceptor();
            List <MethodImplementationInfo> methods     = Seq.Make(interceptor.GetInterceptableMethods(typeof(IInterfaceOne), typeof(ImplementationOne))).ToList();

            List <MethodImplementationInfo> expected = Seq.Collect(
                new MethodImplementationInfo(typeof(IInterfaceOne).GetMethod("TargetMethod"),
                                             typeof(ImplementationOne).GetMethod("TargetMethod"))).ToList();

            CollectionAssert.AreEquivalent(expected, methods);
        }
Exemple #16
0
        [Ignore] // TODO: Known issue - we don't copy attributes yet
        public void ProxyPropertyReflectionReturnsAttributes()
        {
            IInstanceInterceptor interceptor = new InterfaceInterceptor();
            HasSomeProperties    target      = new HasSomeProperties();
            IInterceptingProxy   proxy       = interceptor.CreateProxy(typeof(IHaveSomeProperties), target);

            PropertyInfo    nameProp = proxy.GetType().GetProperty("Name");
            SampleAttribute attr     = (SampleAttribute)Attribute.GetCustomAttribute(nameProp, typeof(SampleAttribute));

            Assert.AreEqual("A name", attr.Name);
        }
        static void InterfaceInterceptor(object instance)
        {
            //Interface interceptor
            var interceptor      = new InterfaceInterceptor();
            var canIntercept     = interceptor.CanIntercept(instance);
            var myProxy          = interceptor.Intercept(instance, typeof(IMyType), new MyHandler()) as IMyType;
            var proxy            = myProxy as IInterceptionProxy;
            var otherInterceptor = proxy.Interceptor;
            var result           = myProxy.MyMethod();

            Assert.AreEqual(20, result);
        }
        public void CanDoInterfaceInterception()
        {
            var instance    = new MyType();
            var interceptor = new InterfaceInterceptor();
            var handler     = new ModifyResultHandler();

            var proxy = this.InstanceInterception(interceptor, instance, handler) as IMyType;

            var result = proxy.MyMethod();

            Assert.Equal(20, result);
        }
Exemple #19
0
        public void MultipleProxiesForTheSameInterfaceHaveTheSameType()
        {
            // arrange
            IInstanceInterceptor interceptor = new InterfaceInterceptor();
            HasSomeProperties    target      = new HasSomeProperties();

            // act
            object proxy1 = interceptor.CreateProxy(typeof(IHaveSomeProperties), target);
            object proxy2 = interceptor.CreateProxy(typeof(IHaveSomeProperties), target);

            // assert
            Assert.AreSame(proxy1.GetType(), proxy2.GetType());
        }
Exemple #20
0
        public void InterceptorCreatesProxyInstance()
        {
            IInstanceInterceptor   interceptor = new InterfaceInterceptor();
            ImplementsInterfaceOne target      = new ImplementsInterfaceOne();

            IInterceptingProxy proxy = interceptor.CreateProxy(typeof(IInterfaceOne), target);

            IInterfaceOne intercepted = (IInterfaceOne)proxy;

            intercepted.TargetMethod();

            Assert.IsTrue(target.TargetMethodCalled);
        }
        public void CanDoCallback()
        {
            var called      = false;
            var instance    = new LongWait();
            var interceptor = new InterfaceInterceptor();
            var handler     = new CallbackInterceptionHandler(() => called = true);

            var proxy = this.InstanceInterception(interceptor, instance, handler) as ILongWait;

            proxy.DoLongOperation();

            Assert.True(called);
        }
Exemple #22
0
        public void TestSetUp()
        {
            var innerCatalog = new TypeCatalog(typeof(Customer));
            var interceptor  = new InterfaceInterceptor();

            var valueInterceptor = new DynamicProxyInterceptor(interceptor);
            var cfg = new InterceptionConfiguration()
                      .AddInterceptor(valueInterceptor);

            var catalog = new InterceptingCatalog(innerCatalog, cfg);

            container = new CompositionContainer(catalog);
        }
        public void CanCache()
        {
            var instance    = new Calculator();
            var interceptor = new InterfaceInterceptor();
            var proxy       = interceptor.Intercept(instance, typeof(ICalculator), new CachingInterceptionHandler(new MemoryCache(Options.Create <MemoryCacheOptions>(new MemoryCacheOptions())), TimeSpan.FromSeconds(10))) as ICalculator;

            proxy.Add(1, 2);

            var timer = Stopwatch.StartNew();

            proxy.Add(1, 2);
            Assert.True(timer.Elapsed < TimeSpan.FromSeconds(5));
        }
Exemple #24
0
        public void ProxyInterceptsEvents()
        {
            IInstanceInterceptor          interceptor          = new InterfaceInterceptor();
            ClassWithEvents               target               = new ClassWithEvents();
            IInterceptingProxy            proxy                = interceptor.CreateProxy(typeof(IDoEvents), target);
            CallCountInterceptionBehavior interceptionBehavior = new CallCountInterceptionBehavior();

            proxy.AddInterceptionBehavior(interceptionBehavior);

            ((IDoEvents)proxy).SomeEvent += (s, a) => { };

            Assert.AreEqual(1, interceptionBehavior.CallCount);
        }
Exemple #25
0
        public void CanCreateProxyForMultipleInterfaces()
        {
            // arrange
            IInstanceInterceptor interceptor = new InterfaceInterceptor();
            HasSomeProperties    target      = new HasSomeProperties();

            // act
            object proxy = interceptor.CreateProxy(typeof(IHaveSomeProperties), target, typeof(IInterfaceOne));

            // assert
            Assert.IsTrue(proxy is IHaveSomeProperties);
            Assert.IsTrue(proxy is IInterfaceOne);
        }
Exemple #26
0
        public void AdditionalInterfaceIsImplementedExplicitly()
        {
            // arrange
            IInstanceInterceptor interceptor = new InterfaceInterceptor();
            HasSomeProperties    target      = new HasSomeProperties();

            // act
            object           proxy            = interceptor.CreateProxy(typeof(IHaveSomeProperties), target, typeof(IInterfaceTwo));
            InterfaceMapping interfaceMapping = proxy.GetType().GetInterfaceMap(typeof(IInterfaceTwo));

            // assert
            Assert.IsNull(interfaceMapping.TargetMethods.FirstOrDefault(mi => mi.IsPublic));
        }
Exemple #27
0
        public void AssortedParameterKindsAreProperlyHandled()
        {
            IInstanceInterceptor interceptor = new InterfaceInterceptor();

            AssortedParameterKindsAreProperlyHandledHelper.TypeWithAssertedParameterKinds target =
                new AssortedParameterKindsAreProperlyHandledHelper.TypeWithAssertedParameterKinds();

            IInterceptingProxy proxy =
                interceptor.CreateProxy(
                    typeof(AssortedParameterKindsAreProperlyHandledHelper.ITypeWithAssertedParameterKinds),
                    target);

            AssortedParameterKindsAreProperlyHandledHelper.PerformTest(proxy);
        }
Exemple #28
0
        public void ProxiesForTheSameInterfaceButDifferentAdditionalInterfacesDoNotHaveTheSameType()
        {
            // arrange
            IInstanceInterceptor interceptor = new InterfaceInterceptor();
            HasSomeProperties    target      = new HasSomeProperties();

            // act
            object proxy1 = interceptor.CreateProxy(typeof(IHaveSomeProperties), target, typeof(IBaseInterface));
            object proxy2 = interceptor.CreateProxy(typeof(IHaveSomeProperties), target, typeof(IBaseInterface2));

            // assert
            Assert.AreNotSame(proxy1.GetType(), proxy2.GetType());
            Assert.IsTrue(proxy1 is IBaseInterface);
            Assert.IsTrue(proxy2 is IBaseInterface2);
        }
        public void InterceptorCanInterceptProxyInstances()
        {
            CallCountInterceptionBehavior callCounter = new CallCountInterceptionBehavior();

            ProxiedInterfaceImpl impl = new ProxiedInterfaceImpl();
            IProxiedInterface instance = (IProxiedInterface)new MyProxy(typeof(IProxiedInterface), impl).GetTransparentProxy();

            IInstanceInterceptor interceptor = new InterfaceInterceptor();

            IInterceptingProxy proxy = (IInterceptingProxy)interceptor.CreateProxy(typeof(IProxiedInterface), (IProxiedInterface)instance);
            proxy.AddInterceptionBehavior(callCounter);

            IProxiedInterface inter = (IProxiedInterface)proxy;

            Assert.AreEqual("hello world", inter.DoSomething());
            Assert.AreEqual(1, callCounter.CallCount);
        }
        public void CanCreateTransactions()
        {
            var instance    = new Calculator();
            var interceptor = new InterfaceInterceptor();
            var handler     = new MultiInterceptionHandler();
            var result      = false;

            handler.Handlers.Add(new TransactionInterceptionHandler(TimeSpan.FromSeconds(10), System.Transactions.TransactionScopeAsyncFlowOption.Enabled, System.Transactions.TransactionScopeOption.Required, System.Transactions.IsolationLevel.ReadCommitted));
            handler.Handlers.Add(new DelegateInterceptionHandler(ctx =>
            {
                result = Transaction.Current != null;
            }));
            var proxy = interceptor.Intercept(instance, typeof(ICalculator), handler) as ICalculator;

            proxy.Add(1, 2);
            Assert.True(result);
        }
        public void CanRaiseNotifyChangeEvents()
        {
            var instance    = new Notifiable();
            var interceptor = new InterfaceInterceptor();
            var proxy       = interceptor.Intercept(instance, typeof(INotifiable), new NotifyPropertyChangeHandler()) as INotifiable;

            var propertyChangingFired = false;
            var propertyChangedFired  = false;

            proxy.PropertyChanging += (sender, args) => propertyChangingFired = true;
            proxy.PropertyChanged  += (sender, args) => propertyChangedFired = true;

            proxy.Name = "";

            Assert.True(propertyChangingFired);
            Assert.True(propertyChangedFired);
        }
Exemple #32
0
        public void CanImplementAdditionalClosedGenericInterface()
        {
            // arrange
            IInstanceInterceptor interceptor = new InterfaceInterceptor();
            HasSomeProperties    target      = new HasSomeProperties();

            // act
            object proxy =
                interceptor.CreateProxy(
                    typeof(IHaveSomeProperties),
                    target,
                    typeof(IGenericOne <string>));

            // assert
            Assert.IsTrue(proxy is IHaveSomeProperties);
            Assert.IsTrue(proxy is IGenericOne <string>);
        }
		static void InterfaceInterceptor(object instance)
		{
			//Interface interceptor
			var interceptor = new InterfaceInterceptor();
			var canIntercept = interceptor.CanIntercept(instance);
			var myProxy = interceptor.Intercept(instance, typeof(IMyType), new MyHandler()) as IMyType;
			var proxy = myProxy as IInterceptionProxy;
			var otherInterceptor = proxy.Interceptor;
			var result = myProxy.MyMethod();
			Assert.AreEqual(20, result);
		}
        ISignatureTestTarget GetTarget()
        {
            var interceptor = new InterfaceInterceptor();
            PolicySet policySet = GetPolicies();
            var target = new SignatureTestTarget();
            IInterceptingProxy proxy = interceptor.CreateProxy(typeof(ISignatureTestTarget), target);

            PipelineManager manager = new PipelineManager();
            foreach (MethodImplementationInfo method in interceptor.GetInterceptableMethods(typeof(ISignatureTestTarget), typeof(SignatureTestTarget)))
            {
                HandlerPipeline pipeline = new HandlerPipeline(
                    policySet.GetHandlersFor(method, container));
                manager.SetPipeline(method.ImplementationMethodInfo, pipeline);
            }
            proxy.AddInterceptionBehavior(new PolicyInjectionBehavior(manager));

            return (ISignatureTestTarget)proxy;
        }