public async Task FindClientByIdAsync_TestAsync()
        {
            var store = new ClientStore(options);

            var client = await store.FindClientByIdAsync("");

            Assert.Null(client);
            client = await store.FindClientByIdAsync("client1");

            Assert.NotNull(client);
        }
        public async Task FindClientByIdAsync_WhenClientExistsWithCollections_ExpectClientReturnedCollections()
        {
            var storeHolder = GetConfigurationDocumentStoreHolder();

            var testClient = new Client
            {
                ClientId                     = "properties_test_client",
                ClientName                   = "Properties Test Client",
                AllowedCorsOrigins           = { "https://localhost" },
                AllowedGrantTypes            = GrantTypes.HybridAndClientCredentials,
                AllowedScopes                = { "openid", "profile", "api1" },
                Claims                       = { new ClientClaim("test", "value") },
                ClientSecrets                = { new Secret(CryptographyHelper.CreateHash("secret")) },
                IdentityProviderRestrictions = { "AD" },
                PostLogoutRedirectUris       = { "https://locahost/signout-callback" },
                Properties                   = { { "foo1", "bar1" }, { "foo2", "bar2" }, },
                RedirectUris                 = { "https://locahost/signin" }
            };

            using (var session = storeHolder.OpenAsyncSession())
            {
                await session.StoreAsync(testClient.ToEntity());

                await session.SaveChangesAsync();
            }

            WaitForIndexing(storeHolder.IntegrationTest_GetDocumentStore());

            var store  = new ClientStore(storeHolder, FakeLogger <ClientStore> .Create());
            var client = await store.FindClientByIdAsync(testClient.ClientId);

            client.Should().BeEquivalentTo(testClient);
        }
        public async Task Should_Retrieve_Client_With_Properties(TestDatabase testDb)
        {
            var testClient = new Client()
            {
                ClientId   = Guid.NewGuid().ToString(),
                ClientName = "Test Client with Properties",
                Properties =
                {
                    { "prop1", "val1" },
                    { "prop2", "val2" },
                    { "prop3", "val3" }
                }
            };

            using (var session = testDb.OpenSession())
            {
                await session.SaveAsync(testClient.ToEntity());

                await session.FlushAsync();
            }

            Client requestedClient;
            var    loggerMock = new Mock <ILogger <ClientStore> >();

            using (var session = testDb.OpenSession())
            {
                var store = new ClientStore(session, loggerMock.Object);
                requestedClient = await store.FindClientByIdAsync(testClient.ClientId);
            }

            requestedClient.Should().NotBeNull();
            requestedClient.Properties.Count.Should().Be(3);

            await CleanupTestDataAsync(testDb);
        }
        public async Task FindClientByIdAsync_WhenClientExistsWithCollections_ExpectClientReturnedCollections(DbContextOptions <ConfigurationDbContext> options)
        {
            var testClient = new Client
            {
                ClientId                     = "properties_test_client",
                ClientName                   = "Properties Test Client",
                AllowedCorsOrigins           = { "https://localhost" },
                AllowedGrantTypes            = GrantTypes.HybridAndClientCredentials,
                AllowedScopes                = { "openid", "profile", "api1" },
                Claims                       = { new Claim("test", "value") },
                ClientSecrets                = { new Secret("secret".Sha256()) },
                IdentityProviderRestrictions = { "AD" },
                PostLogoutRedirectUris       = { "https://locahost/signout-callback" },
                Properties                   = { { "foo1", "bar1" }, { "foo2", "bar2" }, },
                RedirectUris                 = { "https://locahost/signin" }
            };

            using (var context = new ConfigurationDbContext(options, StoreOptions))
            {
                context.Clients.Add(testClient.ToEntity());
                context.SaveChanges();
            }

            Client client;

            using (var context = new ConfigurationDbContext(options, StoreOptions))
            {
                var store = new ClientStore(context, FakeLogger <ClientStore> .Create());
                client = await store.FindClientByIdAsync(testClient.ClientId);
            }

            client.Should().BeEquivalentTo(testClient);
        }
        public async Task FindClientByIdAsync_WhenClientExists_ExpectClientReturned()
        {
            var storeHolder = GetConfigurationDocumentStoreHolder();

            WaitForIndexing(storeHolder.IntegrationTest_GetDocumentStore());

            var testClient = new Client
            {
                ClientId   = "test_client",
                ClientName = "Test Client"
            };

            using (var session = storeHolder.OpenAsyncSession())
            {
                await session.StoreAsync(testClient.ToEntity());

                await session.SaveChangesAsync();
            }

            WaitForIndexing(storeHolder.IntegrationTest_GetDocumentStore());

            var store  = new ClientStore(storeHolder, FakeLogger <ClientStore> .Create());
            var client = await store.FindClientByIdAsync(testClient.ClientId);

            client.Should().NotBeNull();
        }
        public async Task Should_Retrieve_Client_If_It_Exists(TestDatabase testDb)
        {
            var testClient = new Client()
            {
                ClientId   = Guid.NewGuid().ToString(),
                ClientName = "Test Client"
            };

            using (var session = testDb.OpenSession())
            {
                await session.SaveAsync(testClient.ToEntity());

                await session.FlushAsync();
            }

            Client requestedClient;
            var    loggerMock = new Mock <ILogger <ClientStore> >();

            using (var session = testDb.OpenSession())
            {
                var store = new ClientStore(session, loggerMock.Object);
                requestedClient = await store.FindClientByIdAsync(testClient.ClientId);
            }

            requestedClient.Should().NotBeNull();

            await CleanupTestDataAsync(testDb);
        }
