Example #1
0
        public void Serialize_ParentTestClass_ReturnsValidXml()
        {
            // Arrange
            var test = new ParentTestClass
            {
                Children = new List <TestClass>
                {
                    new TestClass {
                        FirstName = "John", LastName = "Doe"
                    },
                    new TestClass {
                        FirstName = "Jane", LastName = "Doe"
                    }
                },
                Spouse = new TestClass {
                    FirstName = "Jeff", LastName = "Doe"
                }
            };
            var validatorMessages = new XmlValidatorChecks();
            var schema            = GetFileContents("ParentTestClass.xsd");
            var xdoc = new XmlDocument();

            xdoc.Schemas.Add(string.Empty, XmlReader.Create(new StringReader(schema)));

            // Act
            var xml = _xmlSerializer.Serialize(test);

            xdoc.LoadXml(xml);
            xdoc.Validate(validatorMessages.HandleValidationError);

            // Assert
            Assert.True(validatorMessages.IsValid, string.Join("\r\n", validatorMessages.Errors));
        }
Example #2
0
        public void Serialize_ParentTestClass_MatchesSchema()
        {
            // Arrange
            var test = new ParentTestClass
            {
                Children = new List <TestClass>
                {
                    new TestClass {
                        FirstName = "John", LastName = "Doe"
                    },
                    new TestClass {
                        FirstName = "Jane", LastName = "Doe"
                    }
                },
                Spouse = new TestClass {
                    FirstName = "Jeff", LastName = "Doe"
                }
            };
            var schema = JsonSchema.Parse(GetFileContents("ParentTestClass.schema.json"));

            // Act
            var json       = _jsonSerializer.Serialize(test);
            var jsonObject = JObject.Parse(json);

            // Assert
            Assert.True(jsonObject.IsValid(schema), "JSON serialization for [ParentTestClass] does not match schema.");
        }
Example #3
0
        public void Copy_MustCopyParentReference()
        {
            // Arrange
            var testClassParentOriginal = new ParentTestClass();

            testClassParentOriginal.Child = new ChildTestClass()
            {
                ParentReference = testClassParentOriginal,
            };

            var testClassParentCopy = new ParentTestClass();

            // Act
            this.testCandidate.Copy(
                testClassParentOriginal,
                testClassParentCopy,
                new List <IBaseAdditionalProcessing>());

            // Assert
            // Make sure original and copy of the parent object are not the same.
            testClassParentCopy.Should().NotBeSameAs(testClassParentOriginal);

            // Check if the Child's new reference is correctly set to the copied parent's reference.
            testClassParentCopy.Should().BeSameAs(testClassParentCopy.Child.ParentReference);
        }
Example #4
0
        public void SearchNestedTypeTest()
        {
            //ARRANGE
            var id = Guid.NewGuid();
            //set up search client
            var dependencyResolver = new DependencyResolverMock();

            var client = SearchClientFactory.GetClient();

            //create index name
            var indexName = String.Format("{0}_{1}", typeof(ParentTestClass).Name, id).ToLower();
            var index     = new IndexName {
                Name = indexName, Type = typeof(ParentTestClass)
            };

            try
            {
                var indexDescriptor = new CreateIndexDescriptor(index)
                                      .Mappings(map => map.Map <ParentTestClass>(m =>
                                                                                 m.AutoMap()
                                                                                 .Properties(p => p.Nested <ChildClass>(n => n.Name(parent => parent.Children)))));

                var createIndexRequest = client.CreateIndex(indexDescriptor);

                var testClass = new ParentTestClass();
                testClass.Children.Add(new ChildClass());
                var createDocumentResponse = client.Create(testClass, d => d.Index(index)
                                                           .Type(typeof(ParentTestClass)));

                Thread.Sleep(1000);
                //ACT
                //Search
                var searchResponse = client
                                     .Search <ParentTestClass>(s =>
                                                               s.Query(q =>
                                                                       q.Nested(nq =>
                                                                                nq.Path(p => p.Children)
                                                                                .Query(oq =>
                                                                                       oq.Match(m => m.Field(g => g.Children.First().Name)
                                                                                                .Query(testClass.Children.First().Name.ToString()))).IgnoreUnmapped()))
                                                               .Index(Indices.Index(index)));

                var allRecords = client
                                 .Search <ParentTestClass>(q => q
                                                           .Index(Indices.Index(index)));

                //ASSERT
                Assert.IsTrue(searchResponse.IsValid);
                Assert.AreEqual(1, searchResponse.Documents.Count());
                Assert.AreEqual(testClass.Id, searchResponse.Documents.First().Id);
                Assert.AreEqual(1, searchResponse.Documents.First().Children.Count());
                Assert.AreEqual(testClass.Children.First().Id, searchResponse.Documents.First().Children.First().Id);
            }
            finally
            {
                var deleteIndexResult = client.DeleteIndex(index);
            }
        }
        public void Test()
        {
            //ARRANGE

            //set up search client
            var dependencyResolver = new DependencyResolverMock();

            var client        = SearchClientFactory.GetClient();
            var clientFactory = SearchClientFactory.GetClientFactory();

            SearchClientFactory.RegisterDependencies(dependencyResolver);

            //delete existing index
            var index = new IndexName {
                Name = typeof(ParentTestClass).Name.ToLower(), Type = typeof(ParentTestClass)
            };
            var deleteIndexResult = client.DeleteIndex(Indices.Index(index));

            //set up document CRUD controller and create a mock document
            var responseHandler = new ResponseHandler();
            var indexManager    = new IndexManager(dependencyResolver, clientFactory, responseHandler);
            //var documentclient = new DocumentController(clientFactory, indexManager);

            //dependencyResolver.RegisterFactory<IndexMapper<ParentTestClass>>(t => new TestIndexMapper(), Lifetime.Transient);

            var testClass = new ParentTestClass();

            testClass.Children.Add(new ChildClass());
            //documentclient.CreateDocument(testClass);
            this.CreateDocument(testClass, index, client);

            var indexMeta = client.GetIndex(Indices.Index(index));

            Thread.Sleep(1000);
            //ACT
            //Search
            var searchResponse = client
                                 .Search <ParentTestClass>(s =>
                                                           s.Query(q =>
                                                                   q.Nested(nq =>
                                                                            nq.Path(p => p.Children)
                                                                            .Query(oq =>
                                                                                   oq.Match(m => m.Field(g => g.Children.First().Name)
                                                                                            .Query(testClass.Children.First().Name.ToString()))).IgnoreUnmapped()))
                                                           .Index(Indices.Index(index)));

            var allRecords = client
                             .Search <ParentTestClass>(q => q
                                                       .Index(Indices.Index(index)));

            //ASSERT
            Assert.IsTrue(searchResponse.IsValid);
            Assert.AreEqual(1, searchResponse.Documents.Count());
            Assert.AreEqual(testClass.Id, searchResponse.Documents.First().Id);
            Assert.AreEqual(1, searchResponse.Documents.First().Children.Count());
            Assert.AreEqual(testClass.Children.First().Id, searchResponse.Documents.First().Children.First().Id);
        }
