예제 #1
0
        public void ShouldParseDescriptorGettingItById()
        {
            var httpClientMock = new MockMessageHandler(
                new {
                    _id = "sourcedb_to_testdb",
                    _rev = "6-011f9010bf4edcb7312131b1d70fb060",
                    target = "http://example2.com/sourcedb",
                    source = "testdb",
                    continuous = true,
                    create_target = true,
                    _replication_state = "triggered",
                    _replication_state_time = "2011-09-07T14:11:19+04:00",
                    _replication_id = "cef1a54d4948bffcf9cb4d53591c5f5f"
                }.ToJsonObject());

            var descriptor = GetCouchApi(httpClientMock).Replicator.Synchronously.RequestDescriptorById("sourcedb_to_testdb");

            Assert.Equal("sourcedb_to_testdb", descriptor.Id);
            Assert.Equal("6-011f9010bf4edcb7312131b1d70fb060", descriptor.Revision);
            Assert.Equal("testdb", descriptor.Source.ToString());
            Assert.Equal("http://example2.com/sourcedb", descriptor.Target.ToString());
            Assert.True(descriptor.Continuous);
            Assert.True(descriptor.CreateTarget);
            Assert.Equal(ReplicationState.Triggered, descriptor.ReplicationState);
            Assert.Equal(new DateTime(2011, 9, 7, 10, 11, 19, DateTimeKind.Utc), descriptor.ReplicationStartTime);
            Assert.Equal("cef1a54d4948bffcf9cb4d53591c5f5f", descriptor.ReplicationId);
        }
