public async Task GetRawTokenAsync_SendsCorrectRequest()
        {
            HttpConfiguration config = new HttpConfiguration();
            config.SetMobileAppSettingsProvider(new MobileAppSettingsProvider());

            string accessToken = "11111";
            string facebookId = "22222";
            TokenResult tokenResult = CreateTokenResult(facebookId, accessToken);

            MockHttpMessageHandler handlerMock = new MockHttpMessageHandler(CreateResponse(tokenResult));

            var gatewayUri = "http://test";
            Mock<AppServiceHttpClient> appServiceClientMock = new Mock<AppServiceHttpClient>(new Uri(gatewayUri));
            appServiceClientMock.CallBase = true;
            appServiceClientMock.Setup(c => c.CreateHttpClient())
                .Returns(new HttpClient(handlerMock));

            // Act
            TokenResult result = await appServiceClientMock.Object.GetRawTokenAsync(accessToken, "Facebook");

            // Assert
            Assert.Equal(accessToken, result.Properties[TokenResult.Authentication.AccessTokenName]);
            Assert.Equal(gatewayUri + "/api/tokens?tokenName=Facebook&api-version=2015-01-14", handlerMock.ActualRequest.RequestUri.ToString());
            Assert.Equal(accessToken, handlerMock.ActualRequest.Headers.GetValues("X-ZUMO-AUTH").Single());
            Assert.Equal("MobileAppNetServerSdk", handlerMock.ActualRequest.Headers.GetValues("User-Agent").Single());
        }
        public async Task GetRawTokenAsync_SendsCorrectRequest()
        {
            HttpConfiguration config = new HttpConfiguration();
            config.SetMobileAppSettingsProvider(new MobileAppSettingsProvider());

            string accessToken = "facebookAccessToken";
            string authToken = "zumoAuthToken";
            string facebookId = "facebookUserId";
            string providerName = "Facebook";
            TokenEntry tokenEntry = new TokenEntry(providerName);
            tokenEntry.AccessToken = accessToken;
            tokenEntry.AuthenticationToken = authToken;
            tokenEntry.UserId = facebookId;

            MockHttpMessageHandler handlerMock = new MockHttpMessageHandler(CreateResponse(tokenEntry));

            var webappUri = "http://test";
            Mock<AppServiceHttpClient> appServiceClientMock = new Mock<AppServiceHttpClient>(new Uri(webappUri));
            appServiceClientMock.CallBase = true;
            appServiceClientMock.Setup(c => c.CreateHttpClient())
                .Returns(new HttpClient(handlerMock));

            // Act
            TokenEntry result = await appServiceClientMock.Object.GetRawTokenAsync(accessToken, "Facebook");

            // Assert
            Assert.Equal(accessToken, result.AccessToken);
            Assert.Equal(authToken, result.AuthenticationToken);
            Assert.Equal(facebookId, result.UserId);
            Assert.Equal(webappUri + "/.auth/me?provider=facebook", handlerMock.ActualRequest.RequestUri.ToString());
            Assert.Equal(accessToken, handlerMock.ActualRequest.Headers.GetValues("x-zumo-auth").Single());
            Assert.Equal("MobileAppNetServerSdk", handlerMock.ActualRequest.Headers.GetValues("User-Agent").Single());
        }
        public void SendAsync_Traces_And_Invokes_Inner()
        {
            // Arrange
            HttpResponseMessage response = new HttpResponseMessage();
            MockDelegatingHandler mockHandler = new MockDelegatingHandler((rqst, cancellation) =>
                                                 TaskHelpers.FromResult<HttpResponseMessage>(response));

            TestTraceWriter traceWriter = new TestTraceWriter();
            MessageHandlerTracer tracer = new MessageHandlerTracer(mockHandler, traceWriter);
            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) =>
                                     TaskHelpers.FromResult<HttpResponseMessage>(response));
            tracer.InnerHandler = mockInnerHandler;

            HttpRequestMessage request = new HttpRequestMessage();
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "SendAsync" },
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "SendAsync" }
            };

            MethodInfo method = typeof(DelegatingHandler).GetMethod("SendAsync",
                                                                     BindingFlags.Public | BindingFlags.NonPublic |
                                                                     BindingFlags.Instance);

            // Act
            Task<HttpResponseMessage> task = method.Invoke(tracer, new object[] { request, CancellationToken.None }) as Task<HttpResponseMessage>;
            HttpResponseMessage actualResponse = task.Result;

            // Assert
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(response, actualResponse);
        }
        public void SendAsync_Traces_And_Throws_When_Inner_Throws()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("test");
            MockDelegatingHandler mockHandler = new MockDelegatingHandler((rqst, cancellation) => { throw exception; });

            TestTraceWriter traceWriter = new TestTraceWriter();
            MessageHandlerTracer tracer = new MessageHandlerTracer(mockHandler, traceWriter);

            // DelegatingHandlers require an InnerHandler to run.  We create a mock one to simulate what
            // would happen when a DelegatingHandler executing after the tracer throws.
            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => { throw exception; });
            tracer.InnerHandler = mockInnerHandler;

            HttpRequestMessage request = new HttpRequestMessage();
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "SendAsync" },
                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "SendAsync" }
            };

            MethodInfo method = typeof(DelegatingHandler).GetMethod("SendAsync",
                                                                     BindingFlags.Public | BindingFlags.NonPublic |
                                                                     BindingFlags.Instance);

            // Act
            Exception thrown =
                Assert.Throws<TargetInvocationException>(
                    () => method.Invoke(tracer, new object[] { request, CancellationToken.None }));

            // Assert
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown.InnerException);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
        public async Task GetRawTokenAsync_ReturnsNull_IfNoToken()
        {
            string accessToken = "facebookAccessToken";
            MockHttpMessageHandler handlerMock = new MockHttpMessageHandler(CreateEmptyResponse());

            var webappUri = "http://test";
            AppServiceHttpClient appServiceClientMock = new AppServiceHttpClient(new HttpClient(handlerMock));

            // Act
            TokenEntry result = await appServiceClientMock.GetRawTokenAsync(new Uri(webappUri), accessToken, "Facebook");

            // Assert
            Assert.Null(result);
            Assert.Equal(webappUri + "/.auth/me?provider=facebook", handlerMock.ActualRequest.RequestUri.ToString());
            Assert.Equal(accessToken, handlerMock.ActualRequest.Headers.GetValues("x-zumo-auth").Single());
            Assert.Equal("MobileAppNetServerSdk", handlerMock.ActualRequest.Headers.GetValues("User-Agent").Single());
        }
        public async Task GetRawTokenAsync_Throws_IfResponseIsNotSuccess(HttpStatusCode status)
        {
            HttpConfiguration config = new HttpConfiguration();
            config.SetMobileAppSettingsProvider(new MobileAppSettingsProvider());

            var response = new HttpResponseMessage(status);
            MockHttpMessageHandler handlerMock = new MockHttpMessageHandler(response);
            var gatewayUri = "http://test";

            AppServiceHttpClient appServiceClientMock = new AppServiceHttpClient(new HttpClient(handlerMock));

            // Act
            var ex = await Assert.ThrowsAsync<HttpResponseException>(() => appServiceClientMock.GetRawTokenAsync(new Uri(gatewayUri), "123456", "Facebook"));

            // Assert
            Assert.NotNull(ex);
            Assert.Same(response, ex.Response);
        }
        public async Task UploadHealthAsync_should_pass_clientCurrentTime_with_request()
        {
            var mockHttp = new MockHttpMessageHandler();
            var mockTimeCoordinator = new Mock<ITimeCoordinator>();
            var mockCredentialsProvider = new Mock<ICredentialsProvider>();
            var currentTimeUtc = DateTime.UtcNow;
            mockTimeCoordinator.Setup(c => c.UtcNow).Returns(currentTimeUtc);
            var client = new TestableHealthMonitorExchangeClient(mockHttp, mockTimeCoordinator.Object, mockCredentialsProvider.Object);

            mockHttp.Setup(
                $"http://mock/api/endpoints/health?clientCurrentTime={currentTimeUtc.ToString("u", CultureInfo.InvariantCulture)}", 
                req => new HttpResponseMessage(HttpStatusCode.OK));

            try
            {
                var update = new EndpointHealthUpdate(Guid.NewGuid(), new EndpointHealth(DateTime.UtcNow, TimeSpan.Zero, EndpointStatus.Faulty));
                await client.UploadHealthAsync(new[] { update }, CancellationToken.None);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException($"Client should not throw, but it did: {e.Message}", e);
            }
        }
Пример #8
0
        public async Task Can_simulate_timeout()
        {
            var handler = new MockHttpMessageHandler();

            handler.Fallback.Respond(async () =>
            {
                await Task.Delay(10000);

                return new HttpResponseMessage(HttpStatusCode.OK);
            });

            var client = new HttpClient(handler);
            client.Timeout = TimeSpan.FromMilliseconds(1000);

            try
            {
                var result = await client.GetAsync("http://localhost");

                throw new InvalidOperationException("Expected timeout exception");
            }
            catch(OperationCanceledException)
            {
            }
        }
Пример #9
0
        public void SendRequestAsyncSendsRequest()
        {
            var messageHandler = new MockHttpMessageHandler();
            var httpClient = new HttpClient(messageHandler) { BaseAddress = new Uri("http://api.com") };
            var requester = new PublicRequester(httpClient);

            var requestInfo = new RequestInfo(HttpMethod.Get, "foo");

            var responseMessage = new HttpResponseMessage();
            messageHandler.ResponseMessage = Task.FromResult(responseMessage);

            var response = requester.SendRequestAsync(requestInfo).Result;

            Assert.Equal("http://api.com/foo", messageHandler.Request.RequestUri.ToString());
            Assert.Equal(responseMessage, response);
        }
