Ejemplo n.º 1
0
        public async Task HummClient_CreateKey_SetsDeviceKey_On_Success()
        {
            int requestCount = 0;
            var handler      = new MockHttpHandler
                               (
                (clientRequest) =>
            {
                requestCount++;
                if (requestCount <= 1)
                {
                    return(GetSuccessfulCreateKeyResponse());
                }

                return(GetSuccessfulInviteResponse());
            }
                               );

            var client = CreateMockedClient(handler);

            var response = await client.CreateKeyAsync(new CreateKeyRequest()
            {
                DeviceToken = "ABC123", PosVendor = "Yort", OperatorId = "Yort", AutoUpdateClientToken = true
            });

            //Confirm key changed by making another call
            //that needs the returned key to gen valid sig
            var request = new InviteRequest()
            {
                MobileNumber = "0400000", PurchaseAmount = 10.01M, OperatorId = "Automated"
            };
            var response2 = await client.InviteAsync(request);

            Assert.AreEqual(RequestStates.Success, response.Status);
        }
Ejemplo n.º 2
0
        public async Task SurrenderAsyncTest(HttpStatusCode status, bool success = true, char expected = 'e', GameStatus gameStatus = GameStatus.Lost)
        {
            MockHttpHandler handler = new MockHttpHandler();

            handler.SetHttpStatus(status);
            char[,] map = new char[10, 10];
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    map[i, j] = 'u';
                }
            }
            map[0, 0] = 'e';
            var result = new MineResult {
                map = map, status = GameStatus.Lost, success = true, turn = true
            };

            handler.SetReturnObj(result);
            ApiHandler.Instance.SetHandler(handler);
            result = await ApiHandler.Instance.SurrenderAsync();

            Assert.AreEqual(success, result.success);
            Assert.AreEqual(expected, result.map[0, 0]);
            Assert.AreEqual(gameStatus, result.status);
        }
        public async Task Client_RequestsStoryFromCache_PriorToMakingHNCall()
        {
            // Arrange
            object cacheOutput;

            var requestedStory = new Story();

            MockCacheClient.Setup(client => client.CreateEntry(It.IsAny <object>()))
            .Returns(Mock.Of <ICacheEntry>);

            MockHttpHandler.Protected().Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(),
                                                                            ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
            });

            var httpClient = new HttpClient(MockHttpHandler.Object);

            var storyClient = new StoryClient(httpClient, MockCacheClient.Object, MockLoggingClient.Object);

            // Act
            await storyClient.GetStoryById(requestedStory.id);

            // Assert
            MockCacheClient.Verify(call => call.TryGetValue(It.IsAny <object>(), out cacheOutput), Times.Once);
        }
