Exemplo n.º 1
0
 public void GetServiceRoutes_CalledWithServiceTypeUsingDtoDecoratedWithMultipleRoutes_ExpectAllRoutesFromDtoAreReturned()
 {
     ResolvedServiceRoutesFor <ServiceUsingDtoDecoratedWithMultipleRoutes>()
     .ShouldBeEquivalentTo(
         new Route("GET", "/request/multiple/1", InfoOf.Method <ServiceUsingDtoDecoratedWithMultipleRoutes>(x => x.ServiceMethod(null))),
         new Route("GET", "/request/multiple/2", InfoOf.Method <ServiceUsingDtoDecoratedWithMultipleRoutes>(x => x.ServiceMethod(null))));
 }
Exemplo n.º 2
0
        /// <summary>
        /// Gets the DebugView internal property value of provided expression.
        /// </summary>
        /// <param name="expression">Expression to get DebugView.</param>
        /// <returns>DebugView value.</returns>
        public static string GetDebugView([NotNull] this Expression expression)
        {
            Code.NotNull(expression, nameof(expression));

            if (_getDebugView == null)
            {
                var p = Expression.Parameter(typeof(Expression));

                try
                {
                    var l = Expression.Lambda <Func <Expression, string> >(
                        Expression.PropertyOrField(p, "DebugView"),
                        p);

                    _getDebugView = l.Compile();
                }
                catch (ArgumentException)
                {
                    var l = Expression.Lambda <Func <Expression, string> >(
                        Expression.Call(p, InfoOf <Expression> .Method(e => e.ToString())),
                        p);

                    _getDebugView = l.Compile();
                }
            }

            return(_getDebugView(expression));
        }
Exemplo n.º 3
0
        public void FieldAttribute()
        {
            var rd    = new AttributeReader();
            var attrs = rd.GetAttributes <MapValueAttribute>(InfoOf.Member <AttributeReaderTests>(a => a.Field1));

            Assert.AreEqual(0, attrs.Length);
        }
 public void GetServiceRoutes_CalledWithServiceTypeContainingNonAsyncServiceMethodsThatReturnTasks_EmptyServiceMethodsAreReturned()
 {
     ResolvedServiceRoutesFor <ServiceContainingNonAsyncServiceMethodsThatReturnTasks>()
     .ShouldBeEquivalentTo(
         new Route(
             "GET",
             "/requestone",
             InfoOf.Method <ServiceContainingNonAsyncServiceMethodsThatReturnTasks>(
                 x => x.ServiceMethod(new RequestOne()))),
         new Route(
             "GET",
             "/requesttwo",
             InfoOf.Method <ServiceContainingNonAsyncServiceMethodsThatReturnTasks>(
                 x => x.ServiceMethod(new RequestTwo()))),
         new Route(
             "GET",
             "/requestthree",
             InfoOf.Method <ServiceContainingNonAsyncServiceMethodsThatReturnTasks>(
                 x => x.ServiceMethod(new RequestThree(), CancellationToken.None))),
         new Route(
             "GET",
             "/requestfour",
             InfoOf.Method <ServiceContainingNonAsyncServiceMethodsThatReturnTasks>(
                 x => x.ServiceMethod(new RequestFour(), CancellationToken.None))));
 }
Exemplo n.º 5
0
		public void AttributeTest4()
		{
			var attrs = MappingSchema.Default.GetAttributes<MapValueAttribute>(
				InfoOf.Field<AttrTest>(a => a.Field1));

			Assert.That(attrs.Length, Is.EqualTo(3));
		}
        public void Build_Called_ExpectReturnedDelegateCallsServiceMethodOnFactoryCreatedServiceWithBoundModel(
            NancyModule module, object request, Request message, Response response)
        {
            var requestMessageBinderDelegate = MockRepository.GenerateStub <Func <object, object> >();

            requestMessageBinderDelegate.Stub(x => x(Arg <object> .Is.Same(request))).Return(message);

            var requestMessageBinder = MockRepository.GenerateStub <IServiceRequestBinder>();

            requestMessageBinder.Stub(x => x.CreateBindingDelegate(
                                          Arg <Type> .Is.Equal(typeof(Request)),
                                          Arg <ServiceRequestBinderContext> .Matches(ctx => ReferenceEquals(ctx.NancyModule, module))))
            .Return(requestMessageBinderDelegate);

            var service = MockRepository.GenerateStub <StubService>();

            service.Stub(x => x.ServiceMethod(Arg <Request> .Is.Same(message))).Return(response);

            var serviceFactory = MockRepository.GenerateStub <Func <Type, object> >();

            serviceFactory.Stub(x => x(Arg <Type> .Is.Equal(service.GetType()))).Return(service);

            var lambda = (Func <object, object>) new RouteDispatchBuilder()
                         .WithServiceFactory(serviceFactory)
                         .WithServiceMethodInvocation(new SyncServiceMethodInvocation())
                         .WithRequestMessageBinder(requestMessageBinder)
                         .WithModule(module)
                         .WithServiceType(service.GetType())
                         .WithMethod(InfoOf.Method <StubService>(x => x.ServiceMethod(null)))
                         .Build();

            lambda(request).Should().BeSameAs(response);
        }