예제 #2
0
        public void ShouldMapTipicalResponseToGetAllQuery()
        {
            var handler = new MockMessageHandler(new
            {
                total_rows = 2,
                offset = 1,
                rows = new [] {
                    new {
                        key = new object[] { "key", 0 },
                        value = "some string",
                        id = "doc1",
                        doc = new { _id = "doc1" }
                    }
                }
            }.ToJsonObject());

            var couchApi = GetDatabaseApi(handler);
            var result = couchApi.Synchronously.Query(
                new ViewQuery {
                    ViewName = "_all_docs",
                    Key = new object[] {"key", 0},
                    Skip = 1,
                    IncludeDocs = true
                });

            Assert.NotNull(result);
            Assert.Equal(2, result.TotalCount);
            Assert.Equal(1, result.Count);
            var firstRow = result.Rows.First();
            Assert.Equal(new object[] { "key", 0 }.ToJsonFragment(),	firstRow.Key);
            Assert.Equal("\"some string\"",														firstRow.Value.ToString());
            Assert.Equal("doc1",																			firstRow.DocumentId);
            Assert.Equal(new { _id = "doc1" }.ToDocument(),						firstRow.Document);
        }
        public void ShouldGetDocumentFromDbByIdCorrectly()
        {
            var handler = new MockMessageHandler(
                new {
                    _id = "doc1",
                    _rev = "1-1a517022a0c2d4814d51abfedf9bfee7",
                    name = "Стас Гиркин"
                }.ToJsonObject());

            var databaseApi = GetDatabaseApi(handler);
            var result = databaseApi.Synchronously.RequestDocument("doc1");

            Assert.Equal("http://example.com:5984/testdb/doc1", handler.Request.RequestUri.ToString());
            Assert.Equal(HttpMethod.Get, handler.Request.Method);
            Assert.Null(handler.Request.Content);
            Assert.Equal(
                new
                {
                    _id = "doc1",
                    _rev = "1-1a517022a0c2d4814d51abfedf9bfee7",
                    name = "Стас Гиркин"
                }.ToDocument(),
                result
            );
        }
        public void ShouldNotDoNetworkingIfNoWorkToDo()
        {
            var handler = new MockMessageHandler();
            CreateCouchApi(handler).Db("testdb").BulkUpdate(x => { });

            Assert.Null(handler.Request);
        }
        public void ShouldThrowOnNullArguments()
        {
            var httpMock = new MockMessageHandler(new { ok = true }.ToJsonObject());
            var databaseApi = CreateCouchApi(httpMock).Db("testdb");

            Assert.Throws<ArgumentNullException>(() => databaseApi.Synchronously.CopyDocument("doc1", null, null));
            Assert.Throws<ArgumentNullException>(() => databaseApi.Synchronously.CopyDocument(null, null, "doc2"));
        }
        public void ShouldReturnNullIfNoDocumentFound()
        {
            var handler = new MockMessageHandler(new HttpResponseMessage(HttpStatusCode.NotFound));
            IDatabaseApi databaseApi = GetDatabaseApi(handler);

            var version = databaseApi.Synchronously.RequestLastestDocumentRevision("doc1");
            Assert.Null(version);
        }
        public void ShouldReturnNullIfAttachmentHaveNotFoundOnExistingDocument()
        {
            var httpMock = new MockMessageHandler(
                HttpStatusCode.NotFound,
                new { error = "not_found", reason = "Document is missing attachment" }.ToJsonObject());
            var databaseApi = CreateCouchApi(httpMock).Db("testdb");

            Assert.Null(databaseApi.Synchronously.RequestAttachment("attachment1", "doc1", "rev1"));
        }
 public void ShouldThrowIfDatabaseMissing()
 {
     var httpClient = new MockMessageHandler(new HttpResponseMessage(HttpStatusCode.NotFound) {
         Content = new JsonContent("{\"error\":\"not_found\",\"reason\":\"no_db_file\"}")
     });
     Assert.Throws<DatabaseMissingException>(
         () => CreateCouchApi(httpClient).Db("testdb").Synchronously.CopyDocument("doc1", null, "doc2")
     );
 }
 public void ShouldThrowOnBadRequest()
 {
     var httpClient = new MockMessageHandler(new HttpResponseMessage(HttpStatusCode.BadRequest) {
         Content = new JsonContent("{\"error\":\"bad_request\",\"reason\":\"unknown error\"}")
     });
     Assert.Throws<CouchCommunicationException>(
         () => CreateCouchApi(httpClient).Db("testdb").Synchronously.UpdateSecurityDescriptor(new DatabaseSecurityDescriptor())
     );
 }
        public void ShouldThrowCouchCommunicationExceptionOn500()
        {
            var httpMock = new MockMessageHandler(HttpStatusCode.InternalServerError, string.Empty, MediaType.Json);
            var databaseApi = CreateCouchApi(httpMock).Db("testdb");

            Assert.Throws<CouchCommunicationException>(
                () => databaseApi.Synchronously.SaveAttachment(new Attachment("attachment1"), "doc1", "rev1")
            );
        }
        public void ShouldThrowStaleObjectStateExceptionOnConflict()
        {
            var httpMock = new MockMessageHandler(
                HttpStatusCode.Conflict, new { error = "conflict", reason = "Document update conflict." }.ToJsonObject());
            var databaseApi = CreateCouchApi(httpMock).Db("testdb");

            Assert.Throws<StaleObjectStateException>(
                () => databaseApi.Synchronously.RequestAttachment("attachment1", "doc1", "rev1")
            );
        }
        public void ShouldThrowDocumentNotFoundException()
        {
            var httpMock = new MockMessageHandler(
                HttpStatusCode.NotFound, new { error = "not_found", reason = "missing" }.ToJsonObject());
            var databaseApi = CreateCouchApi(httpMock).Db("testdb");

            Assert.Throws<DocumentNotFoundException>(
                () => databaseApi.Synchronously.RequestAttachment("attachment1", "doc1", "rev1")
            );
        }
        public void ShouldThrowOnNullArguments()
        {
            var handler = new MockMessageHandler(new { ok = true }.ToJsonObject());
            IDatabaseApi databaseApi = CreateCouchApi(handler).Db("testdb");

            Assert.Throws<ArgumentNullException>(
                () => databaseApi.Synchronously.DeleteDocument(docId: "doc1", revision: null));
            Assert.Throws<ArgumentNullException>(
                () => databaseApi.Synchronously.DeleteDocument(docId: null, revision: "1-1a517022a0c2d4814d51abfedf9bfee7"));
        }
        public void ShouldEscapeDocumentId()
        {
            var httpMock = new MockMessageHandler(new
                {
                    _id = "docs/doc1",
                    _rev = "1-1a517022a0c2d4814d51abfedf9bfee7",
                    name = "Стас Гиркин"
                }.ToJsonObject());
            var databaseApi = GetDatabaseApi(httpMock);
            databaseApi.Synchronously.RequestDocument("docs/doc1");

            Assert.Equal("http://example.com:5984/testdb/docs%2Fdoc1", httpMock.Request.RequestUri.ToString());
        }
        public void ShouldGetLastestDocumentRevisionCorrectly()
        {
            var response = ConstructOkResponse("1-1a517022a0c2d4814d51abfedf9bfee7");

            var handler = new MockMessageHandler(response);
            IDatabaseApi databaseApi = GetDatabaseApi(handler);
            var revision = databaseApi.Synchronously.RequestLastestDocumentRevision("doc1");

            Assert.Equal("http://example.com:5984/testdb/doc1", handler.Request.RequestUri.ToString());
            Assert.Equal(HttpMethod.Head, handler.Request.Method);
            Assert.Equal(null, handler.Request.Content);
            Assert.Equal("1-1a517022a0c2d4814d51abfedf9bfee7", revision);
        }
        public void ShouldThrowCouchCommunicationExceptionOnWebExceptionWhenSavingToDb()
        {
            var webExeption = new WebException("Something wrong detected");
            var httpClientMock = new MockMessageHandler(webExeption);
            var couchApi = GetDatabaseApi(httpClientMock);

            var couchCommunicationException =
                Assert.Throws<CouchCommunicationException>(
                    () => couchApi.Synchronously.SaveDocument(new { _id = "doc1" }.ToDocument()));

            Assert.Equal("Something wrong detected", couchCommunicationException.Message);
            Assert.Equal(webExeption, couchCommunicationException.InnerException);
        }
        public void ShouldThrowCouchCommunicationExceptionOnWebExceptionWhenUpdatingDocumentInDb()
        {
            var webExeption = new WebException("Something wrong detected");
            var handler = new MockMessageHandler(webExeption);

            var databaseApi = GetDatabaseApi(handler);

            var couchCommunicationException =
                Assert.Throws<CouchCommunicationException>(
                    () => databaseApi.Synchronously.RequestLastestDocumentRevision("doc1"));

            Assert.Equal("Something wrong detected", couchCommunicationException.Message);
            Assert.Equal(webExeption, couchCommunicationException.InnerException);
        }
        public void ShouldNotPostOnBulkUpdate()
        {
            var handler = new MockMessageHandler(new[] {
                new {id = "doc1", rev = "1-1a517022a0c2d4814d51abfedf9bfee7"},
                new {id = "doc2", rev = "2-1a517022a0c2d4814d51abfedf9bfee8"}
            }.ToJsonValue());

            CreateDbConfig(handler).BulkUpdate(b => {
                b.Create(new { _id = "doc1" }.ToDocument());
                b.Create(new { _id = "doc2", rev = "1-1a517022a0c2d4814d51abfedf9bfee9" }.ToDocument());
            }).Wait();

            AssertNonePosted();
        }
        public void ShouldSendDeleteRequestOnDeletion()
        {
            var handler = new MockMessageHandler(
                new { ok = true, id = "doc1", rev = "1-1a517022a0c2d4814d51abfedf9bfee7" }.ToJsonObject());
            IDatabaseApi databaseApi = ((ICouchApi) new CouchApi(new CouchApiSettings(new Uri("http://example.com:5984/")), handler)).Db("testdb");

            var resultObject = databaseApi.Synchronously.DeleteDocument(docId: "doc1", revision: "1-1a517022a0c2d4814d51abfedf9bfee7");

            Assert.Equal(
                "http://example.com:5984/testdb/doc1?rev=1-1a517022a0c2d4814d51abfedf9bfee7",
                handler.Request.RequestUri.ToString());
            Assert.Equal("DELETE", handler.Request.Method.ToString());
            Assert.Equal(new DocumentInfo(id: "doc1", revision: "1-1a517022a0c2d4814d51abfedf9bfee7"), resultObject);
        }
        public void ShouldThrowCouchCommunicationExceptionOn400StatusCode()
        {
            var httpClientMock =
                new MockMessageHandler(new HttpResponseMessage(HttpStatusCode.BadRequest) {
                    Content = new JsonContent(new { error = "bad_request", reason = "Mock reason" }.ToJsonObject())
                });

            var couchApi = GetDatabaseApi(httpClientMock);

            var exception = Assert.Throws<CouchCommunicationException>(
                () => couchApi.Synchronously.SaveDocument(new { _id = "doc1" }.ToDocument())
            );

            Assert.Contains("bad_request: Mock reason", exception.Message);
        }
        public void ShouldThrowCouchCommunicationExceptionOn400StatusCode()
        {
            var handler =
                new MockMessageHandler(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new JsonContent(new { error = "bad_request", reason = "Mock reason" }.ToJsonObject())
                });

            IDatabaseApi databaseApi = GetDatabaseApi(handler);

            var exception = Assert.Throws<CouchCommunicationException>(
                () => databaseApi.Synchronously.RequestLastestDocumentRevision("doc1")
            );

            Assert.Contains("bad_request: Mock reason", exception.Message);
        }
        public void ShouldSaveToDbCorrectly()
        {
            var mockMessageHandler = new MockMessageHandler(new {
                ok = true,
                id = "doc1",
                rev = "1-1a517022a0c2d4814d51abfedf9bfee7"
            }.ToJsonObject());
            var databaseApi = ((ICouchApi) new CouchApi(new CouchApiSettings("http://example.com:5984/"), mockMessageHandler)).Db("testdb");

            var result = databaseApi.Synchronously.SaveDocument(new { _id = "doc1", name = "Стас Гиркин" }.ToDocument());

            Assert.Equal("http://example.com:5984/testdb/doc1", mockMessageHandler.Request.RequestUri.ToString());
            Assert.Equal(HttpMethod.Put, mockMessageHandler.Request.Method);
            Assert.Equal(new { _id = "doc1", name = "Стас Гиркин" }.ToJsonString(), mockMessageHandler.RequestBodyString);
            Assert.Equal(new DocumentInfo("doc1", "1-1a517022a0c2d4814d51abfedf9bfee7"), result);
        }
        public void ShouldMakePutRequest()
        {
            var httpClient = new MockMessageHandler(
                new HttpResponseMessage(HttpStatusCode.OK) { Content = new JsonContent("{\"ok\": true}")});

            CreateCouchApi(httpClient).Db("testdb").Synchronously.UpdateSecurityDescriptor(new DatabaseSecurityDescriptor {
                Admins = new NamesRoles { Names = new[]{"admin1", "admin2"}, Roles = new[]{"admins1", "admins2"}},
                Readers = new NamesRoles { Names = new[]{"reader1", "reader2"}, Roles = new[]{"readers1", "readers2"}},
            });

            Assert.Equal(HttpMethod.Put, httpClient.Request.Method);
            TestUtils.AssertSameJson(
                new {
                    admins = new {names = new[]{"admin1", "admin2"}, roles = new[]{"admins1", "admins2"}},
                    readers = new { names = new[] { "reader1", "reader2" }, roles = new[] { "readers1", "readers2" } }
                },
                httpClient.RequestBodyString);
        }