示例#7
0
        public async Task FindClientByIdAsync_should_return_client()
        {
            using var store = new RavenDbTestDriverWrapper().GetDocumentStore();
            using var s1    = store.OpenAsyncSession();

            await s1.StoreAsync(new Entity.Client
            {
                Id = "test",
                AllowedGrantTypes = new List <Entity.ClientGrantType>
                {
                    new Entity.ClientGrantType
                    {
                        Id = $"{nameof(Entity.ClientGrantType).ToLowerInvariant()}/test"
                    }
                }
            }, $"{nameof(Entity.Client)}/test");

            await s1.StoreAsync(new Entity.ClientGrantType
            {
                Id        = "test",
                GrantType = "client_credential"
            }, $"{nameof(Entity.ClientGrantType).ToLowerInvariant()}/test");

            await s1.SaveChangesAsync();

            var sut = new ClientStore(new ScopedAsynDocumentcSession(store.OpenAsyncSession()));

            var result = await sut.FindClientByIdAsync("test");

            Assert.NotNull(result);
            Assert.Contains(result.AllowedGrantTypes, g => g == "client_credential");
        }
        public async Task Should_Retrieve_Client_With_Allowed_Cors_Origins(TestDatabase testDb)
        {
            var testClient = new Client()
            {
                ClientId           = Guid.NewGuid().ToString(),
                ClientName         = "Test Client with CORS Origins",
                AllowedCorsOrigins =
                {
                    "*.tld1",
                    "*.tld2",
                    "*.tld3"
                }
            };

            using (var session = testDb.OpenSession())
            {
                await session.SaveAsync(testClient.ToEntity());

                await session.FlushAsync();
            }

            Client requestedClient;
            var    loggerMock = new Mock <ILogger <ClientStore> >();

            using (var session = testDb.OpenSession())
            {
                var store = new ClientStore(session, loggerMock.Object);
                requestedClient = await store.FindClientByIdAsync(testClient.ClientId);
            }

            requestedClient.Should().NotBeNull();
            requestedClient.AllowedCorsOrigins.Count.Should().Be(3);

            await CleanupTestDataAsync(testDb);
        }