Example #6
0
        public void MustUseStrategyWhenCopying()
        {
            // Arrange
            var testClassParentOriginal = new ParentTestClass();

            testClassParentOriginal.AddChild(new ChildTestClass()
            {
                TestValue = 1, Parent = testClassParentOriginal
            });
            testClassParentOriginal.AddChild(new ChildTestClass()
            {
                TestValue = 2, Parent = testClassParentOriginal
            });
            testClassParentOriginal.AddChild(new ChildTestClass()
            {
                TestValue = 3, Parent = testClassParentOriginal
            });

            var testClassParentCopy = new ParentTestClass();

            // Act
            this.testCandidate.Copy(
                testClassParentOriginal,
                testClassParentCopy,
                new List <IBaseAdditionalProcessing>());

            var testClassParentCopyChildren   = testClassParentCopy.Children.Cast <ChildTestClass>().ToList();
            var testClassParentOriginchildren = testClassParentOriginal.Children.Cast <ChildTestClass>().ToList();

            // Assert
            // Make sure original and copy of the parent object are not the same.
            testClassParentCopy.Should().NotBeSameAs(testClassParentOriginal);

            testClassParentCopyChildren.Count.Should().Be(3);

            testClassParentCopyChildren.ElementAt(0).TestValue.Should().Be(testClassParentOriginchildren.ElementAt(0).TestValue * 2);
            testClassParentCopyChildren.ElementAt(1).TestValue.Should().Be(testClassParentOriginchildren.ElementAt(1).TestValue * 2);
            testClassParentCopyChildren.ElementAt(2).TestValue.Should().Be(testClassParentOriginchildren.ElementAt(2).TestValue * 2);

            foreach (var copiedChild in testClassParentCopyChildren)
            {
                foreach (var originalChild in testClassParentOriginal.Children)
                {
                    originalChild.Should().NotBeSameAs(copiedChild);
                }
            }

            // Check for the correct referential reverse relation copy.
            foreach (var child in testClassParentCopyChildren)
            {
                child.Parent.Should().BeSameAs(testClassParentCopy);
            }
        }
        private void CreateDocument(ParentTestClass document, IndexName index, ElasticClient client)
        {
            //var index = new IndexName { Name = "TestName", Type = typeof(ParentTestClass) };
            var descriptor = new CreateIndexDescriptor(index);
            var t          = new Test();

            var t1 = new Test1();

            Func <Func <TypeMappingDescriptor <ParentTestClass>, ITypeMapping>, CreateIndexDescriptor> seed = f =>
            {
                descriptor = descriptor.Mappings(m => m.Map <ParentTestClass>(f));
                return(descriptor);
            };

            var list = new List <Test> {
                t, t1
            };

            var res = list.Aggregate(seed, (x, next) =>
            {
                //throw new NotImplementedException();

                var returnRes = new Func <Func <TypeMappingDescriptor <ParentTestClass>, ITypeMapping>, CreateIndexDescriptor>
                                (
                    pr =>
                {
                    x(next.F(pr));

                    return(descriptor);

                    throw new NotImplementedException();
                });
                return(returnRes);
            });

            var ex = res(new Func <TypeMappingDescriptor <ParentTestClass>, ITypeMapping>(q => null));

            client.CreateIndex(descriptor);
            var documentType = document.GetType();
            //var client = this._clientFactory.GetClient();

            var documentPath = new DocumentPath <ParentTestClass>(document);

            //var index = this.GetIndex(document, client);

            documentPath.Type(documentType);
            documentPath.Index(index);

            var createRequest = new CreateRequest <ParentTestClass>(documentPath);

            var response = client.Create(createRequest);
        }
        public void DispatchToKafkaServerTest()
        {
            //ARRANGE
            var documentId = Guid.NewGuid();
            var document   = new ParentTestClass {
                Email = "*****@*****.**", IntField = 10, DateFiled = DateTimeOffset.Now, Child = new ChildClass {
                    Name = "Child1", ChildEmail = "*****@*****.**", ChildIntField = 100, ChildDateFiled = DateTimeOffset.Now
                }
            };

            document.Child.Parent = document;

            var dependencyResolver = new DependencyResolverMock();

            //var client = SearchClientFactory.GetClient();
            //var clientFactory = SearchClientFactory.GetClientFactory();
            //SearchClientFactory.RegisterDependencies(dependencyResolver);

            ////create an unique index
            var indexId               = Guid.NewGuid();
            var indexName             = String.Format("{0}_{1}", typeof(ParentTestClass).Name, indexId);
            var indexContext          = new IndexContext(typeof(ParentTestClass), indexName);
            var producerConfigManager = new ProducerConfigManager(dependencyResolver);

            dependencyResolver.RegisterFactory <IConfigurationProvider>((t) => new ClientIdProvider(), Lifetime.Transient);
            dependencyResolver.RegisterFactory <IConfigurationProvider>((t) => new EndPoindProvider(), Lifetime.Transient);
            dependencyResolver.RegisterFactory <IConfigurationProvider>((t) => new ProducerTopicConfigProvider(), Lifetime.Transient);
            ////set up document CRUD controller and create a mock document
            //var responseHandler = new ResponseHandler();
            //var indexManager = new IndexManager(dependencyResolver, clientFactory, responseHandler);
            //var documentDispatcher = new DocumentDispatcher(clientFactory, indexManager, responseHandler);
            //var documentclient = new DocumentController(documentDispatcher, indexManager, responseHandler);
            try
            {
                var context = new UpsertDocumentContext <ParentTestClass>(documentId)
                {
                    Document = document, IndexContext = indexContext
                };
                var dispatcher = new KafkaDispatcherConfuence(producerConfigManager);
                //ACT
                dispatcher.UpsertDocument(context);
                //.Wait();

                //ASSERT
            }
            finally
            {
            }
        }