Пример #10
0
        public void SendRequestDoesNotThrowIfResponseIsBadButAllowAnyStatusCodeSpecified()
        {
            var messageHandler = new MockHttpMessageHandler();
            var httpClient = new HttpClient(messageHandler) { BaseAddress = new Uri("http://api.com") };
            var requester = new PublicRequester(httpClient);

            var requestInfo = new RequestInfo(HttpMethod.Get, "foo");
            requestInfo.AllowAnyStatusCode = true;

            var responseMessage = new HttpResponseMessage();
            responseMessage.StatusCode = HttpStatusCode.NotFound;

            messageHandler.ResponseMessage = Task.FromResult(responseMessage);

            var response = requester.SendRequestAsync(requestInfo).Result;
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }
Пример #11
0
        public async Task Action_HttpRequest()
        {
            var handler = new MockHttpMessageHandler();

            handler
            .When(HttpMethod.Post, "http://foo.com/")
            .WithContent("Joe is 52")
            .Respond("plain/text", "string");

            handler
            .When(HttpMethod.Post, "http://foo.com/")
            .WithContent("{\r\n  \"text\": \"Joe is 52\",\r\n  \"age\": 52\r\n}".Replace("\r\n", Environment.NewLine))
            .Respond("plain/text", "object");

            handler
            .When(HttpMethod.Post, "http://foo.com/")
            .WithHeaders(new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("bound", "52"),
                new KeyValuePair <string, string>("unbound", "dialog.age")
            })
            .WithContent("[\r\n  {\r\n    \"text\": \"Joe is 52\",\r\n    \"age\": 52\r\n  },\r\n  {\r\n    \"text\": \"text\",\r\n    \"age\": 11\r\n  }\r\n]".Replace("\r\n", Environment.NewLine))
            .Respond("plain/text", "array");

            var testAdapter = new TestAdapter()
                              .UseStorage(new MemoryStorage())
                              .UseBotState(new ConversationState(new MemoryStorage()), new UserState(new MemoryStorage()));

            var rootDialog = new AdaptiveDialog()
            {
                Triggers = new List <Conditions.OnCondition>()
                {
                    new OnBeginDialog()
                    {
                        Actions = new List <Dialog>()
                        {
                            new SetProperties()
                            {
                                Assignments = new List <PropertyAssignment>()
                                {
                                    new PropertyAssignment()
                                    {
                                        Property = "dialog.name", Value = "Joe"
                                    },
                                    new PropertyAssignment()
                                    {
                                        Property = "dialog.age", Value = 52
                                    },
                                }
                            },
                            new HttpRequest()
                            {
                                Url         = "http://foo.com/",
                                Method      = HttpRequest.HttpMethod.POST,
                                ContentType = "plain/text",
                                Body        = "${dialog.name} is ${dialog.age}"
                            },
                            new SendActivity("${turn.lastresult.content}"),
                            new HttpRequest()
                            {
                                Url         = "http://foo.com/",
                                Method      = HttpRequest.HttpMethod.POST,
                                ContentType = "application/json",
                                Body        = JToken.FromObject(new
                                {
                                    text = "${dialog.name} is ${dialog.age}",
                                    age  = "=dialog.age"
                                })
                            },
                            new SendActivity("${turn.lastresult.content}"),
                            new HttpRequest()
                            {
                                Url         = "http://foo.com/",
                                Method      = HttpRequest.HttpMethod.POST,
                                ContentType = "application/json",
                                Headers     = new Dictionary <string, AdaptiveExpressions.Properties.StringExpression>()
                                {
                                    { "bound", "=dialog.age" },
                                    { "unbound", "dialog.age" }
                                },
                                Body = JToken.FromObject(new object[]
                                {
                                    new
                                    {
                                        text = "${dialog.name} is ${dialog.age}",
                                        age  = "=dialog.age"
                                    },
                                    new
                                    {
                                        text = "text",
                                        age  = 11
                                    }
                                })
                            },
                            new SendActivity("${turn.lastresult.content}"),
                            new SendActivity("done")
                        }
                    }
                }
            };

            DialogManager dm = new DialogManager(rootDialog)
                               .UseResourceExplorer(new ResourceExplorer())
                               .UseLanguageGeneration();

            dm.InitialTurnState.Set <HttpClient>(handler.ToHttpClient());

            await new TestFlow((TestAdapter)testAdapter, dm.OnTurnAsync)
            .SendConversationUpdate()
            .AssertReply("string")
            .AssertReply("object")
            .AssertReply("array")
            .AssertReply("done")
            .StartTestAsync();
        }
 public void Setup()
 {
     _userService = new Mock <IUserService>();
     _mockHttp    = new MockHttpMessageHandler();
 }
Пример #13
0
        internal static DeliveryClient GetMockedDeliveryClientWithOptions(DeliveryOptions options, MockHttpMessageHandler httpMessageHandler = null)
        {
            var httpClient = httpMessageHandler != null?httpMessageHandler.ToHttpClient() : MockHttp.ToHttpClient();

            var client = new DeliveryClient(
                Options.Create(options),
                httpClient,
                _mockContentLinkUrlResolver,
                _mockInlineContentItemsProcessor,
                _mockModelProvider,
                _mockResiliencePolicyProvider,
                _mockTypeProvider,
                _mockPropertyMapper
                );

            return(client);
        }
Пример #14
0
        private AdaptiveDialog CreateQnAMakerActionDialog(MockHttpMessageHandler mockHttp)
        {
            var client = new HttpClient(mockHttp);

            var host           = "https://dummy-hostname.azurewebsites.net/qnamaker";
            var knowlegeBaseId = "dummy-id";
            var endpointKey    = "dummy-key";

            var rootDialog = new AdaptiveDialog("outer")
            {
                AutoEndDialog = false,
                Recognizer    = new QnAMakerRecognizer()
                {
                    KnowledgeBaseId = knowlegeBaseId,
                    HostName        = host,
                    EndpointKey     = endpointKey,
                    HttpClient      = client
                },
                Triggers = new List <OnCondition>()
                {
                    new OnQnAMatch()
                    {
                        Actions = new List <Dialog>()
                        {
                            new SendActivity()
                            {
                                Activity = new ActivityTemplate("@{@answer}")
                            },
                            new AssertCondition()
                            {
                                Condition   = "count(turn.recognized.entities.answer) == 1",
                                Description = "If there is a match there should only be 1 answer"
                            },
                            new AssertCondition()
                            {
                                Condition   = "turn.recognized.answers[0].answer != null",
                                Description = "There should be answers object"
                            },
                            new SendActivity()
                            {
                                Activity = new ActivityTemplate("done")
                            }
                        }
                    },
                    new OnIntent()
                    {
                        Intent  = "DeferToRecognizer_xxx",
                        Actions = new List <Dialog>()
                        {
                            new SendActivity()
                            {
                                Activity = new ActivityTemplate("DeferToRecognizer_xxx")
                            }
                        }
                    },
                    new OnUnknownIntent()
                    {
                        Actions = new List <Dialog>()
                        {
                            new SendActivity("Wha?")
                        }
                    }
                }
            };

            return(rootDialog);
        }
Пример #15
0
        public async Task GetBrowsersStatsAsync()
        {
            // Arrange
            var browsers  = new[] { "Chrome", "Firefox" };
            var startDate = new DateTime(2014, 10, 1);
            var endDate   = new DateTime(2014, 10, 2);

            var apiResponse = @"[
				{
					""date"": ""2014-10-01"",
					""stats"": [
						{
							""metrics"": {
								""clicks"": 0,
								""unique_clicks"": 0
							},
							""name"": ""Chrome"",
							""type"": ""browser""
						},
						{
							""metrics"": {
								""clicks"": 1,
								""unique_clicks"": 1
							},
							""name"": ""Firefox"",
							""type"": ""browser""
						}
					]
				},
				{
					""date"": ""2014-10-02"",
					""stats"": [
						{
							""metrics"": {
								""clicks"": 0,
								""unique_clicks"": 0
							},
							""name"": ""Chrome"",
							""type"": ""browser""
						},
						{
							""metrics"": {
								""clicks"": 1,
								""unique_clicks"": 1
							},
							""name"": ""Firefox"",
							""type"": ""browser""
						}
					]
				}
			]"            ;

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri($"browsers/stats?start_date={startDate.ToString("yyyy-MM-dd")}&end_date={endDate.ToString("yyyy-MM-dd")}&browsers={browsers[0]}&browsers={browsers[1]}")).Respond("application/json", apiResponse);

            var client     = Utils.GetFluentClient(mockHttp);
            var statistics = new Statistics(client);

            // Act
            var result = await statistics.GetBrowsersStatisticsAsync(browsers, startDate, endDate, AggregateBy.None, null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
            result.Length.ShouldBe(2);
            result[0].Stats.Length.ShouldBe(2);
            result[0].Stats[0].Name.ShouldBe("Chrome");
            result[0].Stats[0].Type.ShouldBe("browser");
        }
Пример #16
0
        private static IDebuggerClient Create(MockHttpMessageHandler messageHandler)
        {
            var executor = messageHandler.CreateExecutor();

            return(DebuggerClient.NewInstance(executor));
        }
Пример #17
0
        public async Task GetGlobalStatsAsync()
        {
            // Arrange
            var startDate = new DateTime(2015, 1, 1);
            var endDate   = new DateTime(2015, 1, 2);

            var apiResponse = @"[
				{
					""date"": ""2015-01-01"",
					""stats"": [
						{
							""metrics"": {
								""blocks"": 1,
								""bounce_drops"": 0,
								""bounces"": 0,
								""clicks"": 0,
								""deferred"": 1,
								""delivered"": 1,
								""invalid_emails"": 1,
								""opens"": 1,
								""processed"": 2,
								""requests"": 3,
								""spam_report_drops"": 0,
								""spam_reports"": 0,
								""unique_clicks"": 0,
								""unique_opens"": 1,
								""unsubscribe_drops"": 0,
								""unsubscribes"": 0
							}
						}
					]
				},
				{
					""date"": ""2015-01-02"",
					""stats"": [
						{
							""metrics"": {
								""blocks"": 0,
								""bounce_drops"": 0,
								""bounces"": 0,
								""clicks"": 0,
								""deferred"": 0,
								""delivered"": 0,
								""invalid_emails"": 0,
								""opens"": 0,
								""processed"": 0,
								""requests"": 0,
								""spam_report_drops"": 0,
								""spam_reports"": 0,
								""unique_clicks"": 0,
								""unique_opens"": 0,
								""unsubscribe_drops"": 0,
								""unsubscribes"": 0
							}
						}
					]
				}
			]"            ;

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri($"stats?start_date={startDate.ToString("yyyy-MM-dd")}&end_date={ endDate.ToString("yyyy-MM-dd")}")).Respond("application/json", apiResponse);

            var client     = Utils.GetFluentClient(mockHttp);
            var statistics = new Statistics(client);

            // Act
            var result = await statistics.GetGlobalStatisticsAsync(startDate, endDate, AggregateBy.None, null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
            result.Length.ShouldBe(2);
            result[0].Stats.Length.ShouldBe(1);
            result[0].Stats[0].Metrics.Single(m => m.Key == "requests").Value.ShouldBe(3);
        }