示例#9
0
        public async Task FindClientByIdAsync_WhenClientExists_ExpectClientRetured()
        {
            var repo = g.configurationDb.GetRepository <IdentityServer4.Fsql.Storage.Entities.Client>();

            var testClient = new Client
            {
                ClientId   = "test_client",
                ClientName = "Test Client"
            };
            var entity = testClient.ToEntity();

            repo.Insert(entity);
            repo.SaveMany(entity, "AllowedCorsOrigins");
            repo.SaveMany(entity, "AllowedGrantTypes");
            repo.SaveMany(entity, "AllowedScopes");
            repo.SaveMany(entity, "Claims");
            repo.SaveMany(entity, "ClientSecrets");
            repo.SaveMany(entity, "IdentityProviderRestrictions");
            repo.SaveMany(entity, "PostLogoutRedirectUris");
            repo.SaveMany(entity, "Properties");
            repo.SaveMany(entity, "RedirectUris");


            Client client;
            var    store = new ClientStore(g.configurationDb, FakeLogger <ClientStore> .Create());

            client = await store.FindClientByIdAsync(testClient.ClientId);

            client.Should().NotBeNull();

            DeleteTestData(entity);
        }
        public async Task FindClientByIdAsync_WhenClientIdReceived_ExpectClientToBeReturned()
        {
            var store = new ClientStore(StoreOptions, new FakeLogger <ClientStore>());

            foreach (var testObject in GetClientTestObjects())
            {
                await store.StoreAsync(testObject);
            }

            var client = await store.FindClientByIdAsync("roclient");

            Assert.Single(client.Claims);
            Assert.Equal("role", client.Claims.ToArray()[0].Type);
            Assert.Equal("service", client.Claims.ToArray()[0].Value);

            Assert.Equal("https://cors/", client.AllowedCorsOrigins.ToArray()[0]);
            Assert.Equal("https://origin/", client.AllowedCorsOrigins.ToArray()[1]);

            Assert.Single(client.AllowedGrantTypes);
            Assert.Equal("password", client.AllowedGrantTypes.ToArray()[0]);

            Assert.Single(client.ClientSecrets);
            Assert.Equal("K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=", client.ClientSecrets.ToArray()[0].Value);
            Assert.Equal("SharedSecret", client.ClientSecrets.ToArray()[0].Type);

            Assert.Equal("api1", client.AllowedScopes.ToArray()[0]);
            Assert.Equal("api2.read_only", client.AllowedScopes.ToArray()[1]);

            Assert.Equal("provider", client.IdentityProviderRestrictions.ToArray()[0]);

            Assert.Equal("https://logout/redirect/", client.PostLogoutRedirectUris.ToArray()[0]);
            Assert.Equal("https://logout/redirect-failure/", client.PostLogoutRedirectUris.ToArray()[1]);

            Assert.Equal("https://redirect/", client.RedirectUris.ToArray()[0]);
        }
        public async Task FindClientByIdAsync_WhenClientExists_ExpectClientReturned()
        {
            using var ravenStore = GetDocumentStore();
            await new ClientIndex().ExecuteAsync(ravenStore);

            var testClient = new Client
            {
                ClientId   = "test_client",
                ClientName = "Test Client"
            };

            using (var session = ravenStore.OpenSession())
            {
                session.Store(testClient.ToEntity());
                session.SaveChanges();
            }

            WaitForIndexing(ravenStore);

            Client client;

            using (var session = ravenStore.OpenAsyncSession())
            {
                var store = new ClientStore(session, FakeLogger <ClientStore> .Create());
                client = await store.FindClientByIdAsync(testClient.ClientId);
            }

            client.Should().NotBeNull();
        }