예제 #24
0
        public void ShouldDeleteReplicationDescriptorSendingDeleteRequest()
        {
            var httpClientMock = new MockMessageHandler(
                new { id = "sourcedb_to_testdb", rev = "7-011f9010bf4edcb7312131b1d70fb060" }.ToJsonObject());

            GetCouchApi(httpClientMock).Replicator.Synchronously.Delete(new ReplicationTaskDescriptor {
                Id = "sourcedb_to_testdb",
                Revision = "6-011f9010bf4edcb7312131b1d70fb060",
                Target = new Uri("testdb", UriKind.Relative),
                Source = new Uri("http://example2.com/sourcedb"),
                Continuous = true,
                CreateTarget = true
            });

            Assert.Equal(HttpMethod.Delete, httpClientMock.Request.Method);
            Assert.Equal(
                "http://example.com/_replicator/sourcedb_to_testdb?rev=6-011f9010bf4edcb7312131b1d70fb060",
                httpClientMock.Request.RequestUri.ToString());
        }
예제 #25
0
        public void ShouldRetriveReplicationDescriptorByIdViaGetRequest()
        {
            var httpClientMock = new MockMessageHandler(
                new {
                    _id = "sourcedb_to_testdb",
                    _rev = "6-011f9010bf4edcb7312131b1d70fb060",
                    target = "http://example2.com/sourcedb",
                    source = "testdb",
                    continuous = true,
                    create_target = true,
                    _replication_state = "triggered",
                    _replication_state_time = "2011-09-07T14:11:19+04:00",
                    _replication_id = "cef1a54d4948bffcf9cb4d53591c5f5f"
                }.ToJsonObject());

            GetCouchApi(httpClientMock).Replicator.Synchronously.RequestDescriptorById("sourcedb_to_testdb");

            Assert.Equal(HttpMethod.Get, httpClientMock.Request.Method);
            Assert.Equal("http://example.com/_replicator/sourcedb_to_testdb", httpClientMock.Request.RequestUri.ToString());
        }
예제 #26
0
        /// <summary>
        /// A subtest for testing Execute when an exception is thrown while sending the request. This is tested with
        /// and without back-off. If back-off handler is attached to the service's message handler, there should be 3
        /// tries (the default value of <seealso cref="ConfigurableMessageHandler.NumTries"/>) before the operation
        /// fails.
        /// </summary>
        /// <param name="backOff">Indicates if back-off handler is attached to the service.</param>
        private void SubtestExecute_ThrowException(bool backOff)
        {
            var handler     = new MockMessageHandler(true);
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            // Set the default exponential back-off policy by the input.
            initializer.DefaultExponentialBackOffPolicy = backOff ?
                                                          ExponentialBackOffPolicy.Exception : ExponentialBackOffPolicy.None;

            using (var service = new MockClientService(initializer))
            {
                var request = new TestClientServiceRequest(service, "GET", null);
                Assert.Throws <InvalidOperationMockException>(() => request.Execute());

                int calls = backOff ? service.HttpClient.MessageHandler.NumTries : 1;
                Assert.That(handler.Calls, Is.EqualTo(calls));
            }
        }
        public async Task GetPublicKeysWithoutCaching()
        {
            var clock   = new MockClock();
            var handler = new MockMessageHandler()
            {
                Response = File.ReadAllBytes("./resources/public_keys.json"),
            };
            var clientFactory = new MockHttpClientFactory(handler);
            var keyManager    = new HttpPublicKeySource(
                "https://example.com/certs", clock, clientFactory);
            var keys = await keyManager.GetPublicKeysAsync();

            Assert.Equal(2, keys.Count);
            Assert.Equal(1, handler.Calls);

            var keys2 = await keyManager.GetPublicKeysAsync();

            Assert.Equal(2, keys.Count);
            Assert.Equal(2, handler.Calls);
            Assert.NotSame(keys, keys2);
        }
        public async Task PasswordResetLink()
        {
            var handler = new MockMessageHandler()
            {
                Response = GenerateEmailLinkResponse
            };
            var auth = this.CreateFirebaseAuth(handler);

            var link = await auth.GeneratePasswordResetLinkAsync("*****@*****.**");

            Assert.Equal("https://mock-oob-link.for.auth.tests", link);

            var request = NewtonsoftJsonSerializer.Instance.Deserialize <Dictionary <string, object> >(
                handler.LastRequestBody);

            Assert.Equal(3, request.Count);
            Assert.Equal("*****@*****.**", request["email"]);
            Assert.Equal("PASSWORD_RESET", request["requestType"]);
            Assert.True((bool)request["returnOobLink"]);
            this.AssertRequest(handler.Requests[0]);
        }
        private static async Task TestDynamicHeadersApplied(MockMessageHandler mockHandler, System.Net.Http.HttpClient client)
        {
            var result = await client.GetAsync("http://sometestsite.com/SomeEndPoint");

            Assert.IsTrue(mockHandler.Requests.Last().Headers.Contains("TestHeader"));
            var values = mockHandler.Requests.Last().Headers.GetValues("TestHeader");

            Assert.IsNotNull(values);
            Assert.AreEqual(1, values.Count());
            var firstValue = Guid.Parse(values.First());

            result = await client.GetAsync("http://sometestsite.com/SomeEndPoint");

            Assert.IsTrue(mockHandler.Requests.Last().Headers.Contains("TestHeader"));
            values = mockHandler.Requests.Last().Headers.GetValues("TestHeader");
            Assert.IsNotNull(values);
            Assert.AreEqual(1, values.Count());
            var secondValue = Guid.Parse(values.First());

            Assert.AreNotEqual(firstValue, secondValue);
        }