Example #9
0
        public void Copy_MustFailWhenChildrenistNull()
        {
            // Arrange
            var testClassParentOriginal = new ParentTestClass();

            testClassParentOriginal.MakeChildrenCollectionNull();

            var testClassParentCopy = new ParentTestClass();

            // Act / Assert throws
            Assert.Throws <ArgumentNullException>(() =>
                                                  this.testCandidate.Copy(
                                                      testClassParentOriginal,
                                                      testClassParentCopy,
                                                      new List <IBaseAdditionalProcessing>()));
        }
        public void Copy_MustFailWhenChildrenistNull()
        {
            // Arrange
            var testClassParentOriginal = new ParentTestClass();

            testClassParentOriginal.MakeChildrenCollectionNull();

            var testClassParentCopy = new ParentTestClass();

            // Act / Assert throws
            // This exception is not originating from XUnit per se,
            // but from the assertion library which is itself using
            // Xunit internally.
            Assert.Throws <ArgumentNullException>(() =>
                                                  this.testCandidate.Copy(
                                                      testClassParentOriginal,
                                                      testClassParentCopy,
                                                      new List <IBaseAdditionalProcessing>()));
        }
Example #11
0
        public void Copy_MustCopyInheritedChildrenWhenIntercepted()
        {
            // Arrange
            var testClassParentOriginal = new ParentTestClass();

            testClassParentOriginal.AddChild(new ChildTestClass()
            {
                ParentReference = testClassParentOriginal,
            });
            testClassParentOriginal.AddChild(new ChildTestClass2()
            {
                ParentReference = testClassParentOriginal,
            });
            testClassParentOriginal.AddChild(new ChildTestClass()
            {
                ParentReference = testClassParentOriginal,
            });

            var testClassParentCopy = new ParentTestClass();

            // Act
            this.testCandidate.Copy(
                testClassParentOriginal,
                testClassParentCopy,
                new List <IBaseAdditionalProcessing>
            {
                new GenericContinueCopyInterception <IChildTestClass2>(obj => false),
            });

            var testClassParentCopyChildren = testClassParentCopy.Children.Cast <ChildTestClass>().ToList();

            // Assert
            // Make sure original and copy of the parent object are not the same.
            testClassParentCopy.Should().NotBeSameAs(testClassParentOriginal);

            testClassParentOriginal.Children.Count.Should().Be(3);

            foreach (var childhild in testClassParentCopyChildren)
            {
                childhild.ParentReference.Should().BeSameAs(testClassParentCopy);
            }
        }