示例#12
0
        public void FindClientByIdAsync_WhenClientExists_ExpectClientRetured(
            DbContextOptions <ConfigurationDbContext> options)
        {
            var testClient = new Client
            {
                ClientId   = "test_client",
                ClientName = "Test Client"
            };

            using (var context =
                       new ConfigurationDbContext(options, StoreOptions))
            {
                context.Clients.Add(testClient.ToEntity());
                context.SaveChanges();
            }

            Client client;

            using (var context =
                       new ConfigurationDbContext(options, StoreOptions))
            {
                var store = new ClientStore(
                    context,
                    NullLogger <ClientStore> .Create()
                    );

                client = store.FindClientByIdAsync(testClient.ClientId).Result;
            }

            Assert.NotNull(client);
        }
示例#13
0
        public async Task CanLoadClientById()
        {
            var store  = new ClientStore(Session);
            var client = await store.FindClientByIdAsync("codeclient");

            client.ShouldNotBe(null);
        }
示例#14
0
        public void FindClientByIdAsync_WhenClientExists_ExpectClientPropertiesRetured(DbContextOptions <ConfigurationDbContext> options)
        {
            var testClient = new Client
            {
                ClientId   = "properties_test_client",
                ClientName = "Properties Test Client",
                Properties =
                {
                    { "foo1", "bar1" },
                    { "foo2", "bar2" },
                }
            };

            using (var context = new ConfigurationDbContext(options, StoreOptions))
            {
                context.Clients.Add(testClient.ToEntity());
                context.SaveChanges();
            }

            Client client;

            using (var context = new ConfigurationDbContext(options, StoreOptions))
            {
                var store = new ClientStore(context, FakeLogger <ClientStore> .Create());
                client = store.FindClientByIdAsync(testClient.ClientId).Result;
            }

            client.Properties.Should().NotBeNull();
            client.Properties.Count.Should().Be(2);
            client.Properties.ContainsKey("foo1").Should().BeTrue();
            client.Properties.ContainsKey("foo2").Should().BeTrue();
            client.Properties["foo1"].Should().Be("bar1");
            client.Properties["foo2"].Should().Be("bar2");
        }
示例#15
0
        public async Task FindClientByIdAsync_WhenClientDoesNotExist_ExpectNull()
        {
            var store  = new ClientStore(g.configurationDb, FakeLogger <ClientStore> .Create());
            var client = await store.FindClientByIdAsync(Guid.NewGuid().ToString());

            client.Should().BeNull();
        }
示例#16
0
    public async Task Can_call_ClientStore_FindClientByIdAsync()
    => await ExecuteWithStrategyInTransactionAsync(
        async context =>
    {
        context.AddRange(
            new Client
        {
            ClientId = "C1", Description = "D1",
        },
            new Client
        {
            ClientId = "C2", Description = "D2",
        },
            new Client
        {
            ClientId = "C3", Description = "D3",
        });

        await context.SaveChangesAsync();
    },
        async context =>
    {
        var store = new ClientStore(context, new FakeLogger <ClientStore>());

        Assert.Equal("D2", (await store.FindClientByIdAsync("C2")).Description);
    }
        );