Exemplo n.º 7
0
 public void GetServiceRoutes_CalledWithServiceTypeInheritingFromAnother_ExpectServiceMethodsFromBaseAndDerivedTypeAreReturned()
 {
     ResolvedServiceRoutesFor <ServiceInheritingFromAnotherType>()
     .ShouldBeEquivalentTo(
         new Route("GET", "/requesttwo", InfoOf.Method <ServiceInheritingFromAnotherType>(x => x.ServiceMethod(new RequestTwo()))),
         new Route("GET", "/requestthree", InfoOf.Method <ServiceInheritingFromAnotherType>(x => x.MethodFromDerivedService(new RequestThree()))));
 }
Exemplo n.º 8
0
            private bool BuildListMapper()
            {
                var fromListType = _fromExpression.Type;
                var toListType   = _localObject.Type;

                if (!toListType.IsSubClass(typeof(IEnumerable <>)) || !fromListType.IsSubClass(typeof(IEnumerable <>)))
                {
                    return(false);
                }

                var clearMethodInfo = toListType.GetMethod("Clear");

                if (clearMethodInfo != null)
                {
                    _expressions.Add(Call(_localObject, clearMethodInfo));
                }

                var fromItemType = fromListType.GetItemType();
                var toItemType   = toListType.GetItemType();

                var addRangeMethodInfo = toListType.GetMethod("AddRange");

                if (addRangeMethodInfo != null)
                {
                    var selectExpr = Select(_builder, _fromExpression, fromItemType, toItemType);
                    _expressions.Add(Call(_localObject, addRangeMethodInfo, selectExpr));
                }
                else if (toListType.IsGenericType && !toListType.IsGenericTypeDefinition)
                {
                    if (toListType.IsSubClass(typeof(ICollection <>)))
                    {
                        var selectExpr = Select(
                            _builder,
                            _fromExpression, fromItemType,
                            toItemType);

                        _expressions.Add(
                            Call(
                                InfoOf.Method(() => ((ICollection <int>)null).AddRange((IEnumerable <int>)null))
                                .GetGenericMethodDefinition()
                                .MakeGenericMethod(toItemType),
                                _localObject,
                                selectExpr));
                    }
                    else
                    {
                        _expressions.Add(
                            Assign(
                                _localObject,
                                _builder.ConvertCollection(_fromExpression, toListType)));
                    }
                }
                else
                {
                    throw new NotImplementedException();
                }

                return(true);
            }
Exemplo n.º 9
0
        private static MethodInfo CreateSpecialisedDelegateCreator(MethodInfo serviceMethod)
        {
            MethodInfo genericDelegateCreator =
                InfoOf.Method <AsyncVoidServiceMethodInvocation>(x => CreateInvocationDelegate <object>(null, null))
                .GetGenericMethodDefinition();

            return(genericDelegateCreator.MakeGenericMethod(GetTaskResultTypeFromMethodReturnType(serviceMethod)));
        }
Exemplo n.º 10
0
 public void CreateInvocationDelegate_CalledWithNullContext_ExpectArgumentNullExceptionWithCorrectParamName()
 {
     new SyncServiceMethodInvocation().Invoking(
         x => x.CreateInvocationDelegate(
             InfoOf.Method <StubService>(svc => svc.ServiceMethodWithResponse(null)),
             null))
     .ShouldThrow <ArgumentNullException>().And.ParamName.Should().Be("context");
 }
Exemplo n.º 11
0
 public void GetServiceRoutes_CalledWithServiceTypeContainingMixtureOfPublicAndNonPublicServiceMethods_ExpectOnlyPublicMethodsAreReturned()
 {
     ResolvedServiceRoutesFor <ServiceContainingMixtureOfPublicAndNonPublicMethods>()
     .ShouldBeEquivalentTo(
         new Route(
             "GET",
             "/requesttwo",
             InfoOf.Method <ServiceContainingMixtureOfPublicAndNonPublicMethods>(x => x.ServiceMethod(null))));
 }