Пример #18
0
        public async Task GetInboxProvidersStatsAsync()
        {
            // Arrange
            var providers = new[] { "Gmail", "Hotmail" };
            var startDate = new DateTime(2014, 10, 1);
            var endDate   = new DateTime(2014, 10, 2);

            var apiResponse = @"[
				{
					""date"": ""2014-10-01"",
					""stats"": [
						{
							""metrics"": {
								""blocks"": 1,
								""bounces"": 0,
								""clicks"": 0,
								""deferred"": 1,
								""delivered"": 1,
								""drops"": 0,
								""opens"": 1,
								""spam_reports"": 0,
								""unique_clicks"": 0,
								""unique_opens"": 1
							},
							""name"": ""Gmail"",
							""type"": ""esp""
						}
					]
				},
				{
					""date"": ""2014-10-02"",
					""stats"": [
						{
							""metrics"": {
								""blocks"": 0,
								""bounces"": 0,
								""clicks"": 0,
								""deferred"": 0,
								""delivered"": 0,
								""drops"": 0,
								""opens"": 0,
								""spam_reports"": 0,
								""unique_clicks"": 0,
								""unique_opens"": 0
							},
							""name"": ""Gmail"",
							""type"": ""esp""
						}
					]
				}
			]"            ;

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri($"mailbox_providers/stats?start_date={startDate.ToString("yyyy-MM-dd")}&end_date={endDate.ToString("yyyy-MM-dd")}&mailbox_providers={providers[0]}&mailbox_providers={providers[1]}")).Respond("application/json", apiResponse);

            var client     = Utils.GetFluentClient(mockHttp);
            var statistics = new Statistics(client);

            // Act
            var result = await statistics.GetInboxProvidersStatisticsAsync(providers, startDate, endDate, AggregateBy.None, null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
            result.Length.ShouldBe(2);
            result[0].Stats.Length.ShouldBe(1);
            result[0].Stats[0].Name.ShouldBe("Gmail");
            result[0].Stats[0].Type.ShouldBe("esp");
        }
Пример #19
0
        public void TestListAll()
        {
            var jsonResponseListAll = @"[{
				'balance': 0,
				'closed': true,
				'created_at': 1574371071,
				'currency': 'usd',
				'customer': 594287,
				'date': 1574371069,
				'discounts': [],
				'draft': false,
				'id': 8441,
				'invoice': 2356205,
				'items': [{
					'amount': 123,
					'catalog_item': null,
					'created_at': 1574371071,
					'description': '',
					'discountable': true,
					'id': 22932564,
					'name': 'ABC',
					'quantity': 1,
					'taxable': true,
					'type': null,
					'unit_cost': 123,
					'object': 'line_item',
					'metadata': {},
					'discounts': [],
					'taxes': []
				}],
				'metadata': {
					'account_manager': 'https://www.google.com/'
				},
				'name': 'Credit Note',
				'notes': null,
				'number': 'CN-00003',
				'object': 'credit_note',
				'paid': true,
				'pdf_url': 'https://ajwt.sandbox.invoiced.com/credit_notes/Oh08vH0WUnVauNfmz4SRrXqj/pdf',
				'shipping': [],
				'status': 'paid',
				'subtotal': 123,
				'taxes': [],
				'total': 123,
				'url': 'https://ajwt.sandbox.invoiced.com/credit_notes/Oh08vH0WUnVauNfmz4SRrXqj'
			}]"            ;

            var mockHttp = new MockHttpMessageHandler();

            var mockHeader = new Dictionary <string, string>();

            mockHeader["X-Total-Count"] = "1";
            mockHeader["Link"]          =
                "<https://api.sandbox.invoiced.com/credit_notes?page=1>; rel=\"self\", <https://api.sandbox.invoiced.com/credit_notes?page=1>; rel=\"first\", <https://api.sandbox.invoiced.com/credit_notes?page=1>; rel=\"last\"";

            var request = mockHttp.When(HttpMethod.Get, "https://testmode/credit_notes")
                          .Respond(mockHeader, "application/json", jsonResponseListAll);

            var client = mockHttp.ToHttpClient();

            var conn = new Connection("voodoo", Environment.test);

            conn.TestClient(client);

            var creditNote = conn.NewCreditNote();

            var creditNotes = creditNote.ListAll();

            Assert.True(creditNotes[0].Id == 8441);
            Assert.True(creditNotes[0].Number == "CN-00003");
        }
Пример #20
0
        public void TestSave()
        {
            var jsonResponse = @"{
				'balance': 0,
				'closed': true,
				'created_at': 1574371071,
				'currency': 'usd',
				'customer': 594287,
				'date': 1574371069,
				'discounts': [],
				'draft': false,
				'id': 8441,
				'invoice': 2356205,
				'items': [{
					'amount': 123,
					'catalog_item': null,
					'created_at': 1574371071,
					'description': '',
					'discountable': true,
					'id': 22932564,
					'name': 'ABC',
					'quantity': 1,
					'taxable': true,
					'type': null,
					'unit_cost': 123,
					'object': 'line_item',
					'metadata': {},
					'discounts': [],
					'taxes': []
				}],
				'metadata': {
					'account_manager': 'https://www.google.com/'
				},
				'name': 'Updated',
				'notes': null,
				'number': 'CN-00003',
				'object': 'credit_note',
				'paid': true,
				'pdf_url': 'https://ajwt.sandbox.invoiced.com/credit_notes/Oh08vH0WUnVauNfmz4SRrXqj/pdf',
				'shipping': [],
				'status': 'paid',
				'subtotal': 123,
				'taxes': [],
				'total': 123,
				'url': 'https://ajwt.sandbox.invoiced.com/credit_notes/Oh08vH0WUnVauNfmz4SRrXqj'
			}"            ;

            var mockHttp  = new MockHttpMessageHandler();
            var httpPatch = new HttpMethod("PATCH");
            var request   = mockHttp.When(httpPatch, "https://testmode/credit_notes/8441")
                            .Respond("application/json", jsonResponse);

            var client = mockHttp.ToHttpClient();

            var creditNote = CreateDefaultCreditNote(client);

            creditNote.Name = "Updated";

            creditNote.SaveAll();

            Assert.True(creditNote.Name == "Updated");
        }
        public async Task ExecuteDeliveryFailurePath()
        {
            var(messageData, metaData) = EventHandlerTestHelper.CreateMessageDataPayload();

            messageData.IsDlq = true;

            var config = new WebhookConfig
            {
                Uri                   = "http://localhost/webhook",
                HttpMethod            = HttpMethod.Put,
                EventType             = "Event1",
                PayloadTransformation = PayloadContractTypeEnum.WrapperContract,
                AuthenticationConfig  = new AuthenticationConfig(),
                WebhookRequestRules   = new List <WebhookRequestRule>
                {
                    new WebhookRequestRule
                    {
                        Source = new ParserLocation
                        {
                            Path = "OrderCode"
                        },
                        Destination = new ParserLocation
                        {
                            Location = Location.Uri
                        }
                    }
                }
            };

            var mockHttp = new MockHttpMessageHandler();

            var webhookRequest = mockHttp.Expect(HttpMethod.Put, $"{config.Uri}/{metaData["OrderCode"]}")
                                 .With((m) =>
            {
                var str = m.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                using (var sr = new StringReader(str))
                {
                    using (var jr = new JsonTextReader(sr))
                    {
                        var wrapperObj = JsonSerializer.CreateDefault().Deserialize <WrapperPayloadContract>(jr);
                        return(JToken.DeepEquals(wrapperObj.Payload, JObject.Parse(messageData.Payload)) && wrapperObj.CallbackType == CallbackTypeEnum.DeliveryFailure);
                    }
                }
            })
                                 .Respond(HttpStatusCode.OK, "application/json", string.Empty);

            var mockBigBrother = new Mock <IBigBrother>();
            var httpClients    = new Dictionary <string, HttpClient> {
                { new Uri(config.Uri).Host, mockHttp.ToHttpClient() }
            };

            var httpClientBuilder = new HttpClientFactory(httpClients);
            var requestBuilder    = new RequestBuilder();
            var requestLogger     = new RequestLogger(mockBigBrother.Object);

            var genericWebhookHandler = new GenericWebhookHandler(
                httpClientBuilder,
                new Mock <IAuthenticationHandlerFactory>().Object,
                requestBuilder,
                requestLogger,
                mockBigBrother.Object,
                config);

            await genericWebhookHandler.CallAsync(messageData, new Dictionary <string, object>(), _cancellationToken);

            Assert.Equal(1, mockHttp.GetMatchCount(webhookRequest));
        }
        public void SendAsync_Traces_And_Faults_When_Inner_Faults()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("test");
            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
            tcs.TrySetException(exception);
            TestTraceWriter traceWriter = new TestTraceWriter();
            RequestMessageHandlerTracer tracer = new RequestMessageHandlerTracer(traceWriter);

            // DelegatingHandlers require an InnerHandler to run.  We create a mock one to simulate what
            // would happen when a DelegatingHandler executing after the tracer returns a Task that throws.
            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => { return tcs.Task; });
            tracer.InnerHandler = mockInnerHandler;

            HttpRequestMessage request = new HttpRequestMessage();
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Info) { Kind = TraceKind.Begin },
                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Error) { Kind = TraceKind.End }
            };

            MethodInfo method = typeof(DelegatingHandler).GetMethod("SendAsync",
                                                                     BindingFlags.Public | BindingFlags.NonPublic |
                                                                     BindingFlags.Instance);

            // Act
            Task<HttpResponseMessage> task =
                method.Invoke(tracer, new object[] { request, CancellationToken.None }) as Task<HttpResponseMessage>;

            // Assert
            Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait());
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
Пример #23
0
        public async Task GetCategoryStatsAsync()
        {
            // Arrange
            var categories = new[] { "cat1", "cat2" };
            var startDate  = new DateTime(2015, 1, 1);
            var endDate    = new DateTime(2015, 1, 2);

            var apiResponse = @"[
				{
					""date"": ""2015-01-01"",
					""stats"": [
						{
							""metrics"": {
								""blocks"": 0,
								""bounce_drops"": 0,
								""bounces"": 0,
								""clicks"": 0,
								""deferred"": 0,
								""delivered"": 0,
								""invalid_emails"": 0,
								""opens"": 0,
								""processed"": 0,
								""requests"": 0,
								""spam_report_drops"": 0,
								""spam_reports"": 0,
								""unique_clicks"": 0,
								""unique_opens"": 0,
								""unsubscribe_drops"": 0,
								""unsubscribes"": 0
							},
							""name"": ""cat1"",
							""type"": ""category""
						},
						{
							""metrics"": {
								""blocks"": 0,
								""bounce_drops"": 0,
								""bounces"": 0,
								""clicks"": 0,
								""deferred"": 0,
								""delivered"": 0,
								""invalid_emails"": 0,
								""opens"": 0,
								""processed"": 0,
								""requests"": 0,
								""spam_report_drops"": 0,
								""spam_reports"": 0,
								""unique_clicks"": 0,
								""unique_opens"": 0,
								""unsubscribe_drops"": 0,
								""unsubscribes"": 0
							},
							""name"": ""cat2"",
							""type"": ""category""
						}
					]
				},
				{
					""date"": ""2015-01-02"",
					""stats"": [
						{
							""metrics"": {
								""blocks"": 10,
								""bounce_drops"": 0,
								""bounces"": 0,
								""clicks"": 0,
								""deferred"": 0,
								""delivered"": 0,
								""invalid_emails"": 0,
								""opens"": 0,
								""processed"": 0,
								""requests"": 10,
								""spam_report_drops"": 0,
								""spam_reports"": 0,
								""unique_clicks"": 0,
								""unique_opens"": 0,
								""unsubscribe_drops"": 0,
								""unsubscribes"": 0
							},
							""name"": ""cat1"",
							""type"": ""category""
						},
						{
							""metrics"": {
								""blocks"": 0,
								""bounce_drops"": 0,
								""bounces"": 0,
								""clicks"": 6,
								""deferred"": 0,
								""delivered"": 5,
								""invalid_emails"": 0,
								""opens"": 6,
								""processed"": 0,
								""requests"": 5,
								""spam_report_drops"": 0,
								""spam_reports"": 0,
								""unique_clicks"": 5,
								""unique_opens"": 5,
								""unsubscribe_drops"": 0,
								""unsubscribes"": 6
							},
							""name"": ""cat2"",
							""type"": ""category""
						}
					]
				}
			]"            ;

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri($"categories/stats?start_date={startDate.ToString("yyyy-MM-dd")}&end_date={endDate.ToString("yyyy-MM-dd")}&categories={categories[0]}&categories={categories[1]}")).Respond("application/json", apiResponse);

            var client     = Utils.GetFluentClient(mockHttp);
            var statistics = new Statistics(client);

            // Act
            var result = await statistics.GetCategoriesStatisticsAsync(categories, startDate, endDate, AggregateBy.None, null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
            result.Length.ShouldBe(2);
            result[0].Stats.Length.ShouldBe(2);
            result[0].Stats[0].Name.ShouldBe("cat1");
            result[0].Stats[0].Type.ShouldBe("category");
        }