예제 #30
0
        private static GatewayStoreModel MockGatewayStoreModel(Func <HttpRequestMessage, Task <HttpResponseMessage> > sendFunc)
        {
            Mock <IDocumentClientInternal> mockDocumentClient = new Mock <IDocumentClientInternal>();

            mockDocumentClient.Setup(client => client.ServiceEndpoint).Returns(new Uri("https://foo"));

            GlobalEndpointManager endpointManager  = new GlobalEndpointManager(mockDocumentClient.Object, new ConnectionPolicy());
            ISessionContainer     sessionContainer = new SessionContainer(string.Empty);
            HttpMessageHandler    messageHandler   = new MockMessageHandler(sendFunc);

            return(new GatewayStoreModel(
                       endpointManager,
                       sessionContainer,
                       TimeSpan.FromSeconds(5),
                       ConsistencyLevel.Eventual,
                       new DocumentClientEventSource(),
                       new JsonSerializerSettings(),
                       new UserAgentContainer(),
                       ApiType.None,
                       messageHandler));
        }
예제 #31
0
        public async Task TransportError()
        {
            var handler = new MockMessageHandler()
            {
                Exception = new HttpRequestException("Transport error"),
            };
            var factory = new MockHttpClientFactory(handler);

            var client = new InstanceIdClient(factory, MockCredential, RetryOptions.NoBackOff);

            var exception = await Assert.ThrowsAsync <FirebaseMessagingException>(
                () => client.SubscribeToTopicAsync(new List <string> {
                "abc123"
            }, "test-topic"));

            Assert.Equal(ErrorCode.Unknown, exception.ErrorCode);
            Assert.Null(exception.MessagingErrorCode);
            Assert.Null(exception.HttpResponse);
            Assert.NotNull(exception.InnerException);
            Assert.Equal(5, handler.Calls);
        }
        public async Task UpdateUser()
        {
            var handler = new MockMessageHandler()
            {
                Response = new UserRecord("user1"),
            };
            var factory     = new MockHttpClientFactory(handler);
            var userManager = new FirebaseUserManager(
                new FirebaseUserManagerArgs
            {
                Credential    = MockCredential,
                ProjectId     = MockProjectId,
                ClientFactory = factory,
            });
            var customClaims = new Dictionary <string, object>()
            {
                { "admin", true },
            };

            await userManager.UpdateUserAsync(new UserRecord("user1") { CustomClaims = customClaims });
        }
예제 #33
0
        public async Task WelformedSignErrorWithCode()
        {
            var handler = new MockMessageHandler()
            {
                StatusCode = HttpStatusCode.InternalServerError,
                Response   = @"{""error"": {""message"": ""test reason"", ""status"": ""UNAVAILABLE""}}",
            };
            var factory = new MockHttpClientFactory(handler);
            var signer  = this.CreateFixedAccountIAMSigner(factory);

            Assert.Equal("test-service-account", await signer.GetKeyIdAsync());
            byte[] data = Encoding.UTF8.GetBytes("Hello world");
            var    ex   = await Assert.ThrowsAsync <FirebaseAuthException>(
                async() => await signer.SignDataAsync(data));

            Assert.Equal(ErrorCode.Unavailable, ex.ErrorCode);
            Assert.Equal("test reason", ex.Message);
            Assert.Null(ex.AuthErrorCode);
            Assert.NotNull(ex.HttpResponse);
            Assert.Null(ex.InnerException);
        }
        public async Task ValidUnrevokedToken()
        {
            var cookie = await CreateSessionCookieAsync();

            var handler = new MockMessageHandler()
            {
                Response = @"{
                    ""users"": [
                        {
                            ""localId"": ""testuser""
                        }
                    ]
                }",
            };
            var auth = this.CreateFirebaseAuth(handler);

            var decoded = await auth.VerifySessionCookieAsync(cookie, true);

            Assert.Equal("testuser", decoded.Uid);
            Assert.Equal(1, handler.Calls);
        }
예제 #35
0
        public async Task Unavailable()
        {
            var handler = new MockMessageHandler()
            {
                StatusCode = HttpStatusCode.ServiceUnavailable,
                Response   = @"{""error"": {""message"": ""test reason""}}",
            };
            var factory = new MockHttpClientFactory(handler);
            var signer  = this.CreateFixedAccountIAMSigner(factory);

            byte[] data = Encoding.UTF8.GetBytes("Hello world");
            var    ex   = await Assert.ThrowsAsync <FirebaseAuthException>(
                async() => await signer.SignDataAsync(data));

            Assert.Equal(ErrorCode.Unavailable, ex.ErrorCode);
            Assert.Equal("test reason", ex.Message);
            Assert.Null(ex.AuthErrorCode);
            Assert.NotNull(ex.HttpResponse);
            Assert.Null(ex.InnerException);
            Assert.Equal(5, handler.Calls);
        }
        public void ResolveKey()
        {
            var           mockedCache               = CreateEmptyMockedCache();
            var           cert                      = "{\"x5u\": \"LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQ0lqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FnOEFNSUlDQ2dLQ0FnRUFqbXJnN3NGeFJkb2JTWkhJMlpqawpucnBGVC9RclhEcFl6VVU4SU1hNFRPa2dFUnRaM09CbFpkbWNieXVmcEJuNTJmWDlYRWVIOVR1QjkxOWNQeEJFCnpKN0NzUmVTK1dxcHk5UFN3K3BtQ2lDZmpIZmx1ZDJ1dzUwbmVYOGVKeFl0ekhDN1VOOCt1QThvQ0tqdzBJM1AKK0VDYTdhVy9EbU1jSS81T3NyaXhlN2ZQenY4Q0V6aFRidzdBOTZuSzIrVkkvVXFGV2Yxb0Rzd2xYOFBPaHpMRQppdWo3eEJpdWJqbDZONERablF5YW84UzJFZ2ZQT05KNG1ySW42VEQwNzEvdE9NaDFHWUF3SnBWQ3YzYWdSUVdHCjhNaWxhYXlyQzRaNTNrNmRLV1FTNklmVTd3NWJnQjEraGdJenBoK05NbzdWWTROYkpYOTZ1b0Q3QW9pQjRvNjYKclMxakNLS3lEcUwwTTkwQzFIaDcrUit5TWhJa0ZkRUdDS0ZHaDNmbDlVREdKNEZEVG1vNGR1MENxbm13bWpvVgpmUmR0eW4rNjFBRHhQNnpkN24xTEFxeVBCNEVreHVrUTc3Sy9PTkxwUnYydHJmdDlvU1VSMWpXTXE3dzEyV1lyCmhZVnhPR1NvNU40RUdCSmpIQXlRZ01DUzhQWGdtN045WGFOdWtlczBZQ3lBTDlYU0JDRTNuNFQ0Qk9XRzlEMkIKQ0QvelV2bjVDRnl3Smh1ZzlSdzRMV3QwbzJHYXlpTjN5SDBwZFhBc2pTRlRiN1ZpdnBPc1cwL3k2aUdmMEJqSwpUOHlYSkVvOG9QcDRIMkl1TDR4TDQ4bW50Qm5WalBzSXRuemlHQ2pxZ0hCN2xxYjdxeXUvNit4dEhnTGxGb2MyCjBLQnZTYURGWWJiRXRPNE5GVnJNdUlFQ0F3RUFBUT09Ci0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQ==\"}";
            var           mockHandler               = new MockMessageHandler <string>(HttpStatusCode.OK, cert);
            var           resolver                  = new JwtSigningKeyResolver(mockedCache.Object, Options.Create(_options), mockHandler, _logger);
            var           token                     = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsIng1dSI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC94NXUifQ.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE0NzI1NDk1NDgsImV4cCI6MTUwNDA4NTU0OCwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5hbWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.jKg9l0cuTapEFcx9v1pLtBiigK_7EXlCqvKZBoS24XE";
            SecurityToken securityToken             = new JwtSecurityToken(token);
            var           tokenValidationParameters = new TokenValidationParameters();

            var keys = resolver.IssuerSigningKeyResolver(token, securityToken, "", tokenValidationParameters);

            Assert.NotNull(keys);
            Assert.NotEmpty(keys);
            Assert.IsType <RsaSecurityKey>(keys.First());

            var key = keys.First() as RsaSecurityKey;

            Assert.Equal(66571, key.Parameters.Modulus.Sum(b => b));
            Assert.Equal(2, key.Parameters.Exponent.Sum(b => b));
        }
