Esempio n. 1
0
 public void Setup()
 {
     ValidationFactory.SetDefaultConfigurationValidatorFactory(new SystemConfigurationSource(false));
     host =
         new TestServiceHost <TestServiceImplementation, ITestService>(
             Settings.Default.TestServiceAddress);
 }
        public async Task Can_invoke_service()
        {
            var           host     = new TestServiceHost("http://example.com", new HelloServiceBootstrapper());
            HelloResponse response = await host.Client.Send <HelloResponse>(new HelloRequest { Name = "World!" });

            response.Result.Should().Be("Hello, World!");
        }
            public async Task GivenJobWithConstructorArgs_ItResolvesThemFromTheContainer()
            {
                // Arrange
                var expected = new SomeService();
                var host     = new TestServiceHost(
                    componentRegistrations: b => {
                    b.RegisterInstance(expected).As <SomeService>();
                });

                host.Initialize();

                var job = new JobDescription("test", typeof(TestJobWithService));

                var dispatcher = new JobDispatcher(new[] { job }, host.Container);
                var invocation = TestHelpers.CreateInvocation(Guid.NewGuid(), "Test", "test", new Dictionary <string, string>());
                var context    = new InvocationContext(invocation, queue: null);
                var slot       = new ContextSlot();

                TestJobWithService.SetContextSlot(slot);

                // Act
                await dispatcher.Dispatch(context);

                // Assert
                Assert.Same(expected, slot.Value);
            }
 public void Setup()
 {
     ValidationFactory.SetDefaultConfigurationValidatorFactory(new SystemConfigurationSource(false));
     host =
         new TestServiceHost<TestServiceImplementation, ITestService>(
             Settings.Default.TestServiceAddress);
 }
Esempio n. 5
0
        public static void CredentialsNotNull()
        {
            var host  = new TestServiceHost();
            var creds = host.Credentials;

            Assert.NotNull(creds);
            Assert.IsType <ServiceCredentials>(creds);
            // Make sure same instance is returned each time
            Assert.Same(creds, host.Credentials);
        }