Пример #24
0
        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,\"searchableAttributes\": 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);
        }
Пример #25
0
        public RepositoryServiceTestsFixture()
        {
            FirstRepositoryId   = "SWxsdXN0cmF0aW9uLXdlYg==";
            FirstRepositoryName = "Mock First Repository";
            FirstRepositoryUrl  = "bitbucket.org/stash/projects/csharp/repos/core";

            SecondRepositoryId   = "SWxsdXN0cmF0aW9uLW1vYmlsZQ==";
            SecondRepositoryName = "Mock Second Repository";
            SecondRepositoryUrl  = "bitbucket.org/stash/projects/aspnet/repos/core";

            Repositories = new List <RepositoryDto>
            {
                new RepositoryDto
                {
                    Id   = FirstRepositoryId,
                    Name = FirstRepositoryName,
                    Url  = FirstRepositoryUrl
                },
                new RepositoryDto
                {
                    Id   = SecondRepositoryId,
                    Name = SecondRepositoryName,
                    Url  = SecondRepositoryUrl
                }
            };
            RepositoriesCount = Repositories.Count;

            FirstContributorId      = "U1d4c2RYTjBjbUYwYVc5dUxYZGxZZz09OktyeXN0aWFuIEN6YXBsaWNraTprcnlzdGlhbi5jemFwbGlja2lAaW50aXZlLmNvbQ==";
            FirstContributorName    = "Krystian Czaplicki";
            FirstContributorEmail   = "*****@*****.**";
            FirstContributorCommits = 5;

            SecondContributorId      = "U1d4c2RYTjBjbUYwYVc5dUxYZGxZZz09OlBhd2VsIEJvcm93c2tpOnBhd2VsLmJvcm93c2tpQGludGl2ZS5jb20=";
            SecondContributorName    = "John Page";
            SecondContributorEmail   = "*****@*****.**";
            SecondContributorCommits = 15;

            Contributors = new List <ContributorDto>
            {
                new ContributorDto
                {
                    Id      = FirstContributorId,
                    Name    = FirstContributorName,
                    Email   = FirstContributorEmail,
                    Commits = FirstContributorCommits
                },
                new ContributorDto
                {
                    Id      = SecondContributorId,
                    Name    = SecondContributorName,
                    Email   = SecondContributorEmail,
                    Commits = SecondContributorCommits
                }
            };
            ContributorsCount = Contributors.Count;

            NonExistingRepositoryId = "SWxsdXN0cmF0aW9uLWVuZ2luZQ==";

            HttpMessageHandler = new MockHttpMessageHandler();
            HttpMessageHandler.When(RestApiUrlsConsts.GetRepositoriesUrl)
            .Respond("application/json", JsonConvert.SerializeObject(Repositories));
            HttpMessageHandler.When(string.Format(RestApiUrlsConsts.GetRepositoryContributorsUrl, FirstRepositoryId))
            .Respond("application/json", JsonConvert.SerializeObject(Contributors));

            ErrorStatusCodeHttpMessageHandler = new MockHttpMessageHandler();
            ErrorStatusCodeHttpMessageHandler.When(RestApiUrlsConsts.GetRepositoriesUrl)
            .Respond(HttpStatusCode.BadRequest);
            HttpMessageHandler.When(string.Format(RestApiUrlsConsts.GetRepositoryContributorsUrl, FirstRepositoryId))
            .Respond(HttpStatusCode.BadRequest);

            EmptyResultsHttpMessageHandler = new MockHttpMessageHandler();
            EmptyResultsHttpMessageHandler.When(RestApiUrlsConsts.GetRepositoriesUrl)
            .Respond("application/json", "{}");
            EmptyResultsHttpMessageHandler.When(string.Format(RestApiUrlsConsts.GetRepositoryContributorsUrl, FirstRepositoryId))
            .Respond("application/json", "{}");
        }
 public void SetUp()
 {
     _mockHttp = new MockHttpMessageHandler();
 }
Пример #27
0
 public static MockHttpMessageHandler AddAuthMock(this MockHttpMessageHandler mockHttp)
 {
     return(mockHttp.AddAuthMock(out MockedRequest _));
 }
 public MediaServiceFixture()
 {
     _mockHttp = new MockHttpMessageHandler();
 }