예제 #37
0
        public void ShouldThrowAggregateExceptionOnMultiplyErrorResponse()
        {
            var handler = new MockMessageHandler(new object[] {
                new { id = "doc1", error = "forbidden", reason = "message" },
                new { id = "doc2", error = "conflict", reason = "message" }
            }.ToJsonValue());

            IDatabaseApi databaseApi = CreateCouchApi(handler).Db("testdb");

            var exception = Assert.Throws <AggregateException>(() =>
                                                               databaseApi.Synchronously.BulkUpdate(
                                                                   x => {
                x.Create(new { _id = "doc1", name = "John", age = 42 }.ToDocument());
                x.Create(new { _id = "doc2" }.ToDocument());
            })
                                                               );

            Assert.Equal(2, exception.InnerExceptions.Count);
            Assert.IsType <InvalidDocumentException>(exception.InnerExceptions[0]);
            Assert.IsType <StaleObjectStateException>(exception.InnerExceptions[1]);
        }
        public async Task DeleteConfigNotFoundError(ProviderTestConfig config)
        {
            var handler = new MockMessageHandler()
            {
                StatusCode = HttpStatusCode.NotFound,
                Response   = ProviderTestConfig.ConfigNotFoundResponse,
            };
            var auth = config.CreateAuth(handler);

            var exception = await Assert.ThrowsAsync <FirebaseAuthException>(
                () => auth.DeleteProviderConfigAsync("saml.provider"));

            Assert.Equal(ErrorCode.NotFound, exception.ErrorCode);
            Assert.Equal(AuthErrorCode.ConfigurationNotFound, exception.AuthErrorCode);
            Assert.Equal(
                "No identity provider configuration found for the given identifier "
                + "(CONFIGURATION_NOT_FOUND).",
                exception.Message);
            Assert.NotNull(exception.HttpResponse);
            Assert.Null(exception.InnerException);
        }
예제 #39
0
        public async Task HttpErrorAsync()
        {
            var handler = new MockMessageHandler()
            {
                StatusCode = HttpStatusCode.InternalServerError,
                Response   = @"{
                    ""error"": {
                        ""status"": ""PERMISSION_DENIED"",
                        ""message"": ""test error"",
                        ""details"": [
                            {
                                ""@type"": ""type.googleapis.com/google.firebase.fcm.v1.FcmError"",
                                ""errorCode"": ""UNREGISTERED""
                            }
                        ]
                    }
                }",
            };
            var factory = new MockHttpClientFactory(handler);
            var client  = this.CreateMessagingClient(factory);
            var message = new Message()
            {
                Topic = "test-topic",
            };

            var ex = await Assert.ThrowsAsync <FirebaseMessagingException>(
                async() => await client.SendAsync(message));

            Assert.Equal(ErrorCode.PermissionDenied, ex.ErrorCode);
            Assert.Equal("test error", ex.Message);
            Assert.Equal(MessagingErrorCode.Unregistered, ex.MessagingErrorCode);
            Assert.NotNull(ex.HttpResponse);

            var req = JsonConvert.DeserializeObject <FirebaseMessagingClient.SendRequest>(
                handler.LastRequestBody);

            Assert.Equal("test-topic", req.Message.Topic);
            Assert.False(req.ValidateOnly);
            Assert.Equal(1, handler.Calls);
        }
        public async Task CreateConfig(ProviderTestConfig config)
        {
            var handler = new MockMessageHandler()
            {
                Response = OidcProviderConfigResponse,
            };
            var auth = config.CreateAuth(handler);
            var args = new OidcProviderConfigArgs()
            {
                ProviderId          = "oidc.provider",
                DisplayName         = "oidcProviderName",
                Enabled             = true,
                ClientId            = "CLIENT_ID",
                Issuer              = "https://oidc.com/issuer",
                ClientSecret        = "CLIENT_SECRET",
                CodeResponseType    = true,
                IdTokenResponseType = true,
            };

            var provider = await auth.CreateProviderConfigAsync(args);

            this.AssertOidcProviderConfig(provider);
            Assert.Equal(1, handler.Requests.Count);
            var request = handler.Requests[0];

            Assert.Equal(HttpMethod.Post, request.Method);
            config.AssertRequest("oauthIdpConfigs?oauthIdpConfigId=oidc.provider", request);

            var body = NewtonsoftJsonSerializer.Instance.Deserialize <JObject>(
                handler.LastRequestBody);

            Assert.Equal(6, body.Count);
            Assert.Equal("oidcProviderName", body["displayName"]);
            Assert.True((bool)body["enabled"]);
            Assert.Equal("CLIENT_ID", body["clientId"]);
            Assert.Equal("https://oidc.com/issuer", body["issuer"]);
            Assert.Equal("CLIENT_SECRET", body["clientSecret"]);
            Assert.True((bool)body["responseType"]["code"]);
            Assert.True((bool)body["responseType"]["idToken"]);
        }
