Пример #1
1
        public void Soap11ClientIssuesAValidRequest()
        {
            var mockMessageHandler = new MockHttpMessageHandler();
            mockMessageHandler
                .Expect(HttpMethod.Post, FakeEndpoint)
                .With(req => req.Content.Headers.ContentType.MediaType == Soap11MediaType)
                .With(req => req.Content.Headers.ContentType.CharSet == SoapCharSet)
                .Respond(HttpStatusCode.OK);

            Task<HttpResponseMessage> result;
            using (var sut = new SoapClient(() => new HttpClient(mockMessageHandler)))
            {
                result = sut.PostAsync(FakeEndpoint, _fakeBody);
            }
            result.ShouldBeType(typeof(Task<HttpResponseMessage>));
            mockMessageHandler.VerifyNoOutstandingExpectation();
        }
        private MockHttpMessageHandler getEmptyHandler()
        {
            var mockHttp = new MockHttpMessageHandler();
            // List indexes
            mockHttp.When(HttpMethod.Get, "*/1/indexes/").Respond("application/json", "{\"items\":[]}");

            //Query an index
            mockHttp.When(HttpMethod.Get, "*/1/indexes/{indexName}").Respond(HttpStatusCode.OK, "application/json", "{\"hits\":[],\"page\":0,\"nbHits\":0,\"nbPages\":0,\"ProcessingTimeMS\":1,\"query\":\"\",\"params\":\"\"}");
            mockHttp.When(HttpMethod.Post, "*/1/indexes/{indexName}/query").Respond(HttpStatusCode.OK, "application/json", "{\"hits\":[],\"page\":0,\"nbHits\":0,\"nbPages\":0,\"ProcessingTimeMS\":1,\"query\":\"\",\"params\":\"\"}");

            // Multiple queries
            mockHttp.When(HttpMethod.Get, "*/1/indexes/*/query").Respond(HttpStatusCode.OK, "application/json", "{\"results\":[]}");

            // Delete index
            mockHttp.When(HttpMethod.Delete, "*/1/indexes/{indexName}").Respond(HttpStatusCode.OK, "application/json", "{\"deletedAt\":\"2013-01-18T15:33:13.556Z\",\"taskID\":1}");

            // Clear index
            mockHttp.When(HttpMethod.Post, "*/1/indexes/{indexName}/clear").Respond(HttpStatusCode.OK, "application/json", "{\"updatedAt\":\"2013-01-18T15:33:13.556Z\",\"taskID\":1}");

            //Add object in an index without objectID
            mockHttp.When(HttpMethod.Post, "*/1/indexes/{indexName}").Respond(HttpStatusCode.Created, "application/json", "{\"createdAt\":\"2013-01-18T15:33:13.556Z\",\"taskID\":1,\"objectID\":\"1\"}");

            //Add object in an index with objectID
            mockHttp.When(HttpMethod.Put, "*/1/indexes/{indexName}/{objectID}").Respond(HttpStatusCode.Created, "application/json", "{\"createdAt\":\"2013-01-18T15:33:13.556Z\",\"taskID\":1,\"objectID\":\"1\"}");

            //Partially update an object in an index
            mockHttp.When(HttpMethod.Post, "*/1/indexes/{indexName}/{objectID}/partial").Respond(HttpStatusCode.OK, "application/json", "{\"updatedAt\":\"2013-01-18T15:33:13.556Z\",\"taskID\":1,\"objectID\":\"1\"}");

            //get an object in an index by objectID
            mockHttp.When(HttpMethod.Get, "*/1/indexes/{indexName}/{objectID}").Respond(HttpStatusCode.OK, "application/json", "{}");

            //get several objects in an index by objectID
            mockHttp.When(HttpMethod.Post, "*/1/indexes/*/objects").Respond(HttpStatusCode.OK, "application/json", "{\"results\":[]}");

            //delete an object in an index by objectID
            mockHttp.When(HttpMethod.Delete, "*/1/indexes/{indexName}/{objectID}").Respond(HttpStatusCode.OK, "application/json", "{\"deletedAt\":\"2013-01-18T15:33:13.556Z\",\"taskID\":1}");

            //batch write operations
            mockHttp.When(HttpMethod.Post, "*/1/indexes/{indexName}/batch").Respond(HttpStatusCode.OK, "application/json", "{\"taskID\":1,\"objectIDs\":[]}");

            //Get index settings
            mockHttp.When(HttpMethod.Get, "*/1/indexes/{indexName}/settings").Respond(HttpStatusCode.OK, "application/json", "{\"minWordSizefor1Typo\": 3,\"minWordSizefor2Typos\": 7,\"hitsPerPage\": 20,\"attributesToIndex\": null,\"attributesToRetrieve\": null,\"attributesToSnippet\": null,\"attributesToHighlight\": null,\"ranking\": [\"typo\",\"geo\",\"proximity\",\"attribute\",\"custom\"],\"customRanking\": null,\"separatorsToIndex\": \"\",\"queryType\": \"prefixAll\"}");

            //Browse index content
            mockHttp.When(HttpMethod.Get, "*/1/indexes/{indexName}/browse").Respond(HttpStatusCode.OK, "application/json", "{\"hits\":[],\"page\":0,\"nbHits\":0,\"nbPages\":0,\"ProcessingTimeMS\":1,\"query\":\"\",\"params\":\"\"}");

            //Change index settings
            mockHttp.When(HttpMethod.Put, "*/1/indexes/{indexName}/settings").Respond(HttpStatusCode.OK, "application/json", "{\"updatedAt\":\"2013-01-18T15:33:13.556Z\",\"taskID\":1}");

            //Copy/Move an Index
            mockHttp.When(HttpMethod.Post, "*/1/indexes/{indexName}/operation").Respond(HttpStatusCode.OK, "application/json", "{\"updatedAt\":\"2013-01-18T15:33:13.556Z\",\"taskID\":1}");

            //Get task status
            mockHttp.When(HttpMethod.Get, "*/1/indexes/{indexName}/task/{taskID}").Respond(HttpStatusCode.OK, "application/json", "{\"status\":\"published\",\"pendingTask\":false}");

            //Add index specific API key
            mockHttp.When(HttpMethod.Post, "*/1/indexes/{indexName}/keys").Respond(HttpStatusCode.Created, "application/json", "{\"key\": \"107da8d0afc2d225ff9a7548caaf599f\",\"createdAt\":\"2013-01-18T15:33:13.556Z\"}");

            //List index specific API Keys
            mockHttp.When(HttpMethod.Get, "*/1/indexes/{indexName}/keys").Respond(HttpStatusCode.OK, "application/json", "{\"keys\":[]}");

            //List index specific API Keys for all indexes
            mockHttp.When(HttpMethod.Get, "*/1/indexes/*/keys").Respond(HttpStatusCode.OK, "application/json", "{\"keys\":[]}");

            //Get the rights of an index specific API key
            mockHttp.When(HttpMethod.Get, "*/1/indexes/{indexName}/keys/{key}").Respond(HttpStatusCode.OK, "application/json", "{\"value\": \"107da8d0afc2d225ff9a7548caaf599f\",\"acl\": [\"search\"],\"validity\": 0}");

            //Delete index specific API key
            mockHttp.When(HttpMethod.Delete, "*/1/indexes/{indexName}/keys/{key}").Respond(HttpStatusCode.OK, "application/json", "{\"deletedAt\":\"2013-01-18T15:33:13.556Z\"}");

            //Add a global API key
            mockHttp.When(HttpMethod.Post, "*/1/keys").Respond(HttpStatusCode.Created, "application/json", "{\"key\": \"107da8d0afc2d225ff9a7548caaf599f\",\"createdAt\":\"2013-01-18T15:33:13.556Z\"}");

            //List global API keys
            mockHttp.When(HttpMethod.Get, "*/1/keys").Respond(HttpStatusCode.OK, "application/json", "{\"keys\":[]}");

            //Get the rights of a global API key
            mockHttp.When(HttpMethod.Get, "*/1/keys/{key}").Respond(HttpStatusCode.OK, "application/json", "{\"value\": \"107da8d0afc2d225ff9a7548caaf599f\",\"acl\": [\"search\"],\"validity\": 0}");

            //Delete a global API key
            mockHttp.When(HttpMethod.Delete, "*/1/keys/{key}").Respond(HttpStatusCode.OK, "application/json", "{\"deletedAt\":\"2013-01-18T15:33:13.556Z\"}");

            //Get last logs
            mockHttp.When(HttpMethod.Get, "*/1/logs").Respond(HttpStatusCode.OK, "application/json", "{\"logs\":[]}");
            
            mockHttp.Fallback.WithAny().Respond(HttpStatusCode.BadRequest);

            return mockHttp;
        }
        private WebServiceClient CreateClient(string type, string ipAddress = "1.2.3.4",
            HttpStatusCode status = HttpStatusCode.OK, string contentType = null, string content = "")
        {
            var service = type.Replace("Async", "");
            if (contentType == null)
            {
                contentType = $"application/vnd.maxmind.com-{service}+json";
            }
            var stringContent = new StringContent(content);
            stringContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            stringContent.Headers.Add("Content-Length", content.Length.ToString());
            var message = new HttpResponseMessage(status)
            {
                Content = stringContent
            };

            // HttpClient mock
            var uri = new Uri($"https://geoip.maxmind.com/geoip/v2.1/{service}/{ipAddress}");
            var mockHttp = new MockHttpMessageHandler();
            mockHttp.When(HttpMethod.Get, uri.ToString())
                .WithHeaders("Accept", "application/json")
                .Respond(message);

            // HttpWebRequest mock
            var contentsBytes = Encoding.UTF8.GetBytes(content);
            var responseStream = new MemoryStream(contentsBytes);

            var syncWebRequest = new MockSyncClient(new Response(uri, status, contentType, responseStream));

            return new WebServiceClient(6, "0123456789", new List<string> { "en" },
                httpMessageHandler: mockHttp, syncWebRequest: syncWebRequest);
        }