Example #12
0
        public void CreateDocumentTest()
        {
            //ARRANGE
            var indexId = Guid.NewGuid();

            var client        = SearchClientFactory.GetClient();
            var clientFactory = SearchClientFactory.GetClientFactory();

            var index = new IndexName {
                Name = String.Format("{0}_{1}", typeof(ParentTestClass).Name, indexId).ToLower(), Type = typeof(ParentTestClass)
            };

            var testClass = new ParentTestClass();

            testClass.Children.Add(new ChildClass());

            var documentPath = new DocumentPath <ParentTestClass>(testClass)
                               .Index(index)
                               .Type(typeof(ParentTestClass));

            var createRequest = new CreateRequest <ParentTestClass>(documentPath);

            //ACT
            try
            {
                var createResponse = client.Create(createRequest);
                Thread.Sleep(1000);

                var getResponse = client.Get <ParentTestClass>(documentPath);
                var document    = getResponse.Source;
                //ASSERT
                Assert.IsTrue(createResponse.IsValid);
                Assert.IsTrue(getResponse.IsValid);
                Assert.AreEqual(testClass.Id, document.Id);
                Assert.AreEqual(testClass.Children.Count, document.Children.Count);
                Assert.AreEqual(testClass.Children.ElementAt(0).Id, document.Children.ElementAt(0).Id);
            }
            finally
            {
                var deleteIndexResult = client.DeleteIndex(index);
            }
        }
Example #13
0
        public void Copy_MustCopyEmptyCollection()
        {
            // Arrange
            var testClassParentOriginal = new ParentTestClass();

            var testClassParentCopy = new ParentTestClass();

            // Act
            this.testCandidate.Copy(
                testClassParentOriginal,
                testClassParentCopy,
                new List <IBaseAdditionalProcessing>());

            // Assert
            // Make sure original and copy of the parent object are not the same.
            // Also make sure the parent test class children collection, which is empty, was copied.
            testClassParentCopy.Should().NotBeSameAs(testClassParentOriginal);
            testClassParentCopy.Children.Should().NotBeSameAs(testClassParentOriginal.Children);
            testClassParentCopy.Should().NotBeNull();
        }
        public void Copy_MustCopyParentReference()
        {
            // Arrange
            var testClassParentOriginal = new ParentTestClass();

            testClassParentOriginal.AddChild(new ChildTestClass()
            {
                ParentReference = testClassParentOriginal,
            });
            testClassParentOriginal.AddChild(new ChildTestClass()
            {
                ParentReference = testClassParentOriginal,
            });
            testClassParentOriginal.AddChild(new ChildTestClass()
            {
                ParentReference = testClassParentOriginal,
            });

            var testClassParentCopy = new ParentTestClass();

            // Act
            this.testCandidate.Copy(
                testClassParentOriginal,
                testClassParentCopy,
                new List <IBaseAdditionalProcessing>());

            var testClassParentCopyChildren = testClassParentCopy.Children.OfType <ChildTestClass>().ToList();

            // Assert
            // Make sure original and copy of the parent object are not the same.
            testClassParentCopy.Should().NotBeSameAs(testClassParentOriginal);

            // Don't forget to do this! Since the Children are a Collection the above wy of
            // retrieving the ist is not typesafe and some objects could fall between chairs and table.
            testClassParentCopyChildren.Count.Should().Be(3);

            foreach (var child in testClassParentCopyChildren)
            {
                child.ParentReference.Should().BeSameAs(testClassParentCopy);
            }
        }
Example #15
0
        public void Copy_MustNotFailWhenChildIsNull()
        {
            // Arrange
            var testClassParentOriginal = new ParentTestClass
            {
                Child = null,
            };

            var testClassParentCopy = new ParentTestClass();

            // Act
            this.testCandidate.Copy(
                testClassParentOriginal,
                testClassParentCopy,
                new List <IBaseAdditionalProcessing>());

            // Assert
            // Make sure original and copy of the parent object are not the same.
            testClassParentCopy.Should().NotBeSameAs(testClassParentOriginal);

            // Check if the Child of the copied class is null
            testClassParentCopy.Child.Should().BeNull();
        }
Example #16
0
        public void Serialization_ThenDeserialization_OfParentTestClass_MatchesInput()
        {
            // Arrange
            var input = new ParentTestClass
            {
                Children = new List <TestClass>
                {
                    new TestClass {
                        FirstName = "John", LastName = "Doe"
                    },
                    new TestClass {
                        FirstName = "Jane", LastName = "Doe"
                    }
                },
                Spouse = new TestClass {
                    FirstName = "Jeff", LastName = "Doe"
                }
            };

            // Act
            var json = _jsonSerializer.Serialize(input);

#if IMMUTABLE
            var output = _jsonSerializer.Deserialize <ParentTestClass>(json).Value;
#else
            var output = _jsonSerializer.Deserialize <ParentTestClass>(json);
#endif

            // Assert
            for (int i = 0; i < input.Children.Count; i++)
            {
                Assert.Equal(input.Children.ToList()[i].FirstName, output.Children.ToList()[i].FirstName);
                Assert.Equal(input.Children.ToList()[i].LastName, output.Children.ToList()[i].LastName);
            }
            Assert.Equal(input.Spouse.FirstName, output.Spouse.FirstName);
            Assert.Equal(input.Spouse.LastName, output.Spouse.LastName);
        }