예제 #41
0
        public void ShouldCreateUpdateCreateAndDeleteRecordsInBulkUpdateRequest()
        {
            var handler = new MockMessageHandler(
                new[] {
                    new {id = "doc1", rev = "2-1a517022a0c2d4814d51abfedf9bfee7"},
                    new {id = "doc2", rev = "2-1a517022a0c2d4814d51abfedf9bfee8"},
                    new {id = "doc3", rev = "1-1a517022a0c2d4814d51abfedf9bfee9"},
                    new {id = "doc4", rev = "1-1a517022a0c2d4814d51abfedf9bfee0"}
                }.ToJsonValue());
            IDatabaseApi databaseApi = CreateCouchApi(handler).Db("testdb");

            var result = databaseApi.Synchronously.BulkUpdate(
                x => {
                    x.Create(new {_id = "doc1", name = "John", age = 42}.ToDocument());
                    x.Update(
                        new {_id = "doc2", _rev = "1-1a517022a0c2d4814d51abfedf9bfee8", name = "John", age = 42}.
                            ToDocument());
                    x.Delete(
                        new {_id = "doc3", _rev = "1-1a517022a0c2d4814d51abfedf9bfee9", name = "John", age = 42}.
                            ToDocument());
                    x.Delete("doc4", "1-1a517022a0c2d4814d51abfedf9bfee0");
                });

            var expectedDescriptor = new {
                docs = new object[] {
                    new {_id = "doc1", name = "John", age = 42},
                    new {_id = "doc2", _rev = "1-1a517022a0c2d4814d51abfedf9bfee8", name = "John", age = 42},
                    new {_id = "doc3", _rev = "1-1a517022a0c2d4814d51abfedf9bfee9", _deleted = true},
                    new {_id = "doc4", _rev = "1-1a517022a0c2d4814d51abfedf9bfee0", _deleted = true}
                }
            }.ToJsonString();

            var sendDescriptor = handler.RequestBodyString;
            Assert.Equal(expectedDescriptor, sendDescriptor);

            Assert.Equal("2-1a517022a0c2d4814d51abfedf9bfee7", result["doc1"].Revision);
            Assert.Equal("2-1a517022a0c2d4814d51abfedf9bfee8", result["doc2"].Revision);
            Assert.Equal("1-1a517022a0c2d4814d51abfedf9bfee9", result["doc3"].Revision);
            Assert.Equal("1-1a517022a0c2d4814d51abfedf9bfee0", result["doc4"].Revision);
        }
        public async Task CreateTenantMinimal(TestConfig config)
        {
            var handler = new MockMessageHandler()
            {
                Response = TenantResponse,
            };
            var auth = config.CreateFirebaseAuth(handler);

            var provider = await auth.TenantManager.CreateTenantAsync(new TenantArgs());

            AssertTenant(provider);
            Assert.Equal(1, handler.Requests.Count);
            var request = handler.Requests[0];

            Assert.Equal(HttpMethod.Post, request.Method);
            config.AssertRequest("tenants", request);

            var body = NewtonsoftJsonSerializer.Instance.Deserialize <JObject>(
                handler.LastRequestBody);

            Assert.Empty(body);
        }
        public async Task Unauthorized()
        {
            var handler = new MockMessageHandler()
            {
                StatusCode = HttpStatusCode.Unauthorized,
                Response   = "Unauthorized",
            };
            var factory = new MockHttpClientFactory(handler);

            var client = new InstanceIdClient(factory, MockCredential);

            var exception = await Assert.ThrowsAsync <FirebaseMessagingException>(
                () => client.SubscribeToTopicAsync("test-topic", new List <string> {
                "abc123"
            }));

            Assert.Equal(ErrorCode.Unauthenticated, exception.ErrorCode);
            Assert.Equal("Unexpected HTTP response with status: 401 (Unauthorized)\nUnauthorized", exception.Message);
            Assert.Null(exception.MessagingErrorCode);
            Assert.NotNull(exception.HttpResponse);
            Assert.Null(exception.InnerException);
        }
예제 #44
0
        public async Task RetryOnNetworkError()
        {
            var handler = new MockMessageHandler()
            {
                Exception = new HttpRequestException("Low-level network error"),
            };
            var factory = new MockHttpClientFactory(handler);
            var args    = this.CreateArgs(factory);

            args.RetryOptions = this.RetryOptionsWithoutBackOff();
            var httpClient = new ErrorHandlingHttpClient <FirebaseException>(args);

            var exception = await Assert.ThrowsAsync <FirebaseException>(
                async() => await httpClient.SendAndDeserializeAsync <Dictionary <string, string> >(
                    this.CreateRequest()));

            Assert.Equal(ErrorCode.Unknown, exception.ErrorCode);
            Assert.Equal("Network error", exception.Message);
            Assert.Same(handler.Exception, exception.InnerException);
            Assert.Null(exception.HttpResponse);
            Assert.Equal(5, handler.Calls);
        }
        public async Task ValidUnrevokedToken(TestConfig config)
        {
            var cookie = await config.CreateSessionCookieAsync();

            var handler = new MockMessageHandler()
            {
                Response = @"{
                    ""users"": [
                        {
                            ""localId"": ""testuser""
                        }
                    ]
                }",
            };
            var auth = config.CreateAuth(handler);

            var decoded = await auth.VerifySessionCookieAsync(cookie, true);

            Assert.Equal("testuser", decoded.Uid);
            Assert.Equal(1, handler.Calls);
            JwtTestUtils.AssertRevocationCheckRequest(null, handler.Requests[0].Url);
        }
예제 #46
0
        public async Task WelformedSignError()
        {
            var handler = new MockMessageHandler()
            {
                StatusCode = HttpStatusCode.InternalServerError,
                Response   = @"{""error"": {""message"": ""test reason""}}",
            };
            var factory = new MockHttpClientFactory(handler);
            var signer  = new FixedAccountIAMSigner(
                factory, GoogleCredential.FromAccessToken("token"), "test-service-account");

            Assert.Equal("test-service-account", await signer.GetKeyIdAsync());
            byte[] data = Encoding.UTF8.GetBytes("Hello world");
            var    ex   = await Assert.ThrowsAsync <FirebaseAuthException>(
                async() => await signer.SignDataAsync(data));

            Assert.Equal(ErrorCode.Internal, ex.ErrorCode);
            Assert.Equal("test reason", ex.Message);
            Assert.Null(ex.AuthErrorCode);
            Assert.NotNull(ex.HttpResponse);
            Assert.Null(ex.InnerException);
        }
예제 #47
0
        public async Task GatewayStatsDurationTest()
        {
            bool failedOnce = false;
            Func <HttpRequestMessage, Task <HttpResponseMessage> > sendFunc = async request =>
            {
                await Task.Delay(1000);

                if (!failedOnce)
                {
                    failedOnce = true;
                    throw new OperationCanceledException();
                }

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("Response")
                });
            };

            HttpMessageHandler mockMessageHandler = new MockMessageHandler(sendFunc);
            CosmosHttpClient   cosmosHttpClient   = MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(mockMessageHandler),
                                                                                          DocumentClientEventSource.Instance);

            Tracing.TraceData.ClientSideRequestStatisticsTraceDatum clientSideRequestStatistics = new Tracing.TraceData.ClientSideRequestStatisticsTraceDatum(DateTime.UtcNow);

            await cosmosHttpClient.SendHttpAsync(() => new ValueTask <HttpRequestMessage>(new HttpRequestMessage(HttpMethod.Get, "http://someuri.com")),
                                                 ResourceType.Document,
                                                 HttpTimeoutPolicyDefault.Instance,
                                                 clientSideRequestStatistics,
                                                 CancellationToken.None);

            Assert.AreEqual(clientSideRequestStatistics.HttpResponseStatisticsList.Count, 2);
            // The duration is calculated using date times which can cause the duration to be slightly off. This allows for up to 15 Ms of variance.
            // https://stackoverflow.com/questions/2143140/c-sharp-datetime-now-precision#:~:text=The%20precision%20is%20related%20to,35%2D40%20ms%20accuracy
            Assert.IsTrue(clientSideRequestStatistics.HttpResponseStatisticsList[0].Duration.TotalMilliseconds >= 985, $"First request did was not delayed by at least 1 second. {JsonConvert.SerializeObject(clientSideRequestStatistics.HttpResponseStatisticsList[0])}");
            Assert.IsTrue(clientSideRequestStatistics.HttpResponseStatisticsList[1].Duration.TotalMilliseconds >= 985, $"Second request did was not delayed by at least 1 second. {JsonConvert.SerializeObject(clientSideRequestStatistics.HttpResponseStatisticsList[1])}");
            Assert.IsTrue(clientSideRequestStatistics.HttpResponseStatisticsList[0].RequestStartTime <
                          clientSideRequestStatistics.HttpResponseStatisticsList[1].RequestStartTime);
        }