Пример #4
0
        public async Task GetMetadataAsync_Returns_Expected_Cloud_Metadata_When_No_Zone()
        {
            var stubMetadata = new
            {
                location          = "westus2",
                name              = "dotnet-agent-test",
                resourceGroupName = "dotnet-agent-testing",
                subscriptionId    = "7657426d-c4c3-44ac-88a2-3b2cd59e6dba",
                vmId              = "e11ebedc-019d-427f-84dd-56cd4388d3a8",
                vmSize            = "Standard_D2s_v3"
            };

            var handler = new MockHttpMessageHandler();

            handler.When(AzureCloudMetadataProvider.MetadataUri)
            .Respond("application/json", JsonConvert.SerializeObject(stubMetadata));

            var provider = new AzureCloudMetadataProvider(new NoopLogger(), handler);

            var metadata = await provider.GetMetadataAsync();

            metadata.Should().NotBeNull();
            metadata.Account.Should().NotBeNull();
            metadata.Account.Id.Should().Be(stubMetadata.subscriptionId);
            metadata.Provider.Should().Be(provider.Provider);
            metadata.Instance.Should().NotBeNull();
            metadata.Instance.Id.Should().Be(stubMetadata.vmId);
            metadata.Instance.Name.Should().Be(stubMetadata.name);
            metadata.Project.Should().NotBeNull();
            metadata.Project.Name.Should().Be(stubMetadata.resourceGroupName);
            metadata.Region.Should().Be(stubMetadata.location);
            metadata.Machine.Should().NotBeNull();
            metadata.Machine.Type.Should().Be(stubMetadata.vmSize);
            metadata.AvailabilityZone.Should().BeNull();
        }