示例#17
0
        public async Task TestBackwardsCompatability()
        {
            var context = GetConfigContext();

            var clientStore = new ClientStore(context);
            var client1     = await clientStore.FindClientByIdAsync("myday-web-c5da2136-7b39-4def-b6e0-1574595c71f6");

            var client2 = await clientStore.FindClientByIdAsync("scim-c5da2136-7b39-4def-b6e0-1574595c71f6");

            Assert.IsNotNull(client1);
            Assert.AreEqual("client_", client1.ClientClaimsPrefix);
            Assert.IsTrue(client1.FrontChannelLogoutSessionRequired);
            Assert.IsTrue(client1.BackChannelLogoutSessionRequired);
            Assert.IsNotNull(client2);
            Assert.AreEqual(null, client2.ClientClaimsPrefix);
            Assert.IsFalse(client2.FrontChannelLogoutSessionRequired);
            Assert.IsFalse(client2.BackChannelLogoutSessionRequired);
        }
        public async Task FindClientByIdAsync_WhenClientsExistWithManyCollections_ExpectClientReturnedInUnderFiveSeconds()
        {
            var storeHolder = GetConfigurationDocumentStoreHolder();

            var testClient = new Client
            {
                ClientId          = "test_client_with_uris",
                ClientName        = "Test client with URIs",
                AllowedScopes     = { "openid", "profile", "api1" },
                AllowedGrantTypes = GrantTypes.CodeAndClientCredentials
            };

            for (int i = 0; i < 50; i++)
            {
                testClient.RedirectUris.Add($"https://localhost/{i}");
                testClient.PostLogoutRedirectUris.Add($"https://localhost/{i}");
                testClient.AllowedCorsOrigins.Add($"https://localhost:{i}");
            }

            using (var session = storeHolder.OpenAsyncSession())
            {
                await session.StoreAsync(testClient.ToEntity());

                for (int i = 0; i < 50; i++)
                {
                    await session.StoreAsync(new Client
                    {
                        ClientId               = testClient.ClientId + i,
                        ClientName             = testClient.ClientName,
                        AllowedScopes          = testClient.AllowedScopes,
                        AllowedGrantTypes      = testClient.AllowedGrantTypes,
                        RedirectUris           = testClient.RedirectUris,
                        PostLogoutRedirectUris = testClient.PostLogoutRedirectUris,
                        AllowedCorsOrigins     = testClient.AllowedCorsOrigins,
                    }.ToEntity());
                }

                await session.SaveChangesAsync();
            }

            WaitForIndexing(storeHolder.IntegrationTest_GetDocumentStore());

            var store = new ClientStore(storeHolder, FakeLogger <ClientStore> .Create());

            const int timeout = 5000;
            var       task    = Task.Run(() => store.FindClientByIdAsync(testClient.ClientId));

            if (await Task.WhenAny(task, Task.Delay(timeout)) == task)
            {
                var client = task.Result;
                client.Should().BeEquivalentTo(testClient);
            }
            else
            {
                throw new TestTimeoutException(timeout);
            }
        }