예제 #48
0
        public void ShouldThrowCouchCommunicationExceptionOn400StatusCode()
        {
            var httpClientMock =
                new MockMessageHandler(new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Content = new JsonContent(new { error = "bad_request", reason = "Mock reason" }.ToJsonObject())
            });

            var couchApi = GetDatabaseApi(httpClientMock);

            var exception = Assert.Throws <CouchCommunicationException>(
                () => couchApi.Synchronously.Query(
                    new ViewQuery {
                ViewName    = "_all_docs",
                Key         = new object[] { "key", 0 },
                Skip        = 1,
                IncludeDocs = true
            })
                );

            Assert.Contains("bad_request: Mock reason", exception.Message);
        }
예제 #49
0
        public async Task Forbidden()
        {
            var handler = new MockMessageHandler()
            {
                StatusCode = HttpStatusCode.Forbidden,
                Response   = "Forbidden",
            };
            var factory = new MockHttpClientFactory(handler);

            var client = new InstanceIdClient(factory, MockCredential);

            var exception = await Assert.ThrowsAsync <FirebaseMessagingException>(
                () => client.SubscribeToTopicAsync(new List <string> {
                "abc123"
            }, "test-topic"));

            Assert.Equal(ErrorCode.PermissionDenied, exception.ErrorCode);
            Assert.Equal("Unexpected HTTP response with status: 403 (Forbidden)\nForbidden", exception.Message);
            Assert.Null(exception.MessagingErrorCode);
            Assert.NotNull(exception.HttpResponse);
            Assert.Null(exception.InnerException);
        }
예제 #50
0
        public async Task BadRequest()
        {
            var handler = new MockMessageHandler()
            {
                StatusCode = HttpStatusCode.BadRequest,
                Response   = "BadRequest",
            };
            var factory = new MockHttpClientFactory(handler);

            var client = new InstanceIdClient(factory, MockCredential);

            var exception = await Assert.ThrowsAsync <FirebaseMessagingException>(
                () => client.SubscribeToTopicAsync(new List <string> {
                "abc123"
            }, "test-topic"));

            Assert.Equal(ErrorCode.InvalidArgument, exception.ErrorCode);
            Assert.Equal("Unexpected HTTP response with status: 400 (BadRequest)\nBadRequest", exception.Message);
            Assert.Null(exception.MessagingErrorCode);
            Assert.NotNull(exception.HttpResponse);
            Assert.Null(exception.InnerException);
        }
        public async Task ListSamlByPages(ProviderTestConfig config)
        {
            var handler = new MockMessageHandler()
            {
                Response = ListConfigsResponses,
            };
            var auth    = config.CreateAuth(handler);
            var configs = new List <SamlProviderConfig>();

            // Read page 1.
            var pagedEnumerable = auth.ListSamlProviderConfigsAsync(null);
            var configPage      = await pagedEnumerable.ReadPageAsync(3);

            Assert.Equal(3, configPage.Count());
            Assert.Equal("token", configPage.NextPageToken);

            var request = Assert.Single(handler.Requests);

            config.AssertRequest("inboundSamlConfigs?pageSize=3", request);
            configs.AddRange(configPage);

            // Read page 2.
            pagedEnumerable = auth.ListSamlProviderConfigsAsync(new ListProviderConfigsOptions()
            {
                PageToken = configPage.NextPageToken,
            });
            configPage = await pagedEnumerable.ReadPageAsync(3);

            Assert.Equal(2, configPage.Count());
            Assert.Null(configPage.NextPageToken);

            Assert.Equal(2, handler.Requests.Count);
            config.AssertRequest(
                "inboundSamlConfigs?pageSize=3&pageToken=token", handler.Requests[1]);
            configs.AddRange(configPage);

            Assert.Equal(5, configs.Count);
            Assert.All(configs, this.AssertSamlProviderConfig);
        }
        public async Task CreateConfig(ProviderTestConfig config)
        {
            var handler = new MockMessageHandler()
            {
                Response = SamlProviderConfigResponse,
            };
            var auth = config.CreateAuth(handler);
            var args = new SamlProviderConfigArgs()
            {
                ProviderId       = "saml.provider",
                DisplayName      = "samlProviderName",
                Enabled          = true,
                IdpEntityId      = "IDP_ENTITY_ID",
                SsoUrl           = "https://example.com/login",
                X509Certificates = new List <string>()
                {
                    "CERT1", "CERT2"
                },
                RpEntityId  = "RP_ENTITY_ID",
                CallbackUrl = "https://projectId.firebaseapp.com/__/auth/handler",
            };

            var provider = await auth.CreateProviderConfigAsync(args);

            this.AssertSamlProviderConfig(provider);
            var request = Assert.Single(handler.Requests);

            Assert.Equal(HttpMethod.Post, request.Method);
            config.AssertRequest("inboundSamlConfigs?inboundSamlConfigId=saml.provider", request);

            var body = NewtonsoftJsonSerializer.Instance.Deserialize <JObject>(
                handler.LastRequestBody);

            Assert.Equal(4, body.Count);
            Assert.Equal("samlProviderName", body["displayName"]);
            Assert.True((bool)body["enabled"]);
            this.AssertIdpConfig((JObject)body["idpConfig"]);
            this.AssertSpConfig((JObject)body["spConfig"]);
        }
        public async Task CreateConfigMinimal()
        {
            var handler = new MockMessageHandler()
            {
                Response = SamlProviderConfigResponse,
            };
            var auth = ProviderConfigTestUtils.CreateFirebaseAuth(handler);
            var args = new SamlProviderConfigArgs()
            {
                ProviderId       = "saml.minimal-provider",
                IdpEntityId      = "IDP_ENTITY_ID",
                SsoUrl           = "https://example.com/login",
                X509Certificates = new List <string>()
                {
                    "CERT1", "CERT2"
                },
                RpEntityId  = "RP_ENTITY_ID",
                CallbackUrl = "https://projectId.firebaseapp.com/__/auth/handler",
            };

            var provider = await auth.CreateProviderConfigAsync(args);

            this.AssertSamlProviderConfig(provider);
            Assert.Equal(1, handler.Requests.Count);
            var request = handler.Requests[0];

            Assert.Equal(HttpMethod.Post, request.Method);
            Assert.Equal(
                "/v2/projects/project1/inboundSamlConfigs?inboundSamlConfigId=saml.minimal-provider",
                request.Url.PathAndQuery);
            ProviderConfigTestUtils.AssertClientVersionHeader(request);

            var body = NewtonsoftJsonSerializer.Instance.Deserialize <JObject>(
                handler.LastRequestBody);

            Assert.Equal(2, body.Count);
            this.AssertIdpConfig((JObject)body["idpConfig"]);
            this.AssertSpConfig((JObject)body["spConfig"]);
        }
        public async Task MalformedResponse()
        {
            var clock   = new MockClock();
            var handler = new MockMessageHandler()
            {
                Response = "not json",
            };
            var clientFactory = new MockHttpClientFactory(handler);
            var keyManager    = new HttpPublicKeySource(
                "https://example.com/certs", clock, clientFactory);

            var exception = await Assert.ThrowsAsync <FirebaseAuthException>(
                async() => await keyManager.GetPublicKeysAsync());

            Assert.Equal(ErrorCode.Unknown, exception.ErrorCode);
            Assert.Equal("Failed to parse certificate response: not json.", exception.Message);
            Assert.Equal(AuthErrorCode.CertificateFetchFailed, exception.AuthErrorCode);
            Assert.NotNull(exception.HttpResponse);
            Assert.NotNull(exception.InnerException);

            Assert.Equal(1, handler.Calls);
        }
        public async Task ServiceUnavailable()
        {
            var handler = new MockMessageHandler()
            {
                StatusCode = HttpStatusCode.ServiceUnavailable,
                Response   = "ServiceUnavailable",
            };
            var factory = new MockHttpClientFactory(handler);

            var client = new InstanceIdClient(factory, MockCredential);

            var exception = await Assert.ThrowsAsync <FirebaseMessagingException>(
                () => client.SubscribeToTopicAsync(new List <string> {
                "abc123"
            }, "test-topic"));

            Assert.Equal(ErrorCode.Unavailable, exception.ErrorCode);
            Assert.Equal("Unexpected HTTP response with status: 503 (ServiceUnavailable)\nServiceUnavailable", exception.Message);
            Assert.Null(exception.MessagingErrorCode);
            Assert.NotNull(exception.HttpResponse);
            Assert.Null(exception.InnerException);
        }