Example #17
0
        public void PartialUpdateDocument_by_doc()
        {
            //ARRANGE

            //set up search client

            var client        = SearchClientFactory.GetClient();
            var clientFactory = SearchClientFactory.GetClientFactory();

            //create an index name
            var indexId = Guid.NewGuid();
            var index   = new IndexName {
                Name = String.Format("{0}_{1}", typeof(ParentTestClass).Name, indexId).ToLower(), Type = typeof(ParentTestClass)
            };

            //create a parent class and add 2 children
            var testClass = new ParentTestClass();
            var child1    = new ChildClass();
            var child2    = new ChildClass();

            testClass.Children.Add(child1);
            testClass.Children.Add(child2);

            //create document path
            var documentPath = new DocumentPath <ParentTestClass>(testClass)
                               .Index(index)
                               .Type(typeof(ParentTestClass));

            //ACT
            try
            {
                //create a new parent class document
                var createRequest  = new CreateRequest <ParentTestClass>(documentPath);
                var createResponse = client.Create(createRequest);
                //wait to be indexed
                Thread.Sleep(1000);

                //load the created document
                var getResponse           = client.Get <ParentTestClass>(documentPath);
                var loadedDocAfterCreated = getResponse.Source;

                //create new new path on created parent id only
                var updateDocumentPath = new DocumentPath <ParentTestClass>(testClass.Id)
                                         .Index(index)
                                         .Type(typeof(ParentTestClass));

                //create an anonymous type to update property child and update parent document
                var childToUpdate  = new ChildClass();
                var partialUpdate  = new { Child = childToUpdate };
                var updateResponse = client.Update <ParentTestClass, dynamic>(updateDocumentPath, d => d.Doc(partialUpdate));

                //load updated document
                getResponse = client.Get <ParentTestClass>(updateDocumentPath);
                var loadedDocAfterUpdated = getResponse.Source;

                //ASSERT
                Assert.AreEqual(testClass.Id, loadedDocAfterCreated.Id);
                Assert.AreEqual(testClass.Id, loadedDocAfterUpdated.Id);
                Assert.AreEqual(2, loadedDocAfterCreated.Children.Count);
                Assert.AreEqual(2, loadedDocAfterUpdated.Children.Count);
                Assert.Null(loadedDocAfterCreated.Child);
                Assert.NotNull(loadedDocAfterUpdated.Child);
                Assert.AreEqual(childToUpdate.Id, loadedDocAfterUpdated.Child.Id);
            }
            finally
            {
                var deleteIndexResult = client.DeleteIndex(index);
            }
        }
        public void Search_match_term_by_Id_Test()
        {
            //ARRANGE
            var id = Guid.NewGuid();
            //set up search client
            var dependencyResolver = new DependencyResolverMock();

            var client = SearchClientFactory.GetClient();

            //create index name
            var indexName = String.Format("{0}_{1}", typeof(ParentTestClass).Name, id).ToLower();
            var index     = new IndexName {
                Name = indexName, Type = typeof(ParentTestClass)
            };

            try
            {
                var indexDescriptor = new CreateIndexDescriptor(index)
                                      .Mappings(map => map.Map <ParentTestClass>(m =>
                                                                                 m.AutoMap()));

                var createIndexRequest = client.CreateIndex(indexDescriptor);

                var testClass = new ParentTestClass();
                testClass.Children.Add(new ChildClass());
                var createDocumentResponse = client.Create(testClass, d => d.Index(index)
                                                           .Type(typeof(ParentTestClass)));

                Thread.Sleep(1000);

                //ACT
                //Search
                var searchMatchResponse = client
                                          .Search <ParentTestClass>(s =>
                                                                    s.Query(q =>
                                                                            q.Match(m => m.Field(field => field.Id)
                                                                                    .Query(testClass.Id.ToString())))
                                                                    .Index(index));

                var searchTermResponse = client
                                         .Search <ParentTestClass>(s =>
                                                                   s.Query(q =>
                                                                           q.Term(m => m.Field(field => field.Id)
                                                                                  .Value(testClass.Id.ToString())))
                                                                   .Index(index));

                //ASSERT match response
                Assert.IsTrue(searchMatchResponse.IsValid);
                Assert.AreEqual(1, searchMatchResponse.Documents.Count());
                Assert.AreEqual(testClass.Id, searchMatchResponse.Documents.First().Id);
                Assert.AreEqual(1, searchMatchResponse.Documents.First().Children.Count());
                Assert.AreEqual(testClass.Children.First().Id, searchMatchResponse.Documents.First().Children.First().Id);

                //ASSERT term response
                Assert.IsTrue(searchTermResponse.IsValid);
                Assert.AreEqual(1, searchTermResponse.Documents.Count());
                Assert.AreEqual(testClass.Id, searchTermResponse.Documents.First().Id);
                Assert.AreEqual(1, searchTermResponse.Documents.First().Children.Count());
                Assert.AreEqual(testClass.Children.First().Id, searchTermResponse.Documents.First().Children.First().Id);
            }
            finally
            {
                var deleteIndexResult = client.DeleteIndex(index);
            }
        }