Пример #5
0
 public CqrsGatewayTests()
 {
     _mockHttp = new MockHttpMessageHandler();
     _httpClient = new HttpClient(_mockHttp);
     _httpClient.BaseAddress = new Uri(_protocolAndDomain);
     _gateway = new CqrsGateway<FakeModel>(_httpClient);
 }
Пример #6
0
		public void SetUp()
		{
			_postsParser = Substitute.For<IPostsParser> ();

			_httpMessageHandler = new MockHttpMessageHandler ();

			_getPostsCommand = new GetPostsCommand (_postsParser, _httpMessageHandler);
		}
 public void init()
 {
     mockHttp = new MockHttpMessageHandler();
     mockHttp.When("http://10.0.0.44:8080/*")
             .Respond("application/json", "6");
     client = new HttpClient(mockHttp);
     client.BaseAddress = baseUri;
     koerpersteuerung = new Koerpersteuerung(client);
 }
        public void Respond_HttpContent_Unique()
        {
            var mockHttp = new MockHttpMessageHandler();

            var mockedRequest = mockHttp.When("/path");
            mockedRequest.Respond(req => new StringContent("test", Encoding.UTF8, "text/plain"));

            var contentA = mockedRequest.SendAsync(request, CancellationToken.None).Result.Content;
            var contentB = mockedRequest.SendAsync(request, CancellationToken.None).Result.Content;

            Assert.NotSame(contentA, contentB);
        }
        public void Respond_HttpClient()
        {
            var passthroughHandler = new MockHttpMessageHandler();
            passthroughHandler.Fallback.Respond(new StringContent("test", Encoding.UTF8, "text/plain"));

            var passthroughClient = new HttpClient(passthroughHandler);

            var response = Test(r => r.Respond(passthroughClient));

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("text/plain", response.Content.Headers.ContentType.MediaType);
            Assert.Equal("test", response.Content.ReadAsStringAsync().Result);
        }
        public void Setup()
        {
            providerMock = new Mock<IHttpClientProvider>();
            mockHttp = new MockHttpMessageHandler();

            var credentials = new MeliCredentials(MeliSite.Argentina, 123456, "secret");

            service = new MeliApiService
                      {
                          HttpClientProvider = providerMock.Object,
                          Credentials = credentials
                      };

            providerMock.Setup(call => call.Create(It.IsAny<bool>()))
                        .Returns(new HttpClient(mockHttp));
        }