Esempio n. 6
0
        public void WebDataServiceConstructorCustomTest()
        {
            TestServiceHost      host   = new TestServiceHost();
            DataService <string> target = new DataService <string>();

            target.AttachHost(host);
            object operationContext = target.GetType().GetField("operationContext", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target);
            object actualHost       = operationContext.GetType().GetField("hostInterface", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(operationContext);

            Assert.AreSame(host, actualHost);
        }
            public async Task ItInvokesOnStart()
            {
                // Arrange
                var host      = new TestServiceHost();
                var container = CreateTestContainer();
                var service   = new TestService(TestName, host);

                // Act
                await service.Start(container);

                // Assert
                Assert.True(service.WasStarted);
            }
            public async Task ItConfiguresShutdownTokenToCallOnShutdown()
            {
                // Arrange
                var host      = new TestServiceHost();
                var container = CreateTestContainer();
                var service   = new TestService(TestName, host);
                await service.Start(container);

                // Act
                host.Shutdown();

                // Assert
                Assert.True(service.WasShutdown);
            }
Esempio n. 9
0
 private void MethodNotAllowedServiceTest(bool asynchronousSendEnabled, bool streamed)
 {
     using (var host = TestServiceHost.CreateWebHost <TestService>(asynchronousSendEnabled, false, streamed, new HttpMessageHandlerFactory(typeof(TestHandler))))
     {
         using (var client = TestServiceClient.CreateClient(false, TestServiceCommon.ServiceAddress))
         {
             var result = TestServiceClient.RunClient(client, TestHeaderOptions.InsertRequest | TestHeaderOptions.ValidateResponse, HttpMethod.Options);
             foreach (var httpResponse in result)
             {
                 TestServiceCommon.ValidateMethodNotAllowedResponse(httpResponse);
             }
         }
     }
 }
            public async Task ItInjectsPropertiesWithPublicSetters()
            {
                // Arrange
                var host      = new TestServiceHost();
                var container = CreateTestContainer();
                var service   = new TestServiceWithComponents(TestName, host);

                // Act
                await service.Start(container);

                // Assert
                Assert.Same(service.Something, container.Resolve <SomeComponent>());
                Assert.Null(service.SomethingElse);
            }
Esempio n. 11
0
 private void MissingPropertyServiceTest(bool asynchronousSendEnabled, bool faultDetail, bool streamed)
 {
     using (var host = TestServiceHost.CreateWebHost <TestService>(asynchronousSendEnabled, faultDetail, streamed, new HttpMessageHandlerFactory(typeof(TestHandler))))
     {
         using (var client = TestServiceClient.CreateClient(false, TestServiceCommon.ServiceAddress))
         {
             var result = TestServiceClient.RunClient(client, TestHeaderOptions.InsertRequest | TestHeaderOptions.ValidateResponse);
             foreach (var httpResponse in result)
             {
                 TestServiceCommon.ValidateInternalServerErrorResponse(httpResponse, faultDetail);
             }
         }
     }
 }
Esempio n. 12
0
        public static void CustomCredentials()
        {
            var host      = new TestServiceHost();
            var testCreds = new TestServiceCredentials();

            Assert.NotNull(host.Description);
            Assert.NotNull(host.Description.Behaviors);
            host.Description.Behaviors.Add(testCreds);
            var creds = host.Credentials;

            Assert.NotNull(creds);
            Assert.IsType <TestServiceCredentials>(creds);
            // Make sure same instance is returned each time
            Assert.Same(testCreds, host.Credentials);
        }
    /// <summary>
    /// Returns a file system implementation, which is assigned
    /// to the <see cref="TestContext.FileSystem"/> property.
    /// </summary>
    /// <param name="localTestFolder">The temporary test folder that is
    /// used by the context. This is actually just the <see cref="TestContext.LocalTestRoot"/>
    /// reference.</param>
    protected override IFileSystemProvider InitFileSystem(DirectoryInfo localTestFolder)
    {
      ServiceFileSystem = GetServiceProvider();
      var settings = new VfsServiceSettings();

      ServiceHost = new TestServiceHost { Configuration = new TestConfiguration(ServiceFileSystem, settings) };

      ServiceBaseUri = "http://localhost:33456/";
      ServiceHost.Initialize(new[] { ServiceBaseUri }, "/", null);
      ServiceHost.StartListening();

//      //TODO remove debug code
//      ServiceBaseUri = "http://127.0.0.1:56789/";

      return new FileSystemFacade(ServiceBaseUri);
    }
            public async Task GivenNoJobWithName_ItThrowsUnknownJobException()
            {
                // Arrange
                var host = new TestServiceHost();

                host.Initialize();

                var dispatcher = new JobDispatcher(Enumerable.Empty <JobDescription>(), host.Container);
                var invocation = TestHelpers.CreateInvocation(Guid.NewGuid(), "flarg", "test", new Dictionary <string, string>());
                var context    = new InvocationContext(invocation, queue: null);

                // Act/Assert
                var ex = await AssertEx.Throws <UnknownJobException>(() => dispatcher.Dispatch(context));

                Assert.Equal("flarg", ex.JobName);
            }
Esempio n. 15
0
        private IReplyChannel OpenChannel(bool customBinding, out IChannelListener <IReplyChannel> listener)
        {
            var binding = TestServiceHost.CreateBinding(customBinding, new HttpMessageHandlerFactory(typeof(TestHandler)));

            listener = binding.BuildChannelListener <IReplyChannel>(TestServiceCommon.ServiceAddress);
            Assert.IsNotNull(listener);
            listener.Open();
            Assert.AreEqual(CommunicationState.Opened, listener.State);

            var channel = listener.AcceptChannel();

            Assert.IsNotNull(channel);
            channel.Open();
            Assert.AreEqual(CommunicationState.Opened, channel.State);

            return(channel);
        }
Esempio n. 16
0
 private void NoDataServiceTest(bool asynchronousSendEnabled, bool streamed, bool copyHeaderInHandler)
 {
     NoDataServiceTests.CopyHeaderInHandler = copyHeaderInHandler;
     using (var host = TestServiceHost.CreateWebHost <TestService>(asynchronousSendEnabled, false, streamed, new HttpMessageHandlerFactory(typeof(TestHandler))))
     {
         using (var client = TestServiceClient.CreateClient())
         {
             var result = TestServiceClient.RunClient(client, TestHeaderOptions.InsertRequest | TestHeaderOptions.ValidateResponse);
             foreach (var httpResponse in result)
             {
                 Assert.AreEqual(HttpStatusCode.OK, httpResponse.StatusCode);
                 Assert.AreEqual(TestWebServiceBase.HttpReasonPhrase, httpResponse.ReasonPhrase);
                 Assert.AreEqual(0, httpResponse.Content.Headers.ContentLength);
                 Assert.IsNull(httpResponse.Content.Headers.ContentType);
             }
         }
     }
 }
            public async Task GivenAContinuationRequest_ItCallsTheInvokeContinuationMethod()
            {
                // Arrange
                var host = new TestServiceHost();

                host.Initialize();

                var job = new JobDescription("test", typeof(TestAsyncJob));

                var dispatcher = new JobDispatcher(new[] { job }, host.Container);
                var invocation = TestHelpers.CreateInvocation(Guid.NewGuid(), "Test", "test", new Dictionary <string, string>(), isContinuation: true);
                var context    = new InvocationContext(invocation, queue: null);

                // Act
                var result = await dispatcher.Dispatch(context);

                // Assert
                Assert.Equal(ExecutionResult.Completed, result.Result);
            }
Esempio n. 18
0
        private void InitializeServices()
        {
            if (_fileService != null && _fileService.State == CommunicationState.Opened)
            {
                _fileService.CloseService();
            }

            if (_testService != null && _testService.State == CommunicationState.Opened)
            {
                _testService.CloseService();
            }

            // Host the services
            _fileService = new FileServiceHost(9123, UploadsDirectory);
            _fileService.LaunchService();

            _testService = new TestServiceHost(9123, UploadsDirectory);
            _testService.LaunchService();
        }
Esempio n. 19
0
 private void PersistenceTest(bool asynchronousSendEnabled, bool streamed)
 {
     using (var host = TestServiceHost.CreateWebHost <TestService>(asynchronousSendEnabled, false, streamed, new HttpMessageHandlerFactory(typeof(TestHandler))))
     {
         using (var client = TestServiceClient.CreateClient())
         {
             var result = TestServiceClient.RunClient(client, TestHeaderOptions.ValidateResponse);
             foreach (var httpResponse in result)
             {
                 Assert.AreEqual(HttpStatusCode.OK, httpResponse.StatusCode);
                 Assert.AreEqual(TestWebServiceBase.HttpReasonPhrase, httpResponse.ReasonPhrase);
                 Assert.AreEqual("text/plain", httpResponse.Content.Headers.ContentType.MediaType);
                 Assert.AreEqual("utf-8", httpResponse.Content.Headers.ContentType.CharSet);
                 var body = httpResponse.Content.ReadAsString();
                 Assert.AreEqual(body, TestWebServiceBase.HttpResponseContent);
             }
         }
     }
 }
            public async Task GivenAContinuationRequestToANonAsyncJob_ItThrows()
            {
                // Arrange
                var host = new TestServiceHost();

                host.Initialize();

                var job = new JobDescription("test", typeof(TestJob));

                var dispatcher = new JobDispatcher(new[] { job }, host.Container);
                var invocation = TestHelpers.CreateInvocation(Guid.NewGuid(), "Test", "test", new Dictionary <string, string>(), isContinuation: true);
                var context    = new InvocationContext(invocation, queue: null);

                // Act/Assert
                var ex = await AssertEx.Throws <InvalidOperationException>(() => dispatcher.Dispatch(context));

                Assert.Equal(String.Format(
                                 Strings.JobDispatcher_AsyncContinuationOfNonAsyncJob,
                                 job.Name), ex.Message);
            }
Esempio n. 21
0
        static void Main(string[] args)
        {
            var fileServiceHost = new FileServiceHost(9123, @"C:\Uploads");

            fileServiceHost.LaunchService();

            Console.WriteLine("File Server Address: {0}", fileServiceHost.ServiceAddress);
            Console.WriteLine("File Server State: {0}", fileServiceHost.State);

            var testServiceHost = new TestServiceHost(9123, @"C:\Uploads");

            testServiceHost.LaunchService();

            Console.WriteLine("Test Server Address: {0}", testServiceHost.ServiceAddress);
            Console.WriteLine("Test Server State: {0}", testServiceHost.State);

            while (true)
            {
                Thread.Sleep(5000);
            }
        }
Esempio n. 22
0
        public void DataServiceHostServiceRootUriTest()
        {
            // Edit link "../Product(1)" incorrectly produced when base uri is http://service.svc using IDSH
            // Make sure service root URIs always end in '/' when using an IDataServiceHost/IDataServiceHost2
            //
            // Verifies that the service root URI for a IDSH is always terminated in a '/'
            // NOTE: if the service URI would not be properly terminated in a '/', the created edit link in the resulting
            //       entry would be incorrect.
            Uri[] uris = new Uri[]
            {
                new Uri("http://host"),
                new Uri("http://host/a/b"),
                new Uri("http://host/a/b.svc"),
                new Uri("http://host/a/b/c.svc")
            };

            TestUtil.RunCombinations(uris, (uri) =>
            {
                TestServiceHost host = new TestServiceHost(uri)
                {
                    RequestAccept   = "application/atom+xml",
                    RequestPathInfo = "/Customers(0)",
                };

                DataService <CustomDataContext> context = new OpenWebDataService <CustomDataContext>();
                context.AttachHost(host);

                Exception exception = TestUtil.RunCatching(delegate()
                {
                    context.ProcessRequest();
                });

                XmlDocument document = new XmlDocument(TestUtil.TestNameTable);
                host.ResponseStream.Seek(0, SeekOrigin.Begin);
                document.Load(host.ResponseStream);
                UnitTestsUtil.VerifyXPaths(document, "/atom:entry/atom:link[@rel='edit' and @href='Customers(0)']");

                TestUtil.AssertExceptionExpected(exception, false);
            });
        }
Esempio n. 23
0
        public void SerializeResponseBodyAcceptTypeWithCharsetTest()
        {
            // Verifies that the correct handling of 'charset' parameters in accept header media types.
            TestServiceHost host = new TestServiceHost();

            host.RequestPathInfo = "/Customers(0)/Name/$value";
            DataService <CustomDataContext> context = new OpenWebDataService <CustomDataContext>();

            const string TextPlain = "text/plain";
            var          tests     = TestUtil.CreateDictionary <string>(
                TextPlain, TextPlain,
                // valid charset of accept header should not be used for conneg
                TextPlain + ";charset=UTF-8", TextPlain,
                // invalid charset of accept header should not be used for conneg
                TextPlain + ";charset=aabbcc", TextPlain,
                // non-charset parameter should be used for matching
                TextPlain + ";some=value", null,
                // charset and non-charset parameters; non-charset one should be used for matching
                TextPlain + ";charset=utf-8;some=value", null
                );

            TestUtil.RunCombinations(tests, (test) =>
            {
                host.ClearResponse();
                context.AttachHost(host);
                string acceptTypes  = test.Key;
                string result       = test.Value;
                Exception exception = TestUtil.RunCatching(delegate()
                {
                    Trace.WriteLine("Running query with accept type: " + acceptTypes);
                    host.RequestAccept = acceptTypes;
                    context.ProcessRequest();
                });
                TestUtil.AssertExceptionExpected(exception, result == null);
                if (result != null)
                {
                    Assert.AreEqual(result, TestUtil.GetMediaType(host.ResponseContentType));
                }
            });
        }
            public async Task GivenJobWithName_ItInvokesTheJobAndReturnsTheResult()
            {
                // Arrange
                var host = new TestServiceHost();

                host.Initialize();

                var job = new JobDescription("test", typeof(TestJob));

                var dispatcher = new JobDispatcher(new[] { job }, host.Container);
                var invocation = TestHelpers.CreateInvocation(Guid.NewGuid(), "Test", "test", new Dictionary <string, string>());
                var context    = new InvocationContext(invocation, queue: null);
                var expected   = InvocationResult.Completed();

                TestJob.SetTestResult(expected);

                // Act
                var actual = await dispatcher.Dispatch(context);

                // Assert
                Assert.Same(expected, actual);
            }
Esempio n. 25
0
    public void Init()
    {
      ServiceFileSystem = GetServiceProvider();
      ServiceSettings = CustomizeSettings(new VfsServiceSettings());
      
      ServiceHost = new TestServiceHost {Configuration = new TestConfiguration(ServiceFileSystem, ServiceSettings)};

      ServiceBaseUri = "http://localhost:33456/";
      ServiceHost.Initialize(new[] { ServiceBaseUri }, "/", null);
      ServiceHost.StartListening();

//      //TODO remove debug code
//      ServiceBaseUri = "http://127.0.0.1:56789/";

      ClientFileSystem = new FileSystemFacade(ServiceBaseUri);

      //get root folders
      ClientRoot = VirtualFolder.CreateRootFolder(ClientFileSystem);
      ServiceRoot = VirtualFolder.CreateRootFolder(ServiceFileSystem);

      InitInternal();
    }
Esempio n. 26
0
        private void DisposeHandlerTest(bool asynchronousSendEnabled, bool streamed)
        {
            DisposeHandlerTests.handlerList = new List <TestHandler>();
            using (var host = TestServiceHost.CreateWebHost <TestService>(asynchronousSendEnabled, false, streamed, new HttpMessageHandlerFactory(typeof(TestHandler))))
            {
                using (var client = TestServiceClient.CreateClient())
                {
                    var result = TestServiceClient.RunClient(client, TestHeaderOptions.InsertRequest | TestHeaderOptions.ValidateResponse);
                    foreach (var httpResponse in result)
                    {
                        Assert.AreEqual(HttpStatusCode.OK, httpResponse.StatusCode);
                        Assert.AreEqual(TestWebServiceBase.HttpReasonPhrase, httpResponse.ReasonPhrase);
                    }

                    Assert.AreEqual(1, DisposeHandlerTests.handlerList.Count);
                    Assert.IsFalse(DisposeHandlerTests.handlerList[0].IsDisposed);
                }
            }

            Assert.AreEqual(1, DisposeHandlerTests.handlerList.Count);
            Assert.IsTrue(DisposeHandlerTests.handlerList[0].IsDisposed);
        }
Esempio n. 27
0
        public static async Task ServiceHostBaseOpenCloseAbort()
        {
            var host = new TestServiceHost();

            Assert.Equal(CommunicationState.Created, host.State);
            await host.OpenAsync();

            Assert.Equal(CommunicationState.Opened, host.State);
            Assert.True(host.OnOpenAsynCalled);
            await host.CloseAsync();

            Assert.Equal(CommunicationState.Closed, host.State);
            Assert.True(host.OnCloseAsynCalled);
            host.Abort();
            Assert.False(host.OnAbortCalled);
            host = new TestServiceHost();
            await host.OpenAsync();

            Assert.Equal(CommunicationState.Opened, host.State);
            host.Abort();
            Assert.True(host.OnAbortCalled);
            Assert.Equal(CommunicationState.Closed, host.State);
        }
            public TestCacheServerWrapper(TestHost testHost, DistributedCacheServiceArguments arguments)
            {
                string[] commandLineArguments = CreateCommandLine(arguments);

                var hostParameters = HostParameters.FromEnvironment();
                var hostInfo       = new HostInfo(hostParameters.Stamp, hostParameters.Ring, new List <string>());

                var serviceHost = new CacheServiceStartup.ServiceHost(
                    new string[0],
                    arguments.Configuration,
                    hostParameters,
                    new Context(TestGlobal.Logger));

                Host = new TestServiceHost(testHost, serviceHost);

                var _ = arguments.Cancellation.Register(() => Host.StartupCompletedSignal.TrySetCanceled());

                RunInBackground("RunCacheService", async context =>
                {
                    using (var cts = CancellationTokenSource.CreateLinkedTokenSource(context.Token, arguments.Cancellation))
                    {
                        arguments = arguments with
                        {
                            Host         = Host,
                            Cancellation = cts.Token
                        };

                        await DistributedCacheServiceFacade.RunAsync(arguments);

                        Assert.True(cts.IsCancellationRequested, "Cache service task shutdown prematurely");
                    }

                    return(BoolResult.Success);
                },
                                fireAndForget: false);
            }
 public void Setup()
 {
     host =
         new TestServiceHost <TestServiceImplementation, ITestService>(
             Settings.Default.TestServiceAddress);
 }
 public void Setup()
 {
     host =
         new TestServiceHost<TestServiceImplementation, ITestService>(
             Settings.Default.TestServiceAddress);
 }
Esempio n. 31
0
        public void SerializeResponseBodyAcceptTypeTest()
        {
            // Verifies that the correct Content-Type is selected at serialization time.
            TestServiceHost host = new TestServiceHost();

            host.RequestPathInfo = "/Customers";
            DataService <CustomDataContext> context = new OpenWebDataService <CustomDataContext>();

            const string AtomXml     = "application/atom+xml";
            const string AtomXmlFeed = "application/atom+xml;type=feed";
            const string charsetUtf8 = ";charset=utf-8";
            const string JsonLight   = "application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false";

            var testCases = new[]
            {
                // Success cases for all versions
                new { AcceptHeaderString = "application/atom+xml, application/json", Expectation = JsonLight + charsetUtf8 },
                new { AcceptHeaderString = "application/atom+xml, application/json;odata.metadata=minimal", Expectation = JsonLight + charsetUtf8 },
                new { AcceptHeaderString = "application/json, application/atom+xml", Expectation = JsonLight + charsetUtf8 },
                new { AcceptHeaderString = (string)null, Expectation = JsonLight + charsetUtf8 },
                new { AcceptHeaderString = "", Expectation = JsonLight + charsetUtf8 },
                new { AcceptHeaderString = " ", Expectation = JsonLight + charsetUtf8 },
                new { AcceptHeaderString = "*/*", Expectation = JsonLight + charsetUtf8 },
                new { AcceptHeaderString = AtomXml, Expectation = AtomXmlFeed + charsetUtf8 },
                new { AcceptHeaderString = "application/json", Expectation = JsonLight + charsetUtf8 },
                new { AcceptHeaderString = "application/xml,application/json;q=0.8", Expectation = JsonLight + charsetUtf8 },
                new { AcceptHeaderString = AtomXml + ",application/json;q=0.8", Expectation = AtomXmlFeed + charsetUtf8 },
                new { AcceptHeaderString = "application/json," + AtomXml + ";q=0.8", Expectation = JsonLight + charsetUtf8 },
                new { AcceptHeaderString = "text/xml,*/*", Expectation = JsonLight + charsetUtf8 },
                new { AcceptHeaderString = "application/xml,*/*", Expectation = JsonLight + charsetUtf8 },

                // Error cases for all versions
                new { AcceptHeaderString = "text/xml", Expectation = (string)null },
                new { AcceptHeaderString = "application/xml", Expectation = (string)null },
                new { AcceptHeaderString = "application/json;foo=bar", Expectation = (string)null },
                new { AcceptHeaderString = "application/json;odata.metadata=bla", Expectation = (string)null },
                new { AcceptHeaderString = "application/json;foo=bar", Expectation = (string)null },

                // Cases where V2 and V3 expected behaviors differ
                new { AcceptHeaderString = "application/json", Expectation = JsonLight + charsetUtf8 },
                new { AcceptHeaderString = "application/json;odata.metadata=minimal", Expectation = JsonLight + charsetUtf8 },
                new { AcceptHeaderString = "application/json, application/json;odata.metadata=minimal", Expectation = JsonLight + charsetUtf8 },
            };

            TestUtil.RunCombinations(
                testCases,
                new string[] { "4.0" },
                (testCase, requestMaxVersion) =>
            {
                host.ClearResponse();
                context.AttachHost(host);
                string acceptTypes = testCase.AcceptHeaderString;
                string result      = testCase.Expectation;

                Exception exception = TestUtil.RunCatching(delegate()
                {
                    Trace.WriteLine("Running query with accept type: " + acceptTypes);
                    host.RequestAccept     = acceptTypes;
                    host.RequestMaxVersion = requestMaxVersion;
                    context.ProcessRequest();
                });
                TestUtil.AssertExceptionExpected(exception, result == null);
                if (result != null)
                {
                    Assert.AreEqual(result, host.ResponseContentType);
                }
            });
        }