Пример #29
0
        public static MockHttpMessageHandler AddAuthMock(this MockHttpMessageHandler mockHttp, out MockedRequest mocketRequest)
        {
            // Step 1
            mocketRequest = mockHttp.When($"{_portalUri}/portal/en_GB/web/guest/home")
                            .WithExactQueryString(string.Empty)
                            .Respond(new[] {
                new KeyValuePair <string, string>("Set-Cookie", "COOKIE_SUPPORT=true; Expires=Wed, 28-Apr-2021 20:44:04 GMT; Path=/; Secure; HttpOnly"),
                new KeyValuePair <string, string>("Set-Cookie", $"JSESSIONID={_sessionId}; Path=/; Secure; HttpOnly"),
                new KeyValuePair <string, string>("Set-Cookie", "GUEST_LANGUAGE_ID=en_GB; Expires=Wed, 28-Apr-2021 20:44:04 GMT; Path=/; Secure; HttpOnly"),
                new KeyValuePair <string, string>("Set-Cookie", "CARNET_LANGUAGE_ID=en_GB; Expires=Sat, 11-Dec-2066 23:26:12 GMT; Path=/; Secure; HttpOnly")
            }, "text/html",
                                     @"<html>
                    <head>
                        <title>We Connect</title>
                        <meta name=""_csrf"" content=""" + _csrf1 + @"""/>
                    </head>
                    <body></body>
                    </html>");

            // Step 1b
            mockHttp.When($"{_portalUri}/portal/en_GB/web/guest/home")
            .WithExactQueryString($"p_auth={_csrf1}&p_p_id=10_WAR_cored5portlet&p_p_lifecycle=1&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=2&_10_WAR_cored5portlet_javax.portlet.action=changeMarket")
            .Respond("text/plain", "");

            // Step 2
            mockHttp.When($"{_portalUri}/portal/en_GB/web/guest/home/-/csrftokenhandling/get-login-url")
            .Respond("application/json",
                     $"{{\"errorCode\":\"0\",\"loginURL\":{{\"path\":\"{_baseUri}/oidc/v1/authorize?ui_locales=en&scope={_scopes}&response_type=code&state={_csrf1}&redirect_uri={_redirectUri}&nonce={_nonce}&prompt=login&client_id={_clientId}\"}}}}");

            // Step 3
            mockHttp.When($"{_baseUri}/oidc/v1/authorize")
            .WithExactQueryString($"ui_locales=en&scope={_scopes}&response_type=code&state={_csrf1}&redirect_uri={_redirectUri}&nonce={_nonce}&prompt=login&client_id={_clientId}")
            .Respond(HttpStatusCode.Found, new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("Location", $"{_baseUri}/signin-service/v1/signin/{_clientId}?relayState={_relaystate}")
            }, "text/plain", "");

            // Step 4
            mockHttp.When($"{_baseUri}/signin-service/v1/signin/{_clientId}?relayState={_relaystate}")
            .Respond(new [] {
                new KeyValuePair <string, string>("Set-Cookie", $"SESSION={_sessionId}; Path=/signin-service/v1/; Secure; HttpOnly; SameSite=Lax")
            }, "text/html",
                     @"<!DOCTYPE html>
                    <html>
                    <body>
                        <form method=""POST"" action=""/signin-service/v1/{_clientId}/login/identifier"">
                            <input type=""hidden"" id=""hmac"" name=""hmac"" value=""" + _hmac2 + @"""/>
                            <input type=""hidden"" id=""csrf"" name=""_csrf"" value=""" + _csrf2 + @"""/>
	                    </form>
                    </body>
                    </html>");

            // Step 5
            mockHttp.When($"{_baseUri}/signin-service/v1/{_clientId}/login/identifier")
            .Respond("text/html",
                     @"<!DOCTYPE html>
                    <html>
                    <body>
                        <form method=""POST"" action=""/signin-service/v1/" + _clientId + @"/login/authenticate"">
                            <input type=""hidden"" id=""hmac"" name=""hmac"" value=""" + _hmac2 + @""" />
	                    </form>
                    </body>
                    </html>");

            // Step 6
            mockHttp.When($"{_baseUri}/signin-service/v1/{_clientId}/login/authenticate")
            .Respond(HttpStatusCode.Found, new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("Location", $"{_baseUri}/oidc/v1/oauth/sso?clientId={_clientId}&relayState={_relaystate}&userId={_userId}&HMAC={_hmac2}")
            }, "text/plain", "");

            mockHttp.When($"{_baseUri}/oidc/v1/oauth/sso")
            .WithExactQueryString($"clientId={_clientId}&relayState={_relaystate}&userId={_userId}&HMAC={_hmac2}")
            .Respond(HttpStatusCode.Found, new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("Location", $"{_baseUri}/signin-service/v1/consent/users/{_userId}/{_clientId}?scopes={_scopes}&relayState={_relaystate}&callback={_baseUri}/oidc/v1/oauth/client/callback&hmac={_hmac2}")
            }, "text/plain", "");

            mockHttp.When($"{_baseUri}/signin-service/v1/consent/users/{_userId}/{_clientId}")
            .WithExactQueryString($"scopes={_scopes}&relayState={_relaystate}&callback={_baseUri}/oidc/v1/oauth/client/callback&hmac={_hmac2}")
            .Respond(HttpStatusCode.Found, new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("Location", $"{_baseUri}/oidc/v1/oauth/client/callback/success?user_id={_userId}&client_id={_clientId}&scopes={_scopes}&consentedScopes={_scopes}&relayState={_relaystate}&hmac={_hmac2}")
            }, "text/plain", "");

            mockHttp.When($"{_baseUri}/oidc/v1/oauth/client/callback/success")
            .WithExactQueryString($"user_id={_userId}&client_id={_clientId}&scopes={_scopes}&consentedScopes={_scopes}&relayState={_relaystate}&hmac={_hmac2}")
            .Respond(HttpStatusCode.Found, new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("Location", $"{_portalUri}/portal/web/guest/complete-login?state={_finalCsrf}&code={_jwtToken}")
            }, "text/plain", "");

            mockHttp.When($"{_portalUri}/portal/web/guest/complete-login")
            .WithExactQueryString($"state={_finalCsrf}&code={_jwtToken}")
            .Respond("text/plain", "");

            // Step 7
            mockHttp.When($"{_portalUri}/portal/web/guest/complete-login")
            .WithExactQueryString($"p_auth={_finalCsrf}&p_p_id=33_WAR_cored5portlet&p_p_lifecycle=1&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_33_WAR_cored5portlet_javax.portlet.action=getLoginStatus")
            .Respond(HttpStatusCode.Found, new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("Location", $"{_portalUri}/portal/delegate/dashboard/{Vin}")
            }, "text/plain", "");

            // Step 8
            mockHttp.When($"{_portalUri}/portal/delegate/dashboard/{Vin}")
            .Respond("text/html",
                     @"<!DOCTYPE html>
                    <html>
                    <head>
                        <title>We Connect</title>
                        <meta name=""_csrf"" content=""" + _finalCsrf + @"""/>
                    </head>
                    <body></body>
                    </html>");

            return(mockHttp);
        }
        private async Task <(HttpRequestMessage HttpRequest, Guid Correlationid)> RunAcquireTokenSilentAsync(
            AcquireTokenSilentOutcome outcome,
            bool forceRefresh = false)
        {
            MockHttpMessageHandler tokenRequest = null;
            Guid correlationId = Guid.Empty;

            var account = (await _app.GetAccountsAsync().ConfigureAwait(false)).Single();
            AcquireTokenSilentParameterBuilder request = _app
                                                         .AcquireTokenSilent(TestConstants.s_scope, account)
                                                         .WithForceRefresh(forceRefresh);

            switch (outcome)
            {
            case AcquireTokenSilentOutcome.SuccessFromCache:
                var authResult = await request
                                 .ExecuteAsync()
                                 .ConfigureAwait(false);

                correlationId = authResult.CorrelationId;
                break;

            case AcquireTokenSilentOutcome.SuccessViaRefreshGrant:
                // let's remove the AT so that they can't be used
                _app.UserTokenCacheInternal.Accessor.ClearAccessTokens();
                tokenRequest = _harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityUtidTenant);
                authResult   = await request
                               .ExecuteAsync()
                               .ConfigureAwait(false);

                correlationId = authResult.CorrelationId;

                break;

            case AcquireTokenSilentOutcome.SuccessViaCacheRefresh:
                tokenRequest = _harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityUtidTenant);
                authResult   = await request
                               .ExecuteAsync()
                               .ConfigureAwait(false);

                correlationId = authResult.CorrelationId;

                break;

            case AcquireTokenSilentOutcome.FailInvalidGrant:
                (tokenRequest, correlationId) = await RunSilentFlowWithTokenErrorAsync(request, "invalid_grant")
                                                .ConfigureAwait(false);

                break;

            case AcquireTokenSilentOutcome.FailInteractionRequired:
                (tokenRequest, correlationId) = await RunSilentFlowWithTokenErrorAsync(request, "interaction_required")
                                                .ConfigureAwait(false);

                break;

            default:
                throw new NotImplementedException();
            }

            Assert.AreEqual(0, _harness.HttpManager.QueueSize);
            return(tokenRequest?.ActualRequestMessage, correlationId);
        }
Пример #31
0
        private async Task <(HttpRequestMessage HttpRequest, Guid Correlationid)> RunAcquireTokenForClientAsync(
            AcquireTokenForClientOutcome outcome, bool forceRefresh = false)
        {
            MockHttpMessageHandler tokenRequestHandler = null;
            Guid correlationId = default;

            switch (outcome)
            {
            case AcquireTokenForClientOutcome.Success:

                tokenRequestHandler = _harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(authority: TestConstants.AuthorityRegional);
                var authResult = await _app
                                 .AcquireTokenForClient(TestConstants.s_scope)
                                 .WithPreferredAzureRegion(true)
                                 .WithForceRefresh(forceRefresh)
                                 .ExecuteAsync()
                                 .ConfigureAwait(false);

                correlationId = authResult.CorrelationId;
                break;

            case AcquireTokenForClientOutcome.FallbackToGlobal:
                _harness.HttpManager.AddInstanceDiscoveryMockHandler();
                tokenRequestHandler = _harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(authority: TestConstants.AuthorityTenant);
                authResult          = await _app
                                      .AcquireTokenForClient(TestConstants.s_scope)
                                      .WithPreferredAzureRegion(true)
                                      .WithForceRefresh(forceRefresh)
                                      .ExecuteAsync()
                                      .ConfigureAwait(false);

                correlationId = authResult.CorrelationId;
                break;

            case AcquireTokenForClientOutcome.UserProvidedRegion:

                tokenRequestHandler = _harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(authority: TestConstants.AuthorityRegional);
                authResult          = await _app
                                      .AcquireTokenForClient(TestConstants.s_scope)
                                      .WithPreferredAzureRegion(true, TestConstants.Region)
                                      .WithForceRefresh(forceRefresh)
                                      .ExecuteAsync()
                                      .ConfigureAwait(false);

                correlationId = authResult.CorrelationId;
                break;

            case AcquireTokenForClientOutcome.UserProvidedInvalidRegion:

                tokenRequestHandler = _harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(authority: TestConstants.AuthorityRegional);
                authResult          = await _app
                                      .AcquireTokenForClient(TestConstants.s_scope)
                                      .WithPreferredAzureRegion(true, "invalid")
                                      .WithForceRefresh(forceRefresh)
                                      .ExecuteAsync()
                                      .ConfigureAwait(false);

                correlationId = authResult.CorrelationId;
                break;

            case AcquireTokenForClientOutcome.AADUnavailableError:
                correlationId = Guid.NewGuid();

                tokenRequestHandler = new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateFailureMessage(
                        System.Net.HttpStatusCode.GatewayTimeout, "gateway timeout")
                };
                var tokenRequestHandler2 = new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateFailureMessage(
                        System.Net.HttpStatusCode.GatewayTimeout, "gateway timeout")
                };

                // 2 of these are needed because MSAL has a "retry once" policy for 5xx errors
                _harness.HttpManager.AddMockHandler(tokenRequestHandler2);
                _harness.HttpManager.AddMockHandler(tokenRequestHandler);

                var serviceEx = await AssertException.TaskThrowsAsync <MsalServiceException>(() =>
                                                                                             _app
                                                                                             .AcquireTokenForClient(TestConstants.s_scope)
                                                                                             .WithPreferredAzureRegion(true)
                                                                                             .WithForceRefresh(true)
                                                                                             .WithCorrelationId(correlationId)
                                                                                             .ExecuteAsync())
                                .ConfigureAwait(false);

                break;

            default:
                throw new NotImplementedException();
            }

            Assert.AreEqual(0, _harness.HttpManager.QueueSize);

            return(tokenRequestHandler?.ActualRequestMessage, correlationId);
        }