Пример #11
0
        public void Soap11ClientIncludesSoapActionParameter()
        {
            var mockMessageHandler = new MockHttpMessageHandler();
            mockMessageHandler
                .Expect(HttpMethod.Post, FakeEndpoint)
                .With(req => req.Content.Headers.Single(h => h.Key == "SOAPAction").Value.Single() == FakeAction)
                .Respond(HttpStatusCode.OK);

            Task<HttpResponseMessage> result;
            using (var sut = new SoapClient(() => new HttpClient(mockMessageHandler)))
            {
                result = sut.PostAsync(FakeEndpoint, _fakeBody, action: FakeAction);
            }
            result.ShouldBeType(typeof(Task<HttpResponseMessage>));
            mockMessageHandler.VerifyNoOutstandingExpectation();
        }
Пример #12
0
        public static async void TestAsyncTileFetcher()
        {
            // arrange
            var tileSource = KnownTileSources.Create();
            var mockHttp = new MockHttpMessageHandler();
            mockHttp.When("http://*").Respond("image/png", new MemoryStream());
            var httpClient = new HttpClient(mockHttp);
            var range = tileSource.Schema.GetTileInfos(tileSource.Schema.Extent, "3");
            var timeStart = DateTime.Now;

            // act
            var tiles = await tileSource.GetTilesAsync(httpClient, range);

            // assert
            Console.WriteLine("Durations: {0:0} milliseconds", DateTime.Now.Subtract(timeStart).TotalMilliseconds);
            Assert.AreEqual(tiles.Count(), 64);
        }
        public void TestActionNugetSelectById()
        {
            var mockHttp = new MockHttpMessageHandler();
            // Setup a respond for the user api (including a wildcard in the URL)
            mockHttp.When("http://localhost:55893/api/")
                    .Respond("application/json", GenerateJsonArrayofSecurityMf()); // Respond with JSON

            // Inject the handler or client into your application code
            using (var client = new HttpClient(mockHttp))
            {
                System.Uri uri = new System.Uri("http://localhost:55893/api/");
                client.BaseAddress = uri;
                var controller = new SecuritiesMfMvcController(client);
                var result = controller.Select(2155);
                Assert.IsNotNull(result);
            }
        }
        public void Should_Update_Logger_That_Is_ILogLevelSwitchable()
        {
            var logLevel   = LogLevel.Trace;
            var testLogger = new ConsoleLogger(logLevel);

            var configSnapshotFromReader = new MockConfigSnapshot(testLogger, logLevel: "Trace");
            var configStore = new ConfigStore(configSnapshotFromReader, testLogger);
            var service     = Service.GetDefaultService(configSnapshotFromReader, testLogger);

            var waitHandle = new ManualResetEvent(false);
            var handler    = new MockHttpMessageHandler();
            var configUrl  = BackendCommUtils.ApmServerEndpoints
                             .BuildGetConfigAbsoluteUrl(configSnapshotFromReader.ServerUrl, service);

            handler.When(configUrl.AbsoluteUri)
            .Respond(_ =>
            {
                waitHandle.Set();
                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Headers = { ETag = new EntityTagHeaderValue("\"etag\"") },
                    Content = new StringContent("{ \"log_level\": \"error\" }", Encoding.UTF8)
                });
            });

            var centralConfigFetcher = new CentralConfigFetcher(testLogger, configStore, service, handler);

            using var agent = new ApmAgent(new TestAgentComponents(testLogger,
                                                                   centralConfigFetcher: centralConfigFetcher,
                                                                   payloadSender: new NoopPayloadSender()));

            centralConfigFetcher.IsRunning.Should().BeTrue();
            waitHandle.WaitOne();

            // wait up to 60 seconds for the log level to change. Change can often be slower in CI
            var count = 0;

            while (count < 60 && testLogger.LogLevelSwitch.Level == logLevel)
            {
                count++;
                Thread.Sleep(TimeSpan.FromSeconds(1));
            }

            testLogger.LogLevelSwitch.Level.Should().Be(LogLevel.Error);
        }