Exemplo n.º 12
0
        public void CreateInvocationDelegate_CalledWithAsyncDecoratedMethodWithCancellationToken_ExpectReturnedDelegateReturnsDefaultResponse(
            StubService service, object request, Request dto, Response defaultResponse)
        {
            var lambda = (Func <object, CancellationToken, Task <object> >) new AsyncVoidServiceMethodInvocation().CreateInvocationDelegate(
                InfoOf.Method <StubService>(svc => svc.AsyncDecoratedMethodWithCancellationToken(null, CancellationToken.None)),
                Stub.InvocationContextFor(service, request, dto, defaultResponse));

            lambda(request, CancellationToken.None).Result.Should().BeSameAs(defaultResponse);
        }
Exemplo n.º 13
0
        public void PropertyAttribute()
        {
            var rd    = new AttributeReader();
            var attrs = rd.GetAttributes <MapValueAttribute>(InfoOf.Member <AttributeReaderTests>(a => a.Property1));

            Assert.NotNull(attrs);
            Assert.AreEqual(1, attrs.Length);
            Assert.AreEqual("TestName", attrs[0].Value);
        }
Exemplo n.º 14
0
        public void FieldAttribute()
        {
            var rd    = new XmlAttributeReader(new MemoryStream(Encoding.UTF8.GetBytes(Data)));
            var attrs = rd.GetAttributes <ColumnAttribute>(InfoOf.Member <XmlReaderTests>(a => a.Field1));

            Assert.NotNull(attrs);
            Assert.AreEqual(1, attrs.Length);
            Assert.AreEqual("TestName", attrs[0].Name);
        }
Exemplo n.º 15
0
		public void AttributeTest5()
		{
			var attrs = MappingSchema.Default.GetAttributes<MapValueAttribute>(
				InfoOf.Field<AttrTest>(a => a.Field1),
				a => a.Configuration);

			Assert.That(attrs.Length,   Is.EqualTo(1));
			Assert.That(attrs[0].Value, Is.EqualTo(1));
		}
Exemplo n.º 16
0
        public void CreateInvocationDelegate_CalledWithServiceMethodThatReturnsNoResponse_ExpectReturnedDelegateReturnsDefaultResponse(
            StubService service, object request, Request dto, Response defaultResponse)
        {
            var lambda = (Func <object, object>) new SyncServiceMethodInvocation().CreateInvocationDelegate(
                InfoOf.Method <StubService>(x => x.ServiceMethodWithNoResponse(null)),
                Stub.InvocationContextFor(service, request, dto, defaultResponse));

            lambda(request).Should().BeSameAs(defaultResponse);
        }
Exemplo n.º 17
0
 public void GetServiceRoutes_CalledWithServiceTypeContainingServiceMethodWithNoReturnValue_ExpectServiceMethodIsStillReturned()
 {
     ResolvedServiceRoutesFor <ServiceContainingServiceMethodWithNoReturnValue>()
     .ShouldBeEquivalentTo(
         new Route(
             "GET",
             "/requestone",
             InfoOf.Method <ServiceContainingServiceMethodWithNoReturnValue>(x => x.ServiceMethod(null))));
 }
Exemplo n.º 18
0
        public void CreateInvocationDelegate_CalledWithRequestOfIncompatibleType_ExpectExceptionRatherThanPassingNullRequestToService(
            object incompatibleRequest)
        {
            var service = MockRepository.GenerateStrictMock <StubService>();
            var lambda  = (Func <object, object>) new SyncServiceMethodInvocation().CreateInvocationDelegate(
                InfoOf.Method <StubService>(x => x.ServiceMethodWithNoResponse(null)),
                Stub.InvocationContextFor(service, incompatibleRequest, incompatibleRequest));

            lambda.Invoking(x => x(incompatibleRequest)).ShouldThrow <InvalidCastException>();
        }