Example #19
0
        public void Bool_must_query_test()
        {
            //ARRANGE
            var id = Guid.NewGuid();
            //set up search client
            var dependencyResolver = new DependencyResolverMock();

            var client = SearchClientFactory.GetClient();

            //create index name
            var indexName = String.Format("{0}_{1}", typeof(ParentTestClass).Name, id).ToLower();
            var index     = new IndexName {
                Name = indexName, Type = typeof(ParentTestClass)
            };

            try
            {
                var indexDescriptor = new CreateIndexDescriptor(index)
                                      .Mappings(map => map.Map <ParentTestClass>(m =>
                                                                                 m.Properties(p => p.Keyword(d => d.Name(n => n.Email)))));
                //m.AutoMap()));

                var createIndexRequest = client.CreateIndex(indexDescriptor);

                var testClass = new ParentTestClass {
                    IntField = 0, Email = "Text0"
                };
                testClass.Children.Add(new ChildClass());

                var testClass1 = new ParentTestClass {
                    IntField = 1, Email = "Text1"
                };
                testClass1.Children.Add(new ChildClass());

                var testClass2 = new ParentTestClass {
                    IntField = 2, Email = "Text2"
                };
                testClass2.Children.Add(new ChildClass());

                var testClass3 = new ParentTestClass {
                    IntField = 3, Email = "Text3"
                };
                testClass2.Children.Add(new ChildClass());

                var createDocumentResponse = client.Create(testClass, d => d.Index(index)
                                                           .Type(typeof(ParentTestClass)));

                var createDocumentResponse1 = client.Create(testClass1, d => d.Index(index)
                                                            .Type(typeof(ParentTestClass)));

                var createDocumentResponse2 = client.Create(testClass2, d => d.Index(index)
                                                            .Type(typeof(ParentTestClass)));

                var createDocumentResponse3 = client.Create(testClass3, d => d.Index(index)
                                                            .Type(typeof(ParentTestClass)));

                Thread.Sleep(1000);
                var i = client.GetIndex(new GetIndexRequest(index));
                //ACT
                //Search
                var searchMatchResponse = client
                                          .Search <ParentTestClass>(s =>
                                                                    s.Query(q =>
                                                                            q.Bool(b =>
                                                                                   b.Should(must =>
                                                                                            must.Term(term =>
                                                                                                      term.Field(field => field.Email)
                                                                                                      .Value("Text1"))
                                                                                            , must =>
                                                                                            must.Term(term =>
                                                                                                      term.Field(f => f.Email).
                                                                                                      Value("Text2"))
                                                                                            , must =>
                                                                                            must.Term(term =>
                                                                                                      term.Field(f => f.Email).
                                                                                                      Value("Text3")))
                                                                                   .Filter(filter =>
                                                                                           filter.Range(range =>
                                                                                                        range.Field(field => field.IntField)
                                                                                                        .GreaterThan(1)
                                                                                                        .LessThan(10)))
                                                                                   )
                                                                            )
                                                                    .Index(index));


                //ASSERT match response
                Assert.IsTrue(searchMatchResponse.IsValid);
                Assert.AreEqual(1, searchMatchResponse.Documents.Count());
                //Assert.AreEqual(testClass.Id, searchMatchResponse.Documents.First().Id);
                //Assert.AreEqual(1, searchMatchResponse.Documents.First().Children.Count());
                //Assert.AreEqual(testClass.Children.First().Id, searchMatchResponse.Documents.First().Children.First().Id);

                //ASSERT term response
                //Assert.IsTrue(searchTermResponse.IsValid);
                //Assert.AreEqual(1, searchTermResponse.Documents.Count());
                //Assert.AreEqual(testClass.Id, searchTermResponse.Documents.First().Id);
                //Assert.AreEqual(1, searchTermResponse.Documents.First().Children.Count());
                //Assert.AreEqual(testClass.Children.First().Id, searchTermResponse.Documents.First().Children.First().Id);
            }
            finally
            {
                var deleteIndexResult = client.DeleteIndex(index);
            }
        }