Пример #15
0
        public async Task GetMetadataAsync_Returns_Expected_Cloud_Metadata()
        {
            var stubMetadata = new
            {
                accountId               = "946960629917",
                architecture            = "x86_64",
                availabilityZone        = "us-east-2a",
                billingProducts         = (string)null,
                devpayProductCodes      = (string)null,
                marketplaceProductCodes = (string)null,
                imageId      = "ami-07c1207a9d40bc3bd",
                instanceId   = "i-0ae894a7c1c4f2a75",
                instanceType = "t2.medium",
                kernelId     = (string)null,
                pendingTime  = "2020-06-12T17:46:09Z",
                privateIp    = "172.31.0.212",
                ramdiskId    = (string)null,
                region       = "us-east-2",
                version      = "2017-09-30"
            };

            var handler = new MockHttpMessageHandler();

            handler.When(AwsCloudMetadataProvider.TokenUri)
            .Respond("application/json", "aws-token");
            handler.When(AwsCloudMetadataProvider.MetadataUri)
            .Respond("application/json", JsonConvert.SerializeObject(stubMetadata));

            var provider = new AwsCloudMetadataProvider(new NoopLogger(), handler);

            var metadata = await provider.GetMetadataAsync();

            metadata.Should().NotBeNull();
            metadata.Account.Should().NotBeNull();
            metadata.Account.Id.Should().Be(stubMetadata.accountId);
            metadata.Provider.Should().Be(provider.Provider);
            metadata.Instance.Should().NotBeNull();
            metadata.Instance.Id.Should().Be(stubMetadata.instanceId);
            metadata.Project.Should().BeNull();
            metadata.AvailabilityZone.Should().Be("us-east-2a");
            metadata.Region.Should().Be(stubMetadata.region);
            metadata.Machine.Should().NotBeNull();
            metadata.Machine.Type.Should().Be(stubMetadata.instanceType);
        }
        public void Should_Sanitize_HttpRequestMessage_In_Log()
        {
            var testLogger  = new TestLogger(LogLevel.Trace);
            var secretToken = "secretToken";
            var serverUrl   = "http://*****:*****@localhost:8200";

            var configSnapshotFromReader = new MockConfiguration(testLogger, logLevel: "Trace", serverUrl: serverUrl, secretToken: secretToken);
            var configStore = new ConfigurationStore(configSnapshotFromReader, testLogger);
            var service     = Service.GetDefaultService(configSnapshotFromReader, testLogger);

            var waitHandle = new ManualResetEvent(false);
            var handler    = new MockHttpMessageHandler();
            var configUrl  = BackendCommUtils.ApmServerEndpoints
                             .BuildGetConfigAbsoluteUrl(configSnapshotFromReader.ServerUrl, service);

            handler.When(configUrl.AbsoluteUri)
            .Respond(_ =>
            {
                waitHandle.Set();
                return(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));
            });

            var centralConfigFetcher = new CentralConfigurationFetcher(testLogger, configStore, service, handler);

            waitHandle.WaitOne();

            var count = 0;

            while (!testLogger.Log.Contains("Exception was thrown while fetching configuration from APM Server and parsing it.") &&
                   count < 10)
            {
                Thread.Sleep(500);
                count++;
            }

            testLogger.Log
            .Should().Contain($"Authorization: {Consts.Redacted}").And.NotContain(secretToken)
            .And.NotContain(serverUrl);
        }
        public void Should_Update_Logger_That_Is_ILogLevelSwitchable()
        {
            var testLogger = new ConsoleLogger(LogLevel.Trace);

            var environmentConfigurationReader = new EnvironmentConfigurationReader();
            var configSnapshotFromReader       = new ConfigSnapshotFromReader(environmentConfigurationReader, "local");
            var configStore = new ConfigStore(configSnapshotFromReader, testLogger);
            var service     = Service.GetDefaultService(environmentConfigurationReader, testLogger);

            var waitHandle = new ManualResetEvent(false);
            var handler    = new MockHttpMessageHandler();
            var configUrl  = BackendCommUtils.ApmServerEndpoints
                             .BuildGetConfigAbsoluteUrl(environmentConfigurationReader.ServerUrl, service);

            handler.When(configUrl.AbsoluteUri)
            .Respond(_ =>
            {
                waitHandle.Set();
                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Headers = { ETag = new EntityTagHeaderValue("\"etag\"") },
                    Content = new StringContent("{ \"log_level\": \"error\" }", Encoding.UTF8)
                });
            });

            var centralConfigFetcher = new CentralConfigFetcher(testLogger, configStore, service, handler);

            using (var agent = new ApmAgent(new TestAgentComponents(testLogger,
                                                                    centralConfigFetcher: centralConfigFetcher,
                                                                    payloadSender: new NoopPayloadSender())))
            {
                centralConfigFetcher.IsRunning.Should().BeTrue();
                waitHandle.WaitOne();
                Thread.Sleep(TimeSpan.FromSeconds(3));
            }

            testLogger.LogLevelSwitch.Level.Should().Be(LogLevel.Error);
        }