Exemplo n.º 19
0
            //private Type _actualLocalObjectType;

            public Expression GetExpression()
            {
                _locals.Add(_localObject);

                if (!BuildArrayMapper())
                {
                    var newLocalObjectExpr = GetNewExpression(_toExpression.Type);

                    //_actualLocalObjectType = newLocalObjectExpr.Type;

                    _expressions.Add(Assign(
                                         _localObject,
                                         Condition(
                                             Equal(
                                                 _toExpression,
                                                 Constant(
                                                     _builder._mapperBuilder.MappingSchema.GetDefaultValue(_toExpression.Type),
                                                     _toExpression.Type)),
                                             Convert(newLocalObjectExpr, _toExpression.Type),
                                             _toExpression)));

                    if (_cacheMapper)
                    {
                        _expressions.Add(
                            Call(
                                InfoOf.Method(() => Add(null, null, null)),
                                _builder._data.LocalDic,
                                _fromExpression,
                                _localObject));
                    }

                    if (!BuildListMapper())
                    {
                        GetObjectExpression();
                    }
                }

                _expressions.Add(_localObject);

                var expr = Block(_locals, _expressions) as Expression;

                if (_cacheMapper)
                {
                    expr = Expression.Convert(
                        Coalesce(
                            Call(
                                InfoOf <IDictionary <object, object> > .Method(_ => GetValue(null, null)),
                                _builder._data.LocalDic,
                                _fromExpression),
                            expr),
                        _toExpression.Type);
                }

                return(expr);
            }
Exemplo n.º 20
0
        public void CreateInvocationDelegate_CalledWithServiceMethodThatReturnsNoResponse_ExpectServiceMethodIsStillCalled(
            object request, Request dto, Response defaultResponse)
        {
            var service = MockRepository.GenerateMock <StubService>();
            var lambda  = (Func <object, object>) new SyncServiceMethodInvocation().CreateInvocationDelegate(
                InfoOf.Method <StubService>(x => x.ServiceMethodWithNoResponse(null)),
                Stub.InvocationContextFor(service, request, dto, defaultResponse));

            lambda(request);
            service.AssertWasCalled(x => x.ServiceMethodWithNoResponse(Arg <Request> .Is.Same(dto)), x => x.Repeat.Once());
        }
Exemplo n.º 21
0
        public void GetServiceRoutes_CalledWithServiceTypeContainingMultipleRouteVerbs_ExpectServiceRoutesForEachVerbAreReturned()
        {
            const string routePath     = "/requestfive";
            var          serviceMethod = InfoOf.Method <ServiceContainingMultipleRouteVerbs>(x => x.ServiceMethod(new RequestFive()));

            ResolvedServiceRoutesFor <ServiceContainingMultipleRouteVerbs>()
            .ShouldBeEquivalentTo(
                new Route("ABC", routePath, serviceMethod),
                new Route("DEF", routePath, serviceMethod),
                new Route("GHI", routePath, serviceMethod));
        }
Exemplo n.º 22
0
		public void AttributeTest1()
		{
			var ms = new MappingSchema("2");

			var attrs = ms.GetAttributes<MapValueAttribute>(
				InfoOf.Field<AttrTestImpl>(a => a.Field1),
				a => a.Configuration);

			Assert.That(attrs.Length,   Is.EqualTo(2));
			Assert.That(attrs[0].Value, Is.EqualTo(2));
			Assert.That(attrs[1].Value, Is.EqualTo(1));
		}
Exemplo n.º 23
0
        public void CreateInvocationDelegate_CalledWithServiceMethodThatReturnsResponse_ExpectReturnedDelegateReturnsSameResponseAsServiceMethod(
            object request, Request dto, Response response)
        {
            var service = MockRepository.GenerateStub <StubService>();

            service.Stub(x => x.ServiceMethodWithResponse(Arg <Request> .Is.Same(dto))).Return(response);

            var lambda = (Func <object, object>) new SyncServiceMethodInvocation().CreateInvocationDelegate(
                InfoOf.Method <StubService>(x => x.ServiceMethodWithResponse(null)), Stub.InvocationContextFor(service, request, dto));

            lambda(request).Should().BeSameAs(response);
        }
Exemplo n.º 24
0
        public void PropertyAttribute()
        {
            var rd = new XmlAttributeReader(new MemoryStream(Encoding.UTF8.GetBytes(Data)));

            MappingSchema.Default.AddMetadataReader(rd);

            var attrs = MappingSchema.Default.GetAttributes <MapValueAttribute>(InfoOf.Member <XmlReaderTests>(a => a.Property1));

            Assert.NotNull(attrs);
            Assert.AreEqual(1, attrs.Length);
            Assert.AreEqual("TestName", attrs[0].Value);
        }