示例#19
0
    public async Task FindClientByIdAsync_WhenClientsExistWithManyCollections_ExpectClientReturnedInUnderFiveSeconds(DbContextOptions <ConfigurationDbContext> options)
    {
        var testClient = new Client
        {
            ClientId          = "test_client_with_uris",
            ClientName        = "Test client with URIs",
            AllowedScopes     = { "openid", "profile", "api1" },
            AllowedGrantTypes = GrantTypes.CodeAndClientCredentials
        };

        for (int i = 0; i < 50; i++)
        {
            testClient.RedirectUris.Add($"https://localhost/{i}");
            testClient.PostLogoutRedirectUris.Add($"https://localhost/{i}");
            testClient.AllowedCorsOrigins.Add($"https://localhost:{i}");
        }

        using (var context = new ConfigurationDbContext(options))
        {
            context.Clients.Add(testClient.ToEntity());

            for (int i = 0; i < 50; i++)
            {
                context.Clients.Add(new Client
                {
                    ClientId               = testClient.ClientId + i,
                    ClientName             = testClient.ClientName,
                    AllowedScopes          = testClient.AllowedScopes,
                    AllowedGrantTypes      = testClient.AllowedGrantTypes,
                    RedirectUris           = testClient.RedirectUris,
                    PostLogoutRedirectUris = testClient.PostLogoutRedirectUris,
                    AllowedCorsOrigins     = testClient.AllowedCorsOrigins,
                }.ToEntity());
            }

            context.SaveChanges();
        }

        using (var context = new ConfigurationDbContext(options))
        {
            var store = new ClientStore(context, FakeLogger <ClientStore> .Create(), new NoneCancellationTokenProvider());

            const int timeout = 5000;
            var       task    = Task.Run(() => store.FindClientByIdAsync(testClient.ClientId));

            if (await Task.WhenAny(task, Task.Delay(timeout)) == task)
            {
                var client = task.Result;
                client.Should().BeEquivalentTo(testClient);
            }
            else
            {
                throw new TestTimeoutException(timeout);
            }
        }
    }
        public async Task FindClientByIdAsync_WhenClientDoesNotExist_ExpectNull(DbContextOptions <ConfigurationDbContext> options)
        {
            using (var context = new ConfigurationDbContext(options, StoreOptions))
            {
                var store  = new ClientStore(context, FakeLogger <ClientStore> .Create());
                var client = await store.FindClientByIdAsync(Guid.NewGuid().ToString());

                client.Should().BeNull();
            }
        }
        public async Task FindClientByIdAsync_WhenClientDoesNotExist_ExpectNull()
        {
            var storeHolder = GetConfigurationDocumentStoreHolder();

            WaitForIndexing(storeHolder.IntegrationTest_GetDocumentStore());

            var store  = new ClientStore(storeHolder, FakeLogger <ClientStore> .Create());
            var client = await store.FindClientByIdAsync(Guid.NewGuid().ToString());

            client.Should().BeNull();
        }
        public static async Task <List <FlattenedAuthorizationCodeHandle> > InsertTestData_AuthorizationCode(int count = 1)
        {
            var dao = new IdentityServer3CassandraDao();
            await dao.EstablishConnectionAsync();

            IClientStore clientStore  = new ClientStore();
            var          insertTokens = await CassandraTestHelper.InsertTestData_Tokens(count); // only add one client

            var clientId     = insertTokens[0].ClientId;
            var clientRecord = await clientStore.FindClientByIdAsync(clientId);

            List <FlattenedAuthorizationCodeHandle> result = new List <FlattenedAuthorizationCodeHandle>();
            int i = 0;

            foreach (var insertToken in insertTokens)
            {
                var claimIdentityRecords = new List <ClaimIdentityRecord>()
                {
                    new ClaimIdentityRecord()
                    {
                        AuthenticationType = Constants.PrimaryAuthenticationType,
                        ClaimTypeRecords   = new List <ClaimTypeRecord>()
                        {
                            new ClaimTypeRecord()
                            {
                                Type      = Constants.ClaimTypes.Subject,
                                Value     = "Value:" + i,
                                ValueType = "VALUETYPE:" + i
                            }
                        }
                    }
                };
                FlattenedAuthorizationCodeHandle handle = new FlattenedAuthorizationCodeHandle
                {
                    ClientId        = clientId,
                    SubjectId       = insertToken.SubjectId,
                    Expires         = DateTimeOffset.UtcNow.AddMinutes(5),
                    CreationTime    = DateTimeOffset.UtcNow,
                    IsOpenId        = true,
                    RedirectUri     = "REDIRECTURI/" + i,
                    WasConsentShown = true,
                    Nonce           = "NONCE:" + i,

                    ClaimIdentityRecords = new FlattenedAuthorizationCodeHandle().SerializeClaimsIdentityRecords(claimIdentityRecords),
                    RequestedScopes      = new FlattenedAuthorizationCodeHandle().SerializeRequestScopes(clientRecord.AllowedScopes),
                    Key = Guid.NewGuid().ToString()
                };
                ++i;
                result.Add(handle);
            }
            await dao.CreateManyAuthorizationCodeHandleAsync(result);

            return(result);
        }