Пример #32
0
        private async Task <(HttpRequestMessage HttpRequest, Guid Correlationid)> RunAcquireTokenInteractiveAsync(
            AcquireTokenInteractiveOutcome outcome)
        {
            MockHttpMessageHandler tokenRequestHandler = null;
            Guid correlationId = default;

            switch (outcome)
            {
            case AcquireTokenInteractiveOutcome.Success:
                MsalMockHelpers.ConfigureMockWebUI(
                    _app.ServiceBundle.PlatformProxy,
                    AuthorizationResult.FromUri(_app.AppConfig.RedirectUri + "?code=some-code"));
                tokenRequestHandler = _harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost();
                var authResult = await _app
                                 .AcquireTokenInteractive(TestConstants.s_scope)
                                 .ExecuteAsync()
                                 .ConfigureAwait(false);

                correlationId = authResult.CorrelationId;
                break;

            case AcquireTokenInteractiveOutcome.AuthorizationError:
                correlationId = Guid.NewGuid();

                var ui = Substitute.For <IWebUI>();
                ui.UpdateRedirectUri(Arg.Any <Uri>()).Returns(new Uri("http://localhost:1234"));
                ui.AcquireAuthorizationAsync(null, null, null, default).ThrowsForAnyArgs(
                    new MsalClientException("user_cancelled"));
                MsalMockHelpers.ConfigureMockWebUI(_app.ServiceBundle.PlatformProxy, ui);

                var ex = await AssertException.TaskThrowsAsync <MsalClientException>(() =>
                                                                                     _app
                                                                                     .AcquireTokenInteractive(TestConstants.s_scope)
                                                                                     .WithCorrelationId(correlationId)
                                                                                     .ExecuteAsync())
                         .ConfigureAwait(false);

                break;

            case AcquireTokenInteractiveOutcome.AADUnavailableError:
                correlationId = Guid.NewGuid();

                MsalMockHelpers.ConfigureMockWebUI(
                    _app.ServiceBundle.PlatformProxy,
                    AuthorizationResult.FromUri(_app.AppConfig.RedirectUri + "?code=some-code"));

                tokenRequestHandler = new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateFailureMessage(
                        System.Net.HttpStatusCode.GatewayTimeout, "gateway timeout")
                };
                var tokenRequestHandler2 = new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateFailureMessage(
                        System.Net.HttpStatusCode.GatewayTimeout, "gateway timeout")
                };

                // 2 of these are needed because MSAL has a "retry once" policy for 5xx errors
                _harness.HttpManager.AddMockHandler(tokenRequestHandler2);
                _harness.HttpManager.AddMockHandler(tokenRequestHandler);

                var serviceEx = await AssertException.TaskThrowsAsync <MsalServiceException>(() =>
                                                                                             _app
                                                                                             .AcquireTokenInteractive(TestConstants.s_scope)
                                                                                             .WithCorrelationId(correlationId)
                                                                                             .ExecuteAsync())
                                .ConfigureAwait(false);

                break;

            default:
                throw new NotImplementedException();
            }

            Assert.AreEqual(0, _harness.HttpManager.QueueSize);

            return(tokenRequestHandler?.ActualRequestMessage, correlationId);
        }
        public static IOrganisationsApiClient Setup(Mock <ILogger <OrganisationsApiClient> > mockedApiClientLogger)
        {
            var standardOrganisartionSummaries = new List <OrganisationStandardSummary>
            {
                new OrganisationStandardSummary
                {
                    StandardCode = 93
                },
                new OrganisationStandardSummary
                {
                    StandardCode = 92
                },
                new OrganisationStandardSummary
                {
                    StandardCode = 91
                }
            };


            var standards = new List <OrganisationStandardSummary>
            {
                new OrganisationStandardSummary
                {
                    Id = 91
                },
                new OrganisationStandardSummary
                {
                    Id = 92
                },
                new OrganisationStandardSummary
                {
                    Id = 93
                },
                new OrganisationStandardSummary
                {
                    Id = 94
                },
                new OrganisationStandardSummary
                {
                    Id = 95
                },
            };

            var mockHttp = new MockHttpMessageHandler();

            var clientlocal = mockHttp.ToHttpClient();

            clientlocal.BaseAddress = new Uri("https://test.local/");

            mockHttp.When($"/api/ao/assessment-organisations/EPA00001/standards")
            .Respond("application/json", JsonConvert.SerializeObject(standardOrganisartionSummaries));

            var webConfigMock = new Mock <IWebConfiguration>();
            var hostMock      = new Mock <IHostingEnvironment>();

            hostMock
            .Setup(m => m.EnvironmentName)
            .Returns(EnvironmentName.Development);

            var mockTokenService = new Mock <TokenService>(webConfigMock.Object, hostMock.Object, false);

            var apiBaseLogger = new Mock <ILogger <ApiClientBase> >();

            var apiClient = new OrganisationsApiClient(clientlocal, mockTokenService.Object, apiBaseLogger.Object);

            return(apiClient);
        }
Пример #34
0
        public async Task SearchAsync()
        {
            // Arrange
            var listId     = 4;
            var conditions = new[]
            {
                new SearchCondition
                {
                    Field           = "last_name",
                    Value           = "Miller",
                    Operator        = ConditionOperator.Equal,
                    LogicalOperator = LogicalOperator.None
                },
                new SearchCondition
                {
                    Field           = "last_click",
                    Value           = "01/02/2015",
                    Operator        = ConditionOperator.GreatherThan,
                    LogicalOperator = LogicalOperator.And
                },
                new SearchCondition
                {
                    Field           = "clicks.campaign_identifier",
                    Value           = "513",
                    Operator        = ConditionOperator.GreatherThan,
                    LogicalOperator = LogicalOperator.Or
                }
            };
            var apiResponse = @"{
				'recipients': [
					{
						'created_at': 1422313607,
						'email': '*****@*****.**',
						'first_name': null,
						'id': 'YUBh',
						'last_clicked': 12345,
						'last_emailed': null,
						'last_name': 'Miller',
						'last_opened': null,
						'updated_at': 1422313790,
						'custom_fields': [
							{
								'id': 23,
								'name': 'pet',
								'value': 'Indiana',
								'type': 'text'
							},
							{
								'id': 24,
								'name': 'age',
								'value': '43',
								'type': 'number'
							}
						]
					}
				]
			}"            ;

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Post, Utils.GetSendGridApiUri(ENDPOINT, "search")).Respond("application/json", apiResponse);

            var client   = Utils.GetFluentClient(mockHttp);
            var contacts = new Contacts(client);

            // Act
            var result = await contacts.SearchAsync(conditions, listId, null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
            result.Length.ShouldBe(1);
            result[0].Email.ShouldBe("*****@*****.**");
            result[0].CustomFields.Length.ShouldBe(2);
            result[0].CustomFields[0].Name.ShouldBe("pet");
            ((Field <string>)result[0].CustomFields[0]).Value.ShouldBe("Indiana");
            result[0].CustomFields[1].Name.ShouldBe("age");
            ((Field <long>)result[0].CustomFields[1]).Value.ShouldBe(43);
        }
Пример #35
0
        public async Task TestGetDevicesAndLastOutputValues()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.When($"{MockDigitalstromConnection.BaseUri}/json/property/query")
            .WithExactQueryString($"query=/apartment/zones/*(ZoneID)/devices/*(dSID)/status(lastChanged)/outputs/*(value,targetValue)&token={MockDigitalstromConnection.AppToken}")
            .Respond("application/json", @"{
                                  ""result"":
                                  {
                                      ""zones"":
                                      [
                                          {
                                              ""ZoneID"": 32027,
                                              ""devices"":
                                              [
                                                  {
                                                      ""dSID"": ""1337234200000e80deadbeef"",
                                                      ""status"":
                                                      [
                                                          {
                                                              ""lastChanged"": ""\""2019-01-15T03:56:29.800Z\"""",
                                                              ""outputs"":
                                                              [
                                                                  {
                                                                      ""value"": 0,
                                                                      ""targetValue"": 0
                                                                  }
                                                              ]
                                                          }
                                                      ]
                                                  },
                                                  {
                                                      ""dSID"": ""4242000aaa000fa0deadbeef"",
                                                      ""status"":
                                                      [
                                                          {
                                                              ""lastChanged"": ""\""2019-01-18T17:15:30.249Z\"""",
                                                              ""outputs"":
                                                              [
                                                                  {
                                                                      ""value"": 21.6404131546947,
                                                                      ""targetValue"": 21.6404131546947
                                                                  }
                                                              ]
                                                          }
                                                      ]
                                                  },
                                                  {
                                                      ""dSID"": ""f00f000aaa000120beefbeef"",
                                                      ""status"": []
                                                  }
                                              ]
                                          }
                                      ]
                                  },
                                  ""ok"": true
                              }");

            using var dsApiClient = new DigitalstromDssClient(mockHttp.AddAuthMock().ToMockProvider());

            var zonesScenes = await dsApiClient.GetDevicesAndLastOutputValues();

            Assert.NotEmpty(zonesScenes.Zones);

            Assert.Equal(DateTime.Parse("2019-01-15T03:56:29.800Z"), zonesScenes.Zones[0].Devices[0].Status[0].LastChangedTime);
            Assert.Equal(0d, zonesScenes.Zones[0].Devices[0].Status[0].Outputs[0].Value);
            Assert.Equal(0d, zonesScenes.Zones[0].Devices[0].Status[0].Outputs[0].TargetValue);
            Assert.Equal(21.6404131546947d, zonesScenes.Zones[0].Devices[1].Status[0].Outputs[0].Value);
            Assert.Equal(21.6404131546947d, zonesScenes.Zones[0].Devices[1].Status[0].Outputs[0].TargetValue);
            Assert.Empty(zonesScenes.Zones[0].Devices[2].Status);
        }