Example #20
0
        public void Search_by_email_not_mapped_match_term_comparison_search_Test()
        {
            //ARRANGE
            var id = Guid.NewGuid();

            var dependencyResolver = new DependencyResolverMock();
            var client             = SearchClientFactory.GetClient();

            //create index name
            var indexName = String.Format("{0}_{1}", typeof(ParentTestClass).Name, id).ToLower();
            var index     = new IndexName {
                Name = indexName, Type = typeof(ParentTestClass)
            };

            //ACT
            try
            {
                var indexDescriptor = new CreateIndexDescriptor(index)
                                      .Mappings(map => map.Map <ParentTestClass>(m =>
                                                                                 m.AutoMap()
                                                                                 .Properties(prop => prop.Nested <ChildClass>(o =>
                                                                                                                              o.Name(parent => parent.Child))
                                                                                             )));
                var createIndexRequest = client.CreateIndex(indexDescriptor);

                var email     = "*****@*****.**";
                var testClass = new ParentTestClass {
                    Email = email
                };
                testClass.Children.Add(new ChildClass());
                var createDocumentResponse = client.Create(testClass, d => d.Index(index)
                                                           .Type(typeof(ParentTestClass)));

                Thread.Sleep(1000);
                var indexReqiest  = new GetIndexRequest(index);
                var indexResponse = client.GetIndex(indexReqiest);
                var indices       = indexResponse.Indices.ToList();
                var first         = indices.First();
                var mappings      = first.Value.Mappings.First()
                                    .Value.Properties.Select(p => new { p.Key.Name, p.Value.Type, PropertyName = p.Value.Name });
                //ACT
                //Search
                var searchResponse = client
                                     .Search <ParentTestClass>(s =>
                                                               s.Query(q =>
                                                                       q.Match(m => m.Field(g => g.Email)
                                                                               .Query(email)))
                                                               .Index(index));

                var searchResponse_partial = client
                                             .Search <ParentTestClass>(s =>
                                                                       s.Query(q =>
                                                                               q.Match(m => m.Field(g => g.Email)
                                                                                       .Query("foreName.lastName")))
                                                                       .Index(index));

                var searchResponse_full_term = client
                                               .Search <ParentTestClass>(s =>
                                                                         s.Query(q =>
                                                                                 q.Term(m => m.Field(g => g.Email)
                                                                                        .Value(email)))
                                                                         .Index(index));

                //ASSERT match full search response
                Assert.IsTrue(searchResponse.IsValid);
                Assert.AreEqual(1, searchResponse.Documents.Count());
                Assert.AreEqual(testClass.Id, searchResponse.Documents.First().Id);
                Assert.AreEqual(testClass.Email, searchResponse.Documents.First().Email);

                //ASSERT partial match search response
                Assert.IsTrue(searchResponse_partial.IsValid);
                Assert.AreEqual(1, searchResponse_partial.Documents.Count());
                Assert.AreEqual(testClass.Id, searchResponse_partial.Documents.First().Id);
                Assert.AreEqual(testClass.Email, searchResponse_partial.Documents.First().Email);

                //ASSERT full term search response
                Assert.IsTrue(searchResponse_full_term.IsValid);
                Assert.AreEqual(0, searchResponse_full_term.Documents.Count());
            }
            finally
            {
                var deleteIndexResult = client.DeleteIndex(index);
            }
        }
Example #21
0
        public void UpdateDocument_load_update_commit_Test()
        {
            //ARRANGE

            var client        = SearchClientFactory.GetClient();
            var clientFactory = SearchClientFactory.GetClientFactory();

            var indexId = Guid.NewGuid();
            var index   = new IndexName {
                Name = String.Format("{0}_{1}", typeof(ParentTestClass).Name, indexId).ToLower(), Type = typeof(ParentTestClass)
            };

            var testClass = new ParentTestClass();

            testClass.Children.Add(new ChildClass());

            var documentPath = new DocumentPath <ParentTestClass>(testClass)
                               .Index(index)
                               .Type(typeof(ParentTestClass));

            //ACT
            try
            {
                //create a document
                var createRequest  = new CreateRequest <ParentTestClass>(documentPath);
                var createResponse = client.Create(createRequest);
                Thread.Sleep(1000);

                //load the created document and assign a property and commit
                var getResponse = client.Get <ParentTestClass>(documentPath);
                var loadedDoc   = getResponse.Source;
                var isChildNull = loadedDoc.Child == null;

                var childToAdd       = new ChildClass();
                var documentToUpdate = loadedDoc;
                documentToUpdate.Child = childToAdd;

                var updateDocumentPath = new DocumentPath <ParentTestClass>(documentToUpdate)
                                         .Index(index)
                                         .Type(typeof(ParentTestClass));

                var updateRequest = new UpdateRequest <ParentTestClass, ParentTestClass>(updateDocumentPath);
                updateRequest.Doc = loadedDoc;

                var updateResponse = client.Update <ParentTestClass>(updateDocumentPath, d => d.Doc(loadedDoc));

                var getResponseUpdated = client.Get <ParentTestClass>(updateDocumentPath);
                var updatedDocument    = getResponseUpdated.Source;

                //ASSERT
                Assert.IsTrue(createResponse.IsValid);
                Assert.IsTrue(getResponse.IsValid);
                Assert.AreEqual(testClass.Id, loadedDoc.Id);
                Assert.AreEqual(1, loadedDoc.Children.Count);
                Assert.IsTrue(isChildNull);
                Assert.AreEqual(testClass.Id, updatedDocument.Id);
                Assert.AreEqual(1, updatedDocument.Children.Count);
                Assert.NotNull(updatedDocument.Child);
                Assert.AreEqual(childToAdd.Id, updatedDocument.Child.Id);
            }
            finally
            {
                var deleteIndexResult = client.DeleteIndex(index);
            }
        }