示例#23
0
        public void TestFindClientByIdAsync()
        {
            var insert = ClientStoreTest.InsertTestData(_clientStore, _scopeStore, 1);

            Guid id           = insert[0].Id;
            var  result       = _clientStore.FindClientByIdAsync(insert[0].Record.ClientId);
            var  clientRecord = new ClientRecord(result.Result.ToClientHandle());


            Assert.AreEqual(clientRecord.Id, id);
        }
        static List <AuthorizationCodeHandleRecord> InsertTestData(ClientStore clientStore,
                                                                   ScopeStore scopeStore,
                                                                   AuthorizationCodeStore authorizationCodeStore,
                                                                   TokenHandleStore ths, int count = 1)
        {
            var tokenInsert = TokenHandleStoreTest.InsertTestData(clientStore, scopeStore, ths, 10);

            var    clientId    = tokenInsert[0].Record.ClientId;
            string subjectSeed = Guid.NewGuid().ToString();
            List <AuthorizationCodeHandleRecord> result = new List <AuthorizationCodeHandleRecord>();
            int i = 0;

            foreach (var tokenRecord in tokenInsert)
            {
                var client = clientStore.FindClientByIdAsync(tokenRecord.Record.ClientId);

                AuthorizationCodeHandle handle = new AuthorizationCodeHandle
                {
                    ClientId        = tokenRecord.Record.ClientId,
                    SubjectId       = tokenRecord.Record.SubjectId,
                    Expires         = DateTimeOffset.UtcNow.AddMinutes(5),
                    CreationTime    = DateTimeOffset.UtcNow,
                    IsOpenId        = true,
                    RedirectUri     = "REDIRECTURI/" + i,
                    WasConsentShown = true,
                    Nonce           = "NONCE:" + i,

                    ClaimIdentityRecords = new List <ClaimIdentityRecord>()
                    {
                        new ClaimIdentityRecord()
                        {
                            AuthenticationType = Constants.PrimaryAuthenticationType,
                            ClaimTypeRecords   = new List <ClaimTypeRecord>()
                            {
                                new ClaimTypeRecord()
                                {
                                    Type      = Constants.ClaimTypes.Subject,
                                    Value     = tokenRecord.Record.SubjectId,
                                    ValueType = "VALUETYPE:" + i
                                }
                            }
                        }
                    },
                    RequestedScopes = client.Result.AllowedScopes,
                    Key             = Guid.NewGuid().ToString(),
                };

                var handleRecord = new AuthorizationCodeHandleRecord(handle);
                authorizationCodeStore.CreateAsync(handleRecord.Record);
                result.Add(handleRecord);
                ++i;
            }
            return(result);
        }
        public async Task Should_Not_Retrieve_Non_Existing_Client(TestDatabase testDb)
        {
            Client requestedClient;
            var    loggerMock = new Mock <ILogger <ClientStore> >();

            using (var session = testDb.OpenSession())
            {
                var store = new ClientStore(session, loggerMock.Object);
                requestedClient = await store.FindClientByIdAsync("not_existing_client");
            }

            requestedClient.Should().BeNull();

            await CleanupTestDataAsync(testDb);
        }
        public async Task FindClientByIdAsync_WhenClientDoesNotExist_ExpectNull()
        {
            using var ravenStore = GetDocumentStore();
            await new ClientIndex().ExecuteAsync(ravenStore);

            WaitForIndexing(ravenStore);

            using (var session = ravenStore.OpenAsyncSession())
            {
                var store  = new ClientStore(session, FakeLogger <ClientStore> .Create());
                var client = await store.FindClientByIdAsync(Guid.NewGuid().ToString());

                client.Should().BeNull();
            }
        }
        public async Task ClientStore_SaveGetByClientIdTest()
        {
            Stopwatch stopwatch = new Stopwatch();

            var storageContext = Services.BuildServiceProvider().GetService <ClientStorageContext>();

            Assert.IsNotNull(storageContext);

            var store = new ClientStore(storageContext, _logger);

            Assert.IsNotNull(store);

            var client = CreateTestObject();

            Console.WriteLine(JsonConvert.SerializeObject(client));

            stopwatch.Start();
            await store.StoreAsync(client);

            stopwatch.Stop();
            Console.WriteLine($"ClientStore.StoreAsync({client.ClientId}): {stopwatch.ElapsedMilliseconds} ms");

            stopwatch.Reset();
            stopwatch.Start();
            var findClient = await store.FindClientByIdAsync(client.ClientId);

            stopwatch.Stop();
            Console.WriteLine($"ClientStore.FindClientByIdAsync({client.ClientId}): {stopwatch.ElapsedMilliseconds} ms");
            Assert.AreEqual <string>(client.ClientId, findClient.ClientId);

            stopwatch.Reset();
            stopwatch.Start();
            var clients = await store.GetAllClients();

            int count = clients.Count();

            stopwatch.Stop();
            Console.WriteLine($"ClientStore.GetAllClients() Count: {count} : {stopwatch.ElapsedMilliseconds} ms");
            Assert.IsTrue(count > 0);

            stopwatch.Reset();
            stopwatch.Start();
            var getClient = (await store.GetAllClients()).FirstOrDefault(f => f.ClientId == client.ClientId);

            stopwatch.Stop();
            Console.WriteLine($"ClientStore.GetAllClients(): {stopwatch.ElapsedMilliseconds} ms");
            Assert.IsNotNull(getClient);
        }
        public async Task ClientStore_RemoveByClientIdTest()
        {
            var storageContext = Services.BuildServiceProvider().GetService <ClientStorageContext>();

            Assert.IsNotNull(storageContext);

            var store = new ClientStore(storageContext, _logger);

            Assert.IsNotNull(store);

            var client = CreateTestObject();

            client.ClientId = Guid.NewGuid().ToString();
            Console.WriteLine(JsonConvert.SerializeObject(client));

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            await store.StoreAsync(client);

            stopwatch.Stop();
            Console.WriteLine($"ClientStore.StoreAsync({client.ClientId}): {stopwatch.ElapsedMilliseconds} ms");
            stopwatch.Reset();

            stopwatch.Start();
            await store.RemoveAsync(client.ClientId);

            stopwatch.Stop();
            Console.WriteLine($"ClientStore.RemoveAsync({client.ClientId}): {stopwatch.ElapsedMilliseconds} ms");

            stopwatch.Reset();
            stopwatch.Start();
            var findClient = await store.FindClientByIdAsync(client.ClientId);

            stopwatch.Stop();
            Console.WriteLine($"ClientStore.FindClientByIdAsync({client.ClientId}): {stopwatch.ElapsedMilliseconds} ms");
            Assert.IsNull(findClient);

            stopwatch.Reset();
            stopwatch.Start();
            var getClient = (await store.GetAllClients()).FirstOrDefault(f => f.ClientId == client.ClientId);

            stopwatch.Stop();
            Console.WriteLine($"ClientStore.GetAllClients(): {stopwatch.ElapsedMilliseconds} ms");
            Assert.IsNull(getClient);
        }
        public async Task FindClientByIdAsync_WhenClientExists_ExpectClientRetured()
        {
            var testClient = new Client
            {
                ClientId   = "test_client",
                ClientName = "Test Client"
            };

            await _context.Clients.Document(testClient.ClientId).SetAsync(testClient.ToEntity());

            Client client;
            var    store = new ClientStore(_context, FakeLogger <ClientStore> .Create());

            client = await store.FindClientByIdAsync(testClient.ClientId);

            client.Should().NotBeNull();
        }
        public async Task FindClientByIdAsync_WhenClientExists_ExpectClientRetured(ISessionFactory sessionFactory)
        {
            var testClient = CreateTestClient();

            using (var provider = new ConfigurationSessionProvider(sessionFactory.OpenSession))
            {
                await provider.Session.SaveAsync(_mapper.Map <Entities.Client>(testClient));
            }

            Client client;

            using (var provider = new ConfigurationSessionProvider(sessionFactory.OpenSession))
            {
                var store = new ClientStore(provider);
                client = await store.FindClientByIdAsync(testClient.ClientId);
            }

            Assert.NotNull(client);
        }