Exemplo n.º 25
0
        public void CreateInvocationDelegate_CalledWithNonAsyncDecoratedMethodWithSingleParameter_ExpectReturnedDelegateReturnsResponse(
            object request, Request dto, Response response)
        {
            var service = MockRepository.GenerateStub <StubService>();

            service.Stub(x => x.NonAsyncDecoratedMethodWithTaskOfTResponse(Arg <Request> .Is.Same(dto))).Return(Task.FromResult(response));

            var lambda = (Func <object, CancellationToken, Task <object> >) new AsyncTaskOfTServiceMethodInvocation().CreateInvocationDelegate(
                InfoOf.Method <StubService>(svc => svc.NonAsyncDecoratedMethodWithTaskOfTResponse(null)),
                Stub.InvocationContextFor(service, request, dto));

            lambda(request, CancellationToken.None).Result.Should().BeSameAs(response);
        }
Exemplo n.º 26
0
 public void GetServiceRoutes_CalledWithServiceTypeContainingMixtureOfServiceAndNonServiceMethods_ExpectOnlyServiceMethodsAreReturned()
 {
     ResolvedServiceRoutesFor <ServiceContainingMixtureOfServiceAndNonServiceMethods>()
     .ShouldBeEquivalentTo(
         new Route(
             "GET",
             "/requesttwo",
             InfoOf.Method <ServiceContainingMixtureOfServiceAndNonServiceMethods>(x => x.ServiceMethod(new RequestTwo()))),
         new Route(
             "GET",
             "/requestfour",
             InfoOf.Method <ServiceContainingMixtureOfServiceAndNonServiceMethods>(x => x.ServiceMethod(new RequestFour()))));
 }
Exemplo n.º 27
0
 public void GetServiceRoutes_CalledWithServiceTypeContainingImplementationsOfInterfaceServiceMethods_ExpectInterfaceAndDeclaredServiceMethodsAreReturned()
 {
     ResolvedServiceRoutesFor <ServiceContainingImplementationsOfInterfaceServiceMethods>()
     .ShouldBeEquivalentTo(
         new Route(
             "GET",
             "/requestone",
             InfoOf.Method <ServiceContainingImplementationsOfInterfaceServiceMethods>(x => x.ServiceMethod(new RequestOne()))),
         new Route(
             "GET",
             "/requesttwo",
             InfoOf.Method <ServiceContainingImplementationsOfInterfaceServiceMethods>(x => x.ServiceMethod(new RequestTwo()))));
 }
        public void Build_CalledWhenDefaultResponseNotSetForServiceMethodNotReturningResponse_ExpectReturnedDelegateReturnsHttpNoContentResponse(
            NancyModule module, object requestParameters, Request request)
        {
            var lambda = (Func <object, object>) new RouteDispatchBuilder()
                         .WithServiceFactory(x => new StubService())
                         .WithServiceMethodInvocation(new SyncServiceMethodInvocation())
                         .WithRequestMessageBinder(StubRequestMessageBinderToReturn(request))
                         .WithModule(module)
                         .WithServiceType(typeof(StubService))
                         .WithMethod(InfoOf.Method <StubService>(x => x.ServiceMethodNotReturningResponse(null)))
                         .Build();

            lambda(requestParameters).Should().Be(HttpStatusCode.NoContent);
        }
Exemplo n.º 29
0
        public void AttributeTest6()
        {
            var ms = new MappingSchema("2",
                                       new MappingSchema("3")
            {
                MetadataReader = new XmlAttributeReader(new MemoryStream(Encoding.UTF8.GetBytes(Data)))
            });

            var attrs = ms.GetAttributes <MapValueAttribute>(
                InfoOf.Field <AttrTest>(a => a.Field1),
                a => a.Configuration);

            Assert.That(attrs !.Length, Is.EqualTo(4));
            Assert.That(attrs ![0].Value, Is.EqualTo(2));
        public void CreateInvocationDelegate_CalledWithNonAsyncDecoratedMethodWithSingleParameter_ExpectServiceMethodCalledAndAwaitedBeforeResponse(
            object request, Request dto, Response defaultResponse)
        {
            var wasCalledWithCorrectArguments = new ManualResetEvent(false);
            var service = CreateStrictMockServiceForDelayedEvent(
                x => x.NonAsyncDecoratedMethodWithTaskResponse(Arg <Request> .Is.Same(dto)),
                wasCalledWithCorrectArguments);

            var lambda = (Func <object, CancellationToken, Task <object> >) new AsyncTaskServiceMethodInvocation().CreateInvocationDelegate(
                InfoOf.Method <StubService>(svc => svc.NonAsyncDecoratedMethodWithTaskResponse(null)),
                Stub.InvocationContextFor(service, request, dto, defaultResponse));

            lambda(request, CancellationToken.None).Wait();
            wasCalledWithCorrectArguments.WaitOne(TimeSpan.FromTicks(1)).Should().BeTrue();
        }