Пример #18
0
        public async Task GetMetadataAsync_Returns_Expected_Cloud_Metadata()
        {
            var stubMetadata = new
            {
                instance = new
                {
                    id          = 4306570268266786072,
                    machineType = "projects/513326162531/machineTypes/n1-standard-1",
                    name        = "dotnet-agent-test",
                    zone        = "projects/513326162531/zones/us-west3-a"
                },
                project = new { numericProjectId = 513326162531, projectId = "elastic-apm" }
            };

            var handler = new MockHttpMessageHandler();

            handler.When(GcpCloudMetadataProvider.MetadataUri)
            .Respond("application/json", JsonConvert.SerializeObject(stubMetadata));

            var provider = new GcpCloudMetadataProvider(new NoopLogger(), handler);

            var metadata = await provider.GetMetadataAsync();

            metadata.Should().NotBeNull();
            metadata.Provider.Should().Be(provider.Provider);
            metadata.Instance.Should().NotBeNull();
            metadata.Instance.Id.Should().Be(stubMetadata.instance.id.ToString());
            metadata.Instance.Name.Should().Be(stubMetadata.instance.name);
            metadata.Project.Should().NotBeNull();
            metadata.Project.Id.Should().Be(stubMetadata.project.numericProjectId.ToString());
            metadata.Project.Name.Should().Be(stubMetadata.project.projectId);
            metadata.AvailabilityZone.Should().Be("us-west3-a");
            metadata.Region.Should().Be("us-west3");
            metadata.Machine.Should().NotBeNull();
            metadata.Machine.Type.Should().Be("n1-standard-1");
        }