예제 #56
0
            public async Task It_Should_Send_Message_To_The_Endpoint()
            {
                using (AutoMock mock = AutoMock.GetLoose(this.xUnitOutput.Capture()))
                {
                    IOptions <TelegramOptions> options = Options.Create(new TelegramOptions {
                        Endpoint = new Uri("https://api.telegram.org"), Channel = "abc", Token = "cde"
                    });
                    mock.Provide(options);

                    var response = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent("some-response")
                    };
                    var mockMessageHandler = new MockMessageHandler(response);
                    mock.Mock <IHttpClientFactory>()
                    .Setup(p => p.CreateClient(HttpClientFactoryExtensions.ClientName))
                    .Returns(new HttpClient(mockMessageHandler)
                    {
                        BaseAddress = options.Value.Endpoint
                    });

                    var service = mock.Create <TelegramServiceImpl>();
                    await service.SendMessageAsync("some-message", CancellationToken.None);

                    mock.Mock <IHttpClientFactory>()
                    .Verify(p => p.CreateClient(HttpClientFactoryExtensions.ClientName), Times.Once);

                    HttpRequestMessage request = mockMessageHandler.MessageSent;
                    Assert.Equal(HttpMethod.Post, request.Method);
                    // ReSharper disable once StringLiteralTypo
                    Assert.Equal("/botcde/sendMessage", request.RequestUri.AbsolutePath);

                    const string expectedContent = "{\"chat_id\":\"abc\",\"text\":\"some-message\",\"parse_mode\":\"Markdown\"}";
                    string       content         = await request.Content.ReadAsStringAsync();

                    Assert.Equal(expectedContent, content);
                }
            }
예제 #57
0
        public void ShouldSendGetRequestForGetAllQuery()
        {
            var httpClientMock = new MockMessageHandler(new {
                total_rows = 2,
                offset = 1,
                rows = new object [0]
                }
            .ToJsonObject());

            var couchApi = GetDatabaseApi(httpClientMock);
            couchApi.Synchronously.Query(
                new ViewQuery {
                    DesignDocumentName = "dd",
                    ViewName = "v1",
                    Skip = 1,
                    IncludeDocs = true
                });

            Assert.Equal(HttpMethod.Get, httpClientMock.Request.Method);
            Assert.Equal(
                "http://example.com:5984/testdb/_design/dd/_view/v1?skip=1&include_docs=true",
                httpClientMock.Request.RequestUri.ToString());
        }
예제 #58
0
        public void ShouldUpdateReplicationDescriptor()
        {
            var httpClientMock = new MockMessageHandler(
                new { id = "sourcedb_to_testdb", rev = "7-011f9010bf4edcb7312131b1d70fb060" }.ToJsonObject());
            using (var couchApi = GetCouchApi(httpClientMock))
            {
                couchApi.Replicator.Synchronously.SaveDescriptor(
                    new ReplicationTaskDescriptor {
                        Id = "sourcedb_to_testdb",
                        Revision = "6-011f9010bf4edcb7312131b1d70fb060",
                        Target = new Uri("testdb", UriKind.Relative),
                        Source = new Uri("http://example2.com/sourcedb"),
                        Continuous = true,
                        CreateTarget = true
                    });

                Assert.Equal(HttpMethod.Put, httpClientMock.Request.Method);
                Assert.Equal(
                    "http://example.com/_replicator/sourcedb_to_testdb",
                    httpClientMock.Request.RequestUri.ToString());
                Assert.Equal(
                    new {
                        _id = "sourcedb_to_testdb",
                        _rev = "6-011f9010bf4edcb7312131b1d70fb060",
                        target = "testdb",
                        source = "http://example2.com/sourcedb",
                        continuous = true,
                        create_target = true
                    }.ToJsonString(),
                    httpClientMock.RequestBodyString
                    );
            }
        }
        public void SendAsync_UserAgent()
        {
            var apiVersion = string.Format("google-api-dotnet-client/{0} (gzip)", Utilities.GetLibraryVersion());
            const string applicationName = "NO NAME";

            var handler = new MockMessageHandler();
            var configurableHanlder = new ConfigurableMessageHandler(handler);

            using (var client = new HttpClient(configurableHanlder))
            {
                // without application name
                var request = new HttpRequestMessage(HttpMethod.Get, "https://test-user-agent");
                HttpResponseMessage response = client.SendAsync(request).Result;
                var userAgent = string.Join(" ", request.Headers.GetValues("User-Agent").ToArray());
                Assert.That(userAgent, Is.EqualTo(apiVersion));

                // with application name
                configurableHanlder.ApplicationName = applicationName;
                request = new HttpRequestMessage(HttpMethod.Get, "https://test-user-agent");
                response = client.SendAsync(request).Result;
                userAgent = string.Join(" ", request.Headers.GetValues("User-Agent").ToArray());
                Assert.That(userAgent, Is.EqualTo(applicationName + " " + apiVersion));
            }
        }
예제 #60
0
 static ICouchApi GetCouchApi(MockMessageHandler messageHandler = null)
 {
     return new CouchApi(new CouchApiSettings("http://example.com"), messageHandler ?? new MockMessageHandler());
 }