Пример #36
0
        public void SendRequestThrowsIfResponseIsBad()
        {
            var messageHandler = new MockHttpMessageHandler();
            var httpClient = new HttpClient(messageHandler) { BaseAddress = new Uri("http://api.com") };
            var requester = new PublicRequester(httpClient);

            var requestInfo = new RequestInfo(HttpMethod.Get, "foo");

            var responseMessage = new HttpResponseMessage();
            responseMessage.Headers.Add("Foo", "bar");
            responseMessage.StatusCode = HttpStatusCode.NotFound;
            responseMessage.Content = new StringContent("hello");

            messageHandler.ResponseMessage = Task.FromResult(responseMessage);

            var aggregateException = Assert.Throws<AggregateException>(() => requester.SendRequestAsync(requestInfo).Wait());
            var e = Assert.IsType<ApiException>(aggregateException.InnerException);

            Assert.Equal(HttpStatusCode.NotFound, e.StatusCode);
            Assert.True(e.Headers.Contains("Foo"));
            Assert.True(e.HasContent);
            Assert.Equal("hello", e.Content);
        }
        private AdaptiveDialog CreateQnAMakerActionDialog(MockHttpMessageHandler mockHttp)
        {
            var client = new HttpClient(mockHttp);

            var rootDialog = new AdaptiveDialog("outer")
            {
                AutoEndDialog = false,
                Recognizer    = new QnAMakerRecognizer
                {
                    KnowledgeBaseId = KnowledgeBaseId,
                    HostName        = Hostname,
                    EndpointKey     = EndpointKey,
                    HttpClient      = client
                },
                Triggers = new List <OnCondition>
                {
                    new OnQnAMatch
                    {
                        Actions = new List <Dialog>
                        {
                            new SendActivity
                            {
                                Activity = new ActivityTemplate("${@answer}")
                            },
                            new AssertCondition
                            {
                                Condition   = "count(turn.recognized.entities.answer) == 1",
                                Description = "If there is a match there should only be 1 answer"
                            },
                            new AssertCondition
                            {
                                Condition   = "turn.recognized.entities.$instance.answer[0].startIndex == 0",
                                Description = "startIndex should be 0",
                            },
                            new AssertCondition
                            {
                                Condition   = "turn.recognized.entities.$instance.answer[0].endIndex != null",
                                Description = "endIndex should not be null",
                            },
                            new AssertCondition
                            {
                                Condition   = "turn.recognized.answers[0].answer != null",
                                Description = "There should be answers object"
                            },
                            new SendActivity
                            {
                                Activity = new ActivityTemplate("done")
                            }
                        }
                    },
                    new OnIntent
                    {
                        Intent  = "DeferToRecognizer_xxx",
                        Actions = new List <Dialog>
                        {
                            new SendActivity
                            {
                                Activity = new ActivityTemplate("DeferToRecognizer_xxx")
                            }
                        }
                    },
                    new OnUnknownIntent
                    {
                        Actions = new List <Dialog>
                        {
                            new SendActivity("Wha?")
                        }
                    }
                }
            };

            return(rootDialog);
        }
Пример #38
0
        public void AllowsPathWithLeadingSlash()
        {
            var messageHandler = new MockHttpMessageHandler();
            var httpClient = new HttpClient(messageHandler) { BaseAddress = new Uri("http://api.example.com/base/") };
            var requester = new PublicRequester(httpClient);

            var requestInfo = new RequestInfo(HttpMethod.Get, "/foo");

            messageHandler.ResponseMessage = Task.FromResult(new HttpResponseMessage());

            var response = requester.SendRequestAsync(requestInfo).Result;
            Assert.Equal("http://api.example.com/base/foo", messageHandler.Request.RequestUri.ToString());
        }
Пример #39
0
        public void CanHandleValidGetWorldByIdResponse()
        {
            MockHttpMessageHandler.SetResponse(new JObject(
                                                   new JProperty("id", "some world id"),
                                                   new JProperty("name", "some world name"),
                                                   new JProperty("description", "some world description"),
                                                   new JProperty("featured", false),
                                                   new JProperty("authorId", "some author id"),
                                                   new JProperty("authorName", "some author name"),
                                                   new JProperty("totalLikes", 420),
                                                   new JProperty("totalVisits", 1337),
                                                   new JProperty("capacity", (short)42),
                                                   new JProperty("tags", new JArray("tag 1", "tag 2")),
                                                   new JProperty("releaseStatus", "public"),
                                                   new JProperty("imageUrl", "https://unit.test/imageUrl.jpg"),
                                                   new JProperty("thumbnailImageUrl", "https://unit.test/thumbnailImageUrl.jpg"),
                                                   new JProperty("assetUrl", "https://unit.test/assetUrl.asset"),
                                                   new JProperty("pluginUrl", "https://unit.test/pluginUrl.plugin"),
                                                   new JProperty("unityPackageUrl", "https://unit.test/unityPackageUrl.unityPackage"),
                                                   new JProperty("namespace", "some namespace presumably"),
                                                   new JProperty("unityPackageUpdated", false),
                                                   new JProperty("unityPackages", new JArray(
                                                                     new JObject(
                                                                         new JProperty("id", "some unity package id"),
                                                                         new JProperty("assetUrl", "https://unit.test/1/assetUrl.asset"),
                                                                         new JProperty("pluginUrl", "https://unit.test/1/pluginUrl.plugin"),
                                                                         new JProperty("unityVersion", "7"),
                                                                         new JProperty("unitySortNumber", 9001),
                                                                         new JProperty("assetVersion", 1),
                                                                         new JProperty("platform", "some platform"),
                                                                         new JProperty("created_at", "some date")))),
                                                   new JProperty("isSecure", false),
                                                   new JProperty("isLockdown", false),
                                                   new JProperty("version", 2),
                                                   new JProperty("organization", "some organization"),
                                                   new JProperty("instances", new List <JArray> {
                new JArray("some instance id", 2)
            }),
                                                   new JProperty("occupants", 4)));

            var api    = new WorldApi();
            var result = api.Get("some world id").Result;

            result.id.Should().Be("some world id");
            result.name.Should().Be("some world name");
            result.description.Should().Be("some world description");
            result.featured.Should().BeFalse();
            result.authorId.Should().Be("some author id");
            result.authorName.Should().Be("some author name");
            result.totalLikes.Should().Be(420);
            result.totalVisits.Should().Be(1337);
            result.capacity.Should().Be(42);
            result.tags.Should().HaveCount(2);
            result.tags[0].Should().Be("tag 1");
            result.tags[1].Should().Be("tag 2");
            result.releaseStatus.Should().Be(ReleaseStatus.Public);
            result.imageUrl.Should().Be("https://unit.test/imageUrl.jpg");
            result.thumbnailImageUrl.Should().Be("https://unit.test/thumbnailImageUrl.jpg");
            result.assetUrl.Should().Be("https://unit.test/assetUrl.asset");
            result.pluginUrl.Should().Be("https://unit.test/pluginUrl.plugin");
            result.unityPackageUrl.Should().Be("https://unit.test/unityPackageUrl.unityPackage");
            result.nameSpace.Should().Be("some namespace presumably");
            result.unityPackageUpdated.Should().BeFalse();
            result.unityPackages.Should().HaveCount(1);
            result.unityPackages[0].id.Should().Be("some unity package id");
            result.unityPackages[0].assetUrl.Should().Be("https://unit.test/1/assetUrl.asset");
            result.unityPackages[0].unityVersion.Should().Be("7");
            result.unityPackages[0].unitySortNumber.Should().Be(9001);
            result.unityPackages[0].assetVersion.Should().Be(1);
            result.unityPackages[0].platform.Should().Be("some platform");
            result.unityPackages[0].created_at.Should().Be(new DateTime());
            result.isSecure.Should().BeFalse();
            result.isLockdown.Should().BeFalse();
            result.version.Should().Be(2);
            result.organization.Should().Be("some organization");
            result.instances.Should().HaveCount(1);
            result.instances[0].id.Should().Be("some instance id");
            result.instances[0].occupants.Should().Be(2);
            result.occupants.Should().Be(4);
        }
        public void TestInitialize()
        {
            _handler = new MockHttpMessageHandler();

            _client = new MailjetClient("api-key", "api-secret-key", _handler);
        }