Ejemplo n.º 4
0
        public void UpdatePropertiesTest()
        {
            var url     = String.Join("/", new string[] { urlPrefix1, layer1, "data" });
            var handler = new MockHttpHandler(url, "POST", (req, res, param) =>
            {
                var result = new RestResult();
                var form   = req.GetFormData();
                if (form.ContainsKey("condition") && form.ContainsKey("data"))
                {
                    result.Success = true;
                }
                return(JsonConvert.SerializeObject(result));
            });

            mockServer.AddRequestHandler(handler);

            try
            {
                var db    = new MapDB(db1);
                var layer = new FeatureLayer(layer1, db);
                layer.UpdateProperties("", null);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Ejemplo n.º 5
0
        public void CountTest()
        {
            var expected = 3;

            var url     = String.Join("/", new string[] { urlPrefix1, layer1, "data" });
            var handler = new MockHttpHandler(url, "POST", (req, res, param) =>
            {
                var result     = new RestResult();
                result.Success = true;
                result.Data    = expected;
                return(JsonConvert.SerializeObject(result));
            });

            mockServer.AddRequestHandler(handler);

            try
            {
                var db     = new MapDB(db1);
                var layer  = new FeatureLayer(layer1, db);
                var actual = layer.Count(null);
                Assert.AreEqual(expected, actual);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Ejemplo n.º 6
0
        public void RemoveAllTest()
        {
            var url     = String.Join("/", new string[] { urlPrefix1, layer1, "data" });
            var handler = new MockHttpHandler(url, "POST", (req, res, param) =>
            {
                var result = new RestResult();
                if (param["op"] == "removeAll")
                {
                    result.Success = true;
                }
                return(JsonConvert.SerializeObject(result));
            });

            mockServer.AddRequestHandler(handler);

            try
            {
                var db    = new MapDB(db1);
                var layer = new FeatureLayer(layer1, db);
                layer.Remove();
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Ejemplo n.º 7
0
        public void GetLayerFieldsTest()
        {
            var expected = new List <LayerField>()
            {
                new LayerField()
                {
                    FieldName = "fieldName",
                    DataType  = "BLOB",
                    FieldSize = 600
                }
            };

            var url     = String.Join("/", new string[] { urlPrefix1, layer1, "fields" });
            var handler = new MockHttpHandler(url, "GET", (req, res, param) =>
            {
                var result     = new RestResult();
                result.Success = true;
                result.Data    = JsonConvert.SerializeObject(expected);
                return(JsonConvert.SerializeObject(result));
            });

            mockServer.AddRequestHandler(handler);

            try
            {
                var db     = new MapDB(db1);
                var layer  = new FeatureLayer(layer1, db);
                var actual = layer.GetLayerFields();
                Assert.AreEqual <LayerField>(expected[0], actual[0]);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Ejemplo n.º 8
0
        public async Task HummClient_Throws_On_NonSuccess_Response()
        {
            var handler = new MockHttpHandler
                          (
                (clientRequest) =>
            {
                return(Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)));
            }
                          );

            var config = new HummClientConfiguration()
            {
                BaseApiUrl = new Uri("https://integration-pos.shophumm.com.au/webapi/v1/Test/"),
                MerchantId = "30299999",
                DeviceId   = "d555",
                PosVersion = "1.0",
                DeviceKey  = "1234567890",
                HttpClient = new HttpClient(handler)
            };

            var client = new HummClient(config);

            var request = new InviteRequest()
            {
                MobileNumber = "0400000", PurchaseAmount = 10.01M, OperatorId = "Automated"
            };

            _ = await client.InviteAsync(request);
        }
Ejemplo n.º 9
0
        public void UpdateLayerFieldTest()
        {
            var oldName = "fieldName";

            var url     = String.Join("/", new string[] { urlPrefix1, layer1, "fields", oldName });
            var handler = new MockHttpHandler(url, "POST", (req, res, param) =>
            {
                var result     = new RestResult();
                result.Success = true;
                return(JsonConvert.SerializeObject(result));
            });

            mockServer.AddRequestHandler(handler);

            try
            {
                var db    = new MapDB(db1);
                var layer = new FeatureLayer(layer1, db);
                var field = new LayerField()
                {
                    FieldName = "newFieldName",
                    DataType  = "INT",
                    FieldSize = 64
                };
                layer.UpdateLayerField(oldName, field);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Ejemplo n.º 10
0
        public void ConvexHullTest()
        {
            var input = new IGeometryObject[]
            {
                new Point(new GeographicPosition(30.0, 110.0))
            };

            var url     = String.Join("/", new string[] { urlPrefix, "analysis/convexhull" });
            var handler = new MockHttpHandler(url, "POST", (req, res, param) =>
            {
                var result = new RestResult();
                var form   = req.GetFormData();
                if (form.ContainsKey("targets"))
                {
                    result.Data    = JsonConvert.SerializeObject(input);
                    result.Success = true;
                }
                return(JsonConvert.SerializeObject(result));
            });

            mockServer.AddRequestHandler(handler);

            try
            {
                var topo   = new TopoQuery();
                var result = topo.ConvexHull(input);
                Assert.AreEqual(input.Length, result.Length);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Ejemplo n.º 11
0
        public void QueryTest()
        {
            var id       = "id";
            var point    = new Point(new GeographicPosition(30.0, 110.0));
            var feature  = new Feature(point);
            var features = new List <Feature>();

            features.Add(feature);
            var collection = new FeatureCollection(features);
            var expected   = new FeatureCollection[] { collection };

            var url     = String.Join("/", new string[] { urlPrefix, db1, "layers", id, "data" });
            var handler = new MockHttpHandler(url, "POST", (req, res, param) =>
            {
                var result     = new RestResult();
                result.Success = true;
                result.Count   = 1;
                result.Data    = JsonConvert.SerializeObject(expected);
                return(JsonConvert.SerializeObject(result));
            });

            mockServer.AddRequestHandler(handler);

            try
            {
                var db     = new MapDB(db1);
                var filter = new QueryFilter();
                var actual = db.Query(filter, 0, 10, new string[] { id });
                Assert.AreEqual(expected[0], actual[0]);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Ejemplo n.º 12
0
        public void GetDbInfoTest()
        {
            var expected = new DbInfo();

            expected.Name    = db1;
            expected.Version = "1.0.0";
            expected.CRS     = CRS.WGS84;

            var url     = String.Join("/", new string[] { urlPrefix, db1 });
            var handler = new MockHttpHandler(url, "GET", (req, res, param) =>
            {
                var result     = new RestResult();
                result.Success = true;
                result.Data    = JsonConvert.SerializeObject(expected);

                return(JsonConvert.SerializeObject(result));
            });

            mockServer.AddRequestHandler(handler);

            try
            {
                var db     = new MapDB(db1);
                var actual = db.GetDbInfo();
                Assert.AreEqual <DbInfo>(expected, actual);
            }
            catch
            {
                Assert.Fail();
            }
        }
Ejemplo n.º 13
0
        public async Task DoMoveAsyncTest(HttpStatusCode status, bool success = true, char expected = 't')
        {
            MockHttpHandler handler = new MockHttpHandler();

            handler.SetHttpStatus(status);
            var move = new Move {
                Type = MoveType.Set, X = 0, Y = 0
            };

            char[,] map = new char[10, 10];
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    map[i, j] = 'u';
                }
            }
            map[0, 0] = 't';
            var result = new MineResult {
                map = map, status = GameStatus.Ongoing, success = true, turn = true
            };

            handler.SetReturnObj(result);
            ApiHandler.Instance.SetHandler(handler);
            result = await ApiHandler.Instance.DoMoveAsync(move);

            Assert.AreEqual(success, result.success);
            Assert.AreEqual(expected, result.map[0, 0]);
        }
        public async Task Client_LogsExceptionMessage_WhenHttpExceptionIsThrown()
        {
            //Arrange
            var requestedStoryId = 12345678;


            MockCacheClient.Setup(client => client.CreateEntry(It.IsAny <object>()))
            .Returns(Mock.Of <ICacheEntry>);
            MockHttpHandler.Protected().Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(),
                                                                            ItExpr.IsAny <CancellationToken>())
            .Throws(new HttpRequestException());

            var httpClient = new HttpClient(MockHttpHandler.Object);

            var storyClient = new StoryClient(httpClient, MockCacheClient.Object, MockLoggingClient.Object);

            // Act
            await storyClient.GetStoryById(requestedStoryId);

            // Assert
            MockLoggingClient.Verify(log => log.Log(
                                         It.IsAny <LogLevel>(),
                                         It.IsAny <EventId>(),
                                         It.Is <It.IsAnyType>((o, t) => true),
                                         It.IsAny <Exception>(),
                                         It.Is <Func <It.IsAnyType, Exception, string> >((o, t) => true)));
        }
Ejemplo n.º 15
0
        public async Task HummClient_Sets_Default_UserAgent()
        {
            string sentUserAgent = null;

            var handler = new MockHttpHandler
                          (
                (clientRequest) =>
            {
                sentUserAgent = clientRequest.Headers.UserAgent.ToString();
                return(GetSuccessfulInviteResponse());
            }
                          );

            var config = new HummClientConfiguration()
            {
                BaseApiUrl = new Uri("https://integration-pos.shophumm.com.au/webapi/v1/Test/"),
                MerchantId = "30299999",
                DeviceId   = "d555",
                PosVersion = "1.0",
                DeviceKey  = "1234567890",
                HttpClient = new HttpClient(handler)
            };

            var client = new HummClient(config);

            var request = new InviteRequest()
            {
                MobileNumber = "0400000", PurchaseAmount = 10.01M, OperatorId = "Automated"
            };
            var response = await client.InviteAsync(request);

            Assert.AreEqual("Yort.Humm.Instore/" + typeof(HummClientConfiguration).Assembly.GetName().Version.ToString(), sentUserAgent);
        }
Ejemplo n.º 16
0
        public void IntersectionTest()
        {
            var source  = new Point(new GeographicPosition(30.0, 110.0));
            var targets = new IGeometryObject[]
            {
                new Point(new GeographicPosition(30.0, 110.0))
            };

            var url     = String.Join("/", new string[] { urlPrefix, "analysis/intersection" });
            var handler = new MockHttpHandler(url, "POST", (req, res, param) =>
            {
                var result = new RestResult();
                var form   = req.GetFormData();
                if (form.ContainsKey("source") && form.ContainsKey("targets"))
                {
                    result.Success = true;
                }
                return(JsonConvert.SerializeObject(result));
            });

            mockServer.AddRequestHandler(handler);

            try
            {
                var topo = new TopoQuery();
                topo.Intersection(source, targets);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Ejemplo n.º 17
0
        public void DifferenceTest()
        {
            var source  = new Point(new GeographicPosition(30.0, 110.0));
            var targets = new IGeometryObject[]
            {
                new Point(new GeographicPosition(30.0, 110.0))
            };
            var relation = SpatialFilter.RELATION_CONTAIN;

            var url     = String.Join("/", new string[] { urlPrefix, "analysis/difference" });
            var handler = new MockHttpHandler(url, "POST", (req, res, param) =>
            {
                var result = new RestResult();
                var form   = req.GetFormData();
                if (form.ContainsKey("source") && form.ContainsKey("targets"))
                {
                    result.Data    = JsonConvert.SerializeObject(targets);
                    result.Success = true;
                }
                return(JsonConvert.SerializeObject(result));
            });

            mockServer.AddRequestHandler(handler);

            try
            {
                var topo   = new TopoQuery();
                var result = topo.Difference(source, targets);
                Assert.AreEqual(targets.Length, result.Length);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Ejemplo n.º 18
0
        public async Task HummClient_ProcessAuthorisation_RaisesEvent_When_AutoHandlePendingResponse_True()
        {
            int requestCount = 0;

            var request = new ProcessAuthorisationRequest()
            {
                ClientTransactionReference = System.Guid.NewGuid().ToString(),
                PurchaseAmount             = 100,
                FinanceAmount   = 500,
                PreapprovalCode = "01000000",
                OperatorId      = "Yort",
                PurchaseItems   = new PurchaseItemsCollection()
                {
                    "Item1", "Item2"
                },
                BuyerConfirms             = true,
                AutoHandlePendingResponse = true,
                TrackingData = new Dictionary <string, string>()
                {
                    { "Key1", "Value1" }
                }
            };

            var handler = new MockHttpHandler
                          (
                (clientRequest) =>
            {
                requestCount++;
                if (requestCount >= 4)
                {
                    return(GetSuccessfulProcessAuthorisationResponse());
                }

                return(GetPendingProcessAuthorisationResponse(request));
            }
                          );
            var eventRaised = false;

            var client = CreateMockedClient(handler);

            client.PendingAuthorisation += (sender, e) =>
            {
                eventRaised = true;
                Assert.AreEqual(request.ClientTransactionReference, e.ClientReference);
                Assert.AreEqual(5, e.RetryDuration);
                Assert.AreEqual(request.TrackingData.Count, e.TrackingData.Count);
            };

            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();
            var response = await client.ProcessAuthorisationAsync(request);

            sw.Stop();

            Assert.AreEqual(4, requestCount);
            Assert.IsTrue(sw.Elapsed.TotalSeconds >= 15);
            Assert.IsTrue(eventRaised);
        }
Ejemplo n.º 19
0
 public JsonRequestMatchingExtensionTests()
 {
     _httpMock   = new MockHttpHandler();
     _httpClient = new HttpClient(_httpMock)
     {
         BaseAddress = new Uri("http://0.0.0.0")
     };
 }
 public When_adding_correlation_delegating_handler_to_httpClient()
 {
     _mockHttp = new MockHttpHandler();
     _services = new ServiceCollection();
     _sut      = _services
                 .AddHttpClient <MyService, MyService>()
                 .ConfigurePrimaryHttpMessageHandler(() => _mockHttp);
 }
 public JsonRespondsExtensionsTests()
 {
     _httpMock   = new MockHttpHandler();
     _httpClient = new HttpClient(_httpMock)
     {
         BaseAddress = new Uri("http://0.0.0.0")
     };
     _sut = _httpMock.When(_ => { });
 }
Ejemplo n.º 22
0
        public async Task GetString()
        {
            var httpHandler = new MockHttpHandler(x => new HttpApiResponse(body: x.Body));
            var client      = HttpApiClient <IApi> .Create("http://localhost", httpHandler : httpHandler);

            var result = await client.GetString("foo");

            Assert.AreEqual("foo", result);
        }
Ejemplo n.º 23
0
        public async Task JsonResponse()
        {
            var api         = new HttpApi <IJsonResponse>();
            var endpoint    = api.Endpoints.Single().Value;
            var httpHandler = new MockHttpHandler(new HttpApiResponse(body: new JsonHttpBody("foo")));
            var result      = (string)await endpoint.Call(httpHandler, "http://localhost", new Dictionary <string, object>());

            Assert.AreEqual("foo", result);
        }
Ejemplo n.º 24
0
            public static HttpClient CreateClient(Func <HttpRequestMessage, CancellationToken, Task <HttpResponseMessage> > func)
            {
                var handler = new MockHttpHandler(func);

                return(new HttpClient(handler)
                {
                    Timeout = Timeout.InfiniteTimeSpan,
                });
            }
Ejemplo n.º 25
0
        public void Setup()
        {
            _testAddress = new Uri("http://TestHost.com/blah");
            _expectedUrl = _testAddress.OriginalString;

            _mockHttpHandler = Substitute.ForPartsOf <MockHttpHandler>();
            _httpClient      = new HttpClient(_mockHttpHandler);

            _sut = new RestClient(_httpClient);
        }
Ejemplo n.º 26
0
        public async Task Method()
        {
            var httpHandler     = new MockHttpHandler();
            var responseHandler = new MockResponseHandler <object>();

            var endpoint = new HttpApiEndpoint(null, "path/to/api", HttpMethod.Get, new Dictionary <string, IHttpArgumentHandler>(), responseHandler, Enumerable.Empty <HttpHeader>());
            await endpoint.Call(httpHandler, "http://localhost", new Dictionary <string, object>());

            Assert.AreEqual(HttpMethod.Get, httpHandler.Request.Method);
        }
Ejemplo n.º 27
0
        public async Task Header()
        {
            var api         = new HttpApi <IHeaderApi>();
            var endpoint    = api.Endpoints.Single().Value;
            var httpHandler = new MockHttpHandler();
            await endpoint.Call(httpHandler, "http://localhost", new Dictionary <string, object>());

            var header = httpHandler.Request.Headers.Single(x => x.Name == "User-Agent");

            Assert.AreEqual("TestUserAgent", header.Values.Single());
        }
Ejemplo n.º 28
0
        public async Task PathForApiType()
        {
            var api         = new HttpApi <IPathForApi>();
            var endpoint    = api.Endpoints.Single().Value;
            var httpHandler = new MockHttpHandler();
            await endpoint.Call(httpHandler, "http://localhost", new Dictionary <string, object> {
                ["key"] = "to"
            });

            Assert.AreEqual("http://localhost/path/to/api", httpHandler.Request.Url.ToString());
        }
Ejemplo n.º 29
0
        public async Task Query()
        {
            var api         = new HttpApi <IQueryApi>();
            var endpoint    = api.Endpoints.Single().Value;
            var httpHandler = new MockHttpHandler();
            await endpoint.Call(httpHandler, "http://localhost", new Dictionary <string, object> {
                ["id"] = 1, ["query"] = 2
            });

            Assert.AreEqual("http://localhost/1?foo=bar", httpHandler.Request.Url.ToString());
        }
Ejemplo n.º 30
0
        private HttpHandler(
            string url, Handler handlerFunction, HttpMethods httpMethod, int count)
        {
            Count           = count;
            HandlerFunction = handlerFunction;
            HttpMethod      = httpMethod.GetMethod();
            Url             = url;

            MockHttpHandler = new MockHttpHandler(
                url, HttpMethod, HandlerFunctionWithCounter);
        }
Ejemplo n.º 31
0
 public MockHttpClient(string responseData, MockHttpHandler handler)
     : base(handler)
 {
     _InnerHandler = handler;
 }