Example #22
0
        public void PartialUpdateDocument_by_script_remove_from_collection()
        {
            //ARRANGE

            var client        = SearchClientFactory.GetClient();
            var clientFactory = SearchClientFactory.GetClientFactory();

            //create a new index
            var indexId = Guid.NewGuid();
            var index   = new IndexName {
                Name = String.Format("{0}_{1}", typeof(ParentTestClass).Name, indexId).ToLower(), Type = typeof(ParentTestClass)
            };

            //create a parent class and add 2 children
            var testClass = new ParentTestClass();
            var child1    = new ChildClass();
            var child2    = new ChildClass();

            testClass.TextCollection.Add("T1");
            testClass.TextCollection.Add("T2");
            testClass.Children.Add(child1);
            testClass.Children.Add(child2);

            //create document path
            var documentPath = new DocumentPath <ParentTestClass>(testClass)
                               .Index(index)
                               .Type(typeof(ParentTestClass));

            //ACT
            try
            {
                //create a new parent class document
                var createRequest  = new CreateRequest <ParentTestClass>(documentPath);
                var createResponse = client.Create(createRequest);

                //wait to be indexed
                Thread.Sleep(1000);

                //load the created document
                var getResponse           = client.Get <ParentTestClass>(documentPath);
                var loadedDocAfterCreated = getResponse.Source;

                //create new new path on created parent id only
                var updateDocumentPath = new DocumentPath <ParentTestClass>(testClass.Id)
                                         .Index(index)
                                         .Type(typeof(ParentTestClass));

                var lang = "painless";

                //var scriptToUpdate = "ctx._source.children.remove(params.p)";
                var scriptToUpdate = "ctx._source.children.remove(ctx._source.children.indexOf(params.p))";
                var updateResponse = client.Update <ParentTestClass, dynamic>(updateDocumentPath,
                                                                              d => d.Script(des =>
                                                                                            des.Inline(scriptToUpdate)
                                                                                            .Lang(lang)
                                                                                            .Params(p => p.Add("p", child1))));

                //load updated document
                getResponse = client.Get <ParentTestClass>(updateDocumentPath);
                var loadedDocAfterUpdated = getResponse.Source;

                //ASSERT
                Assert.AreEqual(testClass.Id, loadedDocAfterCreated.Id);
                Assert.AreEqual(testClass.Id, loadedDocAfterUpdated.Id);
                Assert.AreEqual(2, loadedDocAfterCreated.Children.Count);
                Assert.AreEqual(1, loadedDocAfterUpdated.Children.Count);
                Assert.AreEqual(child2.Id, loadedDocAfterUpdated.Children.ElementAt(0).Id);
            }
            finally
            {
                var deleteIndexResult = client.DeleteIndex(index);
            }
        }
        public void RecieveMessageFromKafkaTest()
        {
            //ARRANGE
            var recieved   = false;
            var documentId = Guid.NewGuid();
            var document   = new ParentTestClass();

            var dependencyResolver = new DependencyResolverMock();

            //var client = SearchClientFactory.GetClient();
            //var clientFactory = SearchClientFactory.GetClientFactory();
            //SearchClientFactory.RegisterDependencies(dependencyResolver);

            ////create an unique index
            var indexId               = Guid.NewGuid();
            var indexName             = String.Format("{0}_{1}", typeof(ParentTestClass).Name, indexId);
            var indexContext          = new IndexContext(typeof(ParentTestClass), indexName);
            var producerConfigManager = new ProducerConfigManager(dependencyResolver);

            dependencyResolver.RegisterFactory <IConfigurationProvider>((t) => new ClientIdProvider(), Lifetime.Transient);
            dependencyResolver.RegisterFactory <IConfigurationProvider>((t) => new EndPoindProvider(), Lifetime.Transient);
            dependencyResolver.RegisterFactory <IConfigurationProvider>((t) => new ProducerTopicConfigProvider(), Lifetime.Transient);
            dependencyResolver.RegisterFactory <IConfigurationProvider>((t) => new GroupIdProvider(), Lifetime.Transient);
            ////set up document CRUD controller and create a mock document
            //var responseHandler = new ResponseHandler();
            //var indexManager = new IndexManager(dependencyResolver, clientFactory, responseHandler);
            //var documentDispatcher = new DocumentDispatcher(clientFactory, indexManager, responseHandler);
            //var documentclient = new DocumentController(documentDispatcher, indexManager, responseHandler);
            try
            {
                //var context = new UpsertDocumentContext<ParentTestClass>(documentId) { Document = document, IndexContext = indexContext };
                //var dispatcher = new KafkaDispatcher(producerConfigManager);
                //ACT
                var topic     = typeof(ParentTestClass).Name;
                var cancelled = false;
                //var time = new Timer(new TimerCallback((_) => cancelled = true), null, 5000, 5000);
                var valueSerializer = new BinarySerializer <ParentTestClass>();
                var keySerializer   = new BinarySerializer <Guid>();
                var config          = producerConfigManager.GetConfiguration(x => (x.ConfigurationScope & ConfigurationScope.Consumer) == ConfigurationScope.Consumer);
                using (var consumer = new Consumer <Guid, ParentTestClass>(config, keySerializer, valueSerializer))
                {
                    var metaData = consumer.GetMetadata(true);

                    consumer.OnMessage += (_, msg)
                                          =>
                    {
                        consumer.CommitAsync(msg).Wait();
                        recieved  = true;
                        cancelled = true;
                    };

                    consumer.OnPartitionEOF += (_, end)
                                               => Console.WriteLine($"Reached end of topic {end.Topic} partition {end.Partition}.");

                    consumer.OnError += (_, error) =>
                    {
                        Console.WriteLine($"Error: {error}");
                        cancelled = true;
                    };

                    consumer.Subscribe(topic);
                    var tp = new TopicPartition(topic, 0);
                    consumer.CommitAsync(new[] { new TopicPartitionOffset(tp, new Offset(15)) });
                    var possition = consumer.Position(new[] { tp });
                    var committed = consumer.Committed(new[] { new TopicPartition(topic, 0) }, TimeSpan.FromMilliseconds(5000));
                    while (!cancelled)
                    {
                        consumer.Poll(TimeSpan.FromMilliseconds(100));
                    }
                    Assert.True(recieved);
                }
            }
            finally
            {
            }
        }