Пример #41
0
        public void CanHandleValidWorldInstanceResponse()
        {
            MockHttpMessageHandler.SetResponse(new JObject(
                                                   new JProperty("id", "some instance id"),
                                                   new JProperty("private", new JArray(
                                                                     new JObject(
                                                                         new JProperty("id", "some private user id"),
                                                                         new JProperty("username", "some private username"),
                                                                         new JProperty("displayName", "some private display name"),
                                                                         new JProperty("currentAvatarImageUrl", "https://unit.test/privateAvatarImageUrl.jpg"),
                                                                         new JProperty("currentAvatarThumbnailImageUrl", "https://unit.test/privateAvatarThumbnailImageUrl.jpg"),
                                                                         new JProperty("tags", new JArray("tag 1", "tag 2")),
                                                                         new JProperty("developerType", "some private developer type"),
                                                                         new JProperty("status", "some private status"),
                                                                         new JProperty("statusDescription", "some private status description"),
                                                                         new JProperty("networkSessionId", "some private network session id")))),
                                                   new JProperty("friends", new JArray(
                                                                     new JObject(
                                                                         new JProperty("id", "some friend user id"),
                                                                         new JProperty("username", "some friend username"),
                                                                         new JProperty("displayName", "some friend display name"),
                                                                         new JProperty("currentAvatarImageUrl", "https://unit.test/friendAvatarImageUrl.jpg"),
                                                                         new JProperty("currentAvatarThumbnailImageUrl", "https://unit.test/friendAvatarThumbnailImageUrl.jpg"),
                                                                         new JProperty("tags", new JArray("tag 1", "tag 2")),
                                                                         new JProperty("developerType", "some friend developer type"),
                                                                         new JProperty("status", "some friend status"),
                                                                         new JProperty("statusDescription", "some friend status description"),
                                                                         new JProperty("networkSessionId", "some friend network session id")))),
                                                   new JProperty("users", new JArray(
                                                                     new JObject(
                                                                         new JProperty("id", "some user id"),
                                                                         new JProperty("username", "some username"),
                                                                         new JProperty("displayName", "some display name"),
                                                                         new JProperty("currentAvatarImageUrl", "https://unit.test/currentAvatarImageUrl.jpg"),
                                                                         new JProperty("currentAvatarThumbnailImageUrl", "https://unit.test/currentAvatarThumbnailImageUrl.jpg"),
                                                                         new JProperty("tags", new JArray("tag 1", "tag 2")),
                                                                         new JProperty("developerType", "some developer type"),
                                                                         new JProperty("status", "some status"),
                                                                         new JProperty("statusDescription", "some status description"),
                                                                         new JProperty("networkSessionId", "some network session id")))),
                                                   new JProperty("name", "some name")));

            var api    = new WorldApi();
            var result = api.GetInstance("some world id", "some instance id").Result;

            result.id.Should().Be("some instance id");
            result.privateUsers.Should().HaveCount(1);
            result.privateUsers[0].id.Should().Be("some private user id");
            result.privateUsers[0].username.Should().Be("some private username");
            result.privateUsers[0].displayName.Should().Be("some private display name");
            result.privateUsers[0].currentAvatarImageUrl.Should().Be("https://unit.test/privateAvatarImageUrl.jpg");
            result.privateUsers[0].currentAvatarThumbnailImageUrl.Should().Be("https://unit.test/privateAvatarThumbnailImageUrl.jpg");
            result.privateUsers[0].tags.Should().HaveCount(2);
            result.privateUsers[0].tags[0].Should().Be("tag 1");
            result.privateUsers[0].tags[1].Should().Be("tag 2");
            result.privateUsers[0].developerType.Should().Be("some private developer type");
            result.privateUsers[0].status.Should().Be("some private status");
            result.privateUsers[0].statusDescription.Should().Be("some private status description");
            result.privateUsers[0].networkSessionId.Should().Be("some private network session id");
            result.friends.Should().HaveCount(1);
            result.friends[0].id.Should().Be("some friend user id");
            result.friends[0].username.Should().Be("some friend username");
            result.friends[0].displayName.Should().Be("some friend display name");
            result.friends[0].currentAvatarImageUrl.Should().Be("https://unit.test/friendAvatarImageUrl.jpg");
            result.friends[0].currentAvatarThumbnailImageUrl.Should().Be("https://unit.test/friendAvatarThumbnailImageUrl.jpg");
            result.friends[0].tags.Should().HaveCount(2);
            result.friends[0].tags[0].Should().Be("tag 1");
            result.friends[0].tags[1].Should().Be("tag 2");
            result.friends[0].developerType.Should().Be("some friend developer type");
            result.friends[0].status.Should().Be("some friend status");
            result.friends[0].statusDescription.Should().Be("some friend status description");
            result.friends[0].networkSessionId.Should().Be("some friend network session id");
            result.users.Should().HaveCount(1);
            result.users[0].id.Should().Be("some user id");
            result.users[0].username.Should().Be("some username");
            result.users[0].displayName.Should().Be("some display name");
            result.users[0].currentAvatarImageUrl.Should().Be("https://unit.test/currentAvatarImageUrl.jpg");
            result.users[0].currentAvatarThumbnailImageUrl.Should().Be("https://unit.test/currentAvatarThumbnailImageUrl.jpg");
            result.users[0].tags.Should().HaveCount(2);
            result.users[0].tags[0].Should().Be("tag 1");
            result.users[0].tags[1].Should().Be("tag 2");
            result.users[0].developerType.Should().Be("some developer type");
            result.users[0].status.Should().Be("some status");
            result.users[0].statusDescription.Should().Be("some status description");
            result.users[0].networkSessionId.Should().Be("some network session id");
            result.name.Should().Be("some name");
        }
Пример #42
0
        public async Task TestGetTemperatureControlConfig()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.When($"{MockDigitalstromConnection.BaseUri}/json/apartment/getTemperatureControlConfig")
            .WithExactQueryString($"token={MockDigitalstromConnection.AppToken}")
            .Respond("application/json", @"{
                                  ""result"":
                                  {
                                      ""zones"": [
                                          {
                                              ""id"": 1,
                                              ""name"": ""RoomWithoutControl"",
                                              ""ControlMode"": 0
                                          },
                                          {
                                              ""id"": 32001,
                                              ""name"": ""RoomFollowing"",
                                              ""ControlMode"": 2,
                                              ""ReferenceZone"": 32027,
                                              ""CtrlOffset"": 0
                                          },
                                          {
                                              ""id"": 32027,
                                              ""name"": ""RoomWithControl"",
                                              ""ControlMode"": 1,
                                              ""EmergencyValue"": 75,
                                              ""CtrlKp"": 5,
                                              ""CtrlTs"": 1,
                                              ""CtrlTi"": 240,
                                              ""CtrlKd"": 0,
                                              ""CtrlImin"": -13.325000000000001,
                                              ""CtrlImax"": 13.325000000000001,
                                              ""CtrlYmin"": 0,
                                              ""CtrlYmax"": 100,
                                              ""CtrlAntiWindUp"": true
                                          }
                                      ]
                                  },
                                  ""ok"": true
                              }");

            using var dsApiClient = new DigitalstromDssClient(mockHttp.AddAuthMock().ToMockProvider());

            var result = await dsApiClient.GetTemperatureControlConfig();

            Assert.Equal(0, result.Zones[0].ControlMode);
            Assert.Null(result.Zones[0].ReferenceZone);
            Assert.Null(result.Zones[0].CtrlOffset);

            Assert.Equal(2, result.Zones[1].ControlMode);
            Assert.Equal(32027, result.Zones[1].ReferenceZone);
            Assert.Equal(0, result.Zones[1].CtrlOffset);
            Assert.Null(result.Zones[1].CtrlKp);

            Assert.Equal(32027, (int)result.Zones[2].Id);
            Assert.Equal(1, result.Zones[2].ControlMode);
            Assert.Equal(75, result.Zones[2].EmergencyValue);
            Assert.Equal(5, result.Zones[2].CtrlKp);
            Assert.Equal(1, result.Zones[2].CtrlTs);
            Assert.Equal(240, result.Zones[2].CtrlTi);
            Assert.Null(result.Zones[2].ReferenceZone);
        }
Пример #43
0
        public static void CreateTestHost(string userName,
                                          IEnumerable <Claim> claims,
                                          string url,
                                          TestServer sut,
                                          ITestOutputHelper testOutputHelper,
                                          out TestHost host,
                                          out MockHttpMessageHandler mockHttp,
                                          bool useJsRuntime = false)
        {
            var navigationInterceptionMock = new Mock <INavigationInterception>();

            host = new TestHost();
            var httpMock = host.AddMockHttp();

            mockHttp = httpMock;
            var localizerMock = new Mock <ISharedStringLocalizerAsync>();

            localizerMock.Setup(m => m[It.IsAny <string>()]).Returns((string key) => new LocalizedString(key, key));
            localizerMock.Setup(m => m[It.IsAny <string>(), It.IsAny <object[]>()]).Returns((string key, object[] p) => new LocalizedString(key, string.Format(key, p)));

            host.ConfigureServices(services =>
            {
                var httpClient       = sut.CreateClient();
                var appConfiguration = CreateApplicationConfiguration(httpClient);

                WebAssemblyHostBuilderExtensions.ConfigureServices(services, appConfiguration, appConfiguration.Get <Settings>(), httpClient.BaseAddress.ToString());

                sut.Services.GetRequiredService <TestUserService>()
                .SetTestUser(true, claims.Select(c => new Claim(c.Type, c.Value)));

                services
                .AddLogging(configure =>
                {
                    configure.AddProvider(new TestLoggerProvider(testOutputHelper));
                })
                .AddTransient(p => sut.CreateHandler())
                .AddIdentityServer4AdminHttpStores(p =>
                {
                    var client = new HttpClient(new BaseAddressAuthorizationMessageHandler(p.GetRequiredService <IAccessTokenProvider>(),
                                                                                           p.GetRequiredService <NavigationManager>())
                    {
                        InnerHandler = sut.CreateHandler()
                    })
                    {
                        BaseAddress = new Uri(httpClient.BaseAddress, "api")
                    };
                    return(Task.FromResult(client));
                })
                .AddSingleton(p => new TestNavigationManager(uri: url))
                .AddSingleton <NavigationManager>(p => p.GetRequiredService <TestNavigationManager>())
                .AddSingleton(navigationInterceptionMock.Object)
                .AddSingleton(navigationInterceptionMock)
                .AddSingleton(p => new Settings
                {
                    ApiBaseUrl = appConfiguration["ApiBaseUrl"]
                })
                .AddSingleton(localizerMock.Object)
                .AddSingleton(localizerMock)
                .AddTransient(p => new HttpClient(sut.CreateHandler()))
                .AddSingleton <SignOutSessionStateManager, FakeSignOutSessionStateManager>()
                .AddSingleton <IAccessTokenProviderAccessor, AccessTokenProviderAccessor>()
                .AddSingleton <IAccessTokenProvider>(p => p.GetRequiredService <FakeAuthenticationStateProvider>())
                .AddSingleton <AuthenticationStateProvider>(p => p.GetRequiredService <FakeAuthenticationStateProvider>())
                .AddSingleton(p => new FakeAuthenticationStateProvider(
                                  userName,
                                  claims))
                .AddScoped <LazyAssemblyLoader>()
                .AddHttpClient("oidc")
                .ConfigureHttpClient(httpClient =>
                {
                    var apiUri             = new Uri(httpClient.BaseAddress, "api");
                    httpClient.BaseAddress = apiUri;
                })
                .AddHttpMessageHandler(() => new FakeDelegatingHandler(sut.CreateHandler()));

                if (useJsRuntime)
                {
                    services.AddSingleton(new JSRuntimeImpl())
                    .AddSingleton <IJSRuntime>(p => p.GetRequiredService <JSRuntimeImpl>());
                }
                else
                {
                    var jsRuntimeMock = new Mock <IJSRuntime>();
                    services.AddSingleton(jsRuntimeMock)
                    .AddSingleton(jsRuntimeMock.Object);
                }
            });
        }