Пример #19
0
 public virtual void SetUp()
 {
     EntryEndpoint = new MockEntryEndpoint(Mock = new SubMockHttpMessageHandler());
 }
Пример #20
0
        public void Init()
        {
            _mockHttp = new MockHttpMessageHandler();
            var client = new HttpClient(_mockHttp);

            string jsonResponse = string.Format("{{'response': 'OK', 'version': '{0}'}}", CAPI.Version);

            _mockHttp.When(_testUrl + "info")
                .WithQueryString(string.Format("clientVersion={0}", CAPI.Version))
                .Respond("applciation/json", jsonResponse);

            _rosetteApi = new CAPI("userkey", null, 1, client);
        }
        private WebServiceClient CreateClient(string service, HttpStatusCode status, string contentType,
            string responseContent)
        {
            StringContent content = new StringContent(responseContent);
            content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            content.Headers.Add("Content-Length", responseContent.Length.ToString());
            HttpResponseMessage message = new HttpResponseMessage(status)
            {
                Content = content
            };
            var mockHttp = new MockHttpMessageHandler();
            mockHttp.When(HttpMethod.Post, $"https://minfraud.maxmind.com/minfraud/v2.0/{service}")
                .WithHeaders("Accept", "application/json")
                .With(request => VerifyRequestFor(service, request))
                .Respond(message);

            return new WebServiceClient(6, "0123456789", httpMessageHandler: mockHttp);
        }
        public void Respond_Stream_Reread_If_Possible()
        {
            var mockHttp = new MockHttpMessageHandler();

            var mockedRequest = mockHttp.When("/path");
            mockedRequest.Respond("text/plain", new MemoryStream(Encoding.UTF8.GetBytes("test")));

            var contentA = mockedRequest.SendAsync(request, CancellationToken.None).Result.Content.ReadAsStringAsync().Result;
            var contentB = mockedRequest.SendAsync(request, CancellationToken.None).Result.Content.ReadAsStringAsync().Result;

            Assert.NotSame(contentA, contentB);
        }
        public void Respond_String_Unique()
        {
            var mockHttp = new MockHttpMessageHandler();

            var mockedRequest = mockHttp.When("/path");
            mockedRequest.Respond("application/json", "{\"test\":\"value\"}");

            var contentA = mockedRequest.SendAsync(request, CancellationToken.None).Result.Content;
            var contentB = mockedRequest.SendAsync(request, CancellationToken.None).Result.Content;

            Assert.NotSame(contentA, contentB);
        }
Пример #24
0
        public void Init()
        {
            // Create a temporary file for use with file testing
            _tmpFile = Path.GetTempFileName();
            StreamWriter sw = File.AppendText(_tmpFile);
            sw.WriteLine("Rosette API Unit Test.  This file is used for testing file operations.");
            sw.Flush();
            sw.Close();
            _mockHttp = new MockHttpMessageHandler();
            var client = new HttpClient(_mockHttp);

            string jsonResponse = string.Format("{{'response': 'OK', 'version': '{0}'}}", CAPI.Version);

            _mockHttp.When(_testUrl + "info")
                .WithQueryString(string.Format("clientVersion={0}", CAPI.Version))
                .Respond("applciation/json", jsonResponse);

            _rosetteApi = new CAPI("userkey", null, 1, client);
        }
        private HttpResponseMessage Test(Action<MockedRequest> respond)
        {
            var mockHttp = new MockHttpMessageHandler();

            var mockedRequest = mockHttp.When("/path");
            respond(mockedRequest);

            return mockedRequest.SendAsync(request, CancellationToken.None).Result;
        }