예제 #1
0
        public void QueryResources_SingleInclude()
        {
            //Create new ESRegAggConnection...

            string actualPath   = "";
            string expectedPath = "r4r_v1/resource/_search"; //Use index in config

            JObject actualRequest   = null;
            JObject expectedRequest = JObject.Parse(@"
                {
                  ""from"": 20,
                  ""size"": 20,
                  ""_source"": {
                    ""includes"": [
                      ""id""
                    ]
                  },
                  ""sort"": [
                    {
                      ""title._sort"": {
                        ""order"": ""asc""
                      }
                    }
                  ]
                }"
                                                    );

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            //SearchResponse<Resource> <-- type
            conn.RegisterRequestHandlerForType <SearchResponse <Resource> >((req, res) =>
            {
                actualPath    = req.Path;
                actualRequest = conn.GetRequestPost(req);
            });

            var svc = this.GetService <ESResourceQueryService>(conn);

            try
            {
                var results = svc.QueryResources(
                    query: new ResourceQuery
                {
                    Keyword = null,
                    Filters = new Dictionary <string, string[]> {
                    }
                },
                    from: 20,
                    includeFields: new string[]
                {
                    "id"
                }
                    );
            }
            catch (Exception) { } //We don't care how it processes the results...


            Assert.Equal(expectedPath, actualPath);
            Assert.Equal(expectedRequest, actualRequest, new JTokenEqualityComparer());
        }
예제 #2
0
        public void GetRequestPost_WithData(string data)
        {
            JToken expected = JToken.Parse(data);

            Mock <IConnectionConfigurationValues> mockConfig = new Mock <IConnectionConfigurationValues>();

            mockConfig.Setup(cfg => cfg.RequestTimeout).Returns(new TimeSpan(0, 0, 5));
            mockConfig.Setup(cfg => cfg.PingTimeout).Returns(new TimeSpan(0, 0, 5));
            IConnectionConfigurationValues config = mockConfig.Object;

            Mock <PostData> mockData = new Mock <PostData>();

            mockData.Setup(
                d => d.Write(It.IsAny <Stream>(), It.IsAny <IConnectionConfigurationValues>())
                )
            .Callback((
                          Stream str, IConnectionConfigurationValues iccv) =>
            {
                byte[] buf = Encoding.UTF8.GetBytes(data);
                str.Write(buf, 0, buf.Length);
            }
                      );


            // None of these values really matter except the post data which is the third parameter.
            RequestData requestData = new RequestData(HttpMethod.GET, "foo", mockData.Object, config, null, null);

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            JToken actual = conn.GetRequestPost(requestData);

            Assert.Equal(expected, actual, new JTokenEqualityComparer());
        }
        public async void Search_TestRequestSetup(Terms_Search_Request_Base data)
        {
            JObject actualRequest = null;

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.SearchResponse <GlossaryTerm> >((req, res) =>
            {
                // We don't really care about the ES response for this test.
                res.Stream     = MockEmptyResponse;
                res.StatusCode = 200;
                actualRequest  = conn.GetRequestPost(req);
            });

            // While this has a URI, it does not matter, an InMemoryConnection never requests
            // from the server.
            var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

            var            connectionSettings = new ConnectionSettings(pool, conn);
            IElasticClient client             = new ElasticClient(connectionSettings);

            // Setup the mocked Options
            IOptions <GlossaryAPIOptions> gTermsClientOptions = GetMockOptions();

            ESTermsQueryService termsClient = new ESTermsQueryService(client, gTermsClientOptions, new NullLogger <ESTermsQueryService>());

            try
            {
                var results = await termsClient.Search(data.Dictionary, data.Audience, data.LangCode, data.SearchTerm, data.MatchType, data.Size, data.From, data.IncludeAdditionalInfo);
            }
            catch (Exception) { }

            Assert.Equal(data.ExpectedRequest, actualRequest, new JTokenEqualityComparer());
        }
        public void GetKeyLabelAggregation_Build_EmptyQuery()
        {
            //Create new ESRegAggConnection...

            string actualPath   = "";
            string expectedPath = "r4r_v1/resource/_search"; //Use index in config

            JObject actualRequest   = null;
            JObject expectedRequest = JObject.Parse(@"
                {
                    ""size"": 0,
                    ""aggs"": {
                        ""researchTypes_agg"": {
                            ""nested"": {
                                ""path"": ""researchTypes""
                            },
                            ""aggs"": {
                                ""researchTypes_key"": {
                                    ""terms"": {
                                        ""field"": ""researchTypes.key"",
                                        ""size"": 999
                                    },
                                    ""aggs"": {
                                        ""researchTypes_label"": {
                                            ""terms"": {
                                                ""field"": ""researchTypes.label""
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } 
            ");

            /*
             */

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            //SearchResponse<Resource> <-- type
            conn.RegisterRequestHandlerForType <SearchResponse <Resource> >((req, res) =>
            {
                actualPath    = req.Path;
                actualRequest = conn.GetRequestPost(req);
            });

            ESResourceAggregationService aggSvc = this.GetService <ESResourceAggregationService>(conn);

            try
            {
                KeyLabelAggResult[] aggResults = aggSvc.GetKeyLabelAggregation("researchTypes", new ResourceQuery());
            } catch (Exception) {} //We don't care how it processes the results...


            Assert.Equal(expectedPath, actualPath);
            Assert.Equal(expectedRequest, actualRequest, new JTokenEqualityComparer());
        }
예제 #5
0
        public void GetRequestPost_NullPostData()
        {
            Mock <IConnectionConfigurationValues> mockConfig = new Mock <IConnectionConfigurationValues>();

            mockConfig.Setup(cfg => cfg.RequestTimeout).Returns(new TimeSpan(0, 0, 5));
            mockConfig.Setup(cfg => cfg.PingTimeout).Returns(new TimeSpan(0, 0, 5));
            IConnectionConfigurationValues config = mockConfig.Object;

            // None of these values really matter except the post data which is the third parameter.
            RequestData requestData = new RequestData(HttpMethod.GET, "foo", null, config, null, null);

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            Assert.Null(conn.GetRequestPost(requestData));
        }
        public async void GetSuggestions_TestRequestSetup(BaseAutosuggestServiceScenario data)
        {
            Uri        esURI         = null;
            string     esContentType = String.Empty;
            HttpMethod esMethod      = HttpMethod.DELETE; // Basically, something other than the expected value.

            JObject requestBody = null;

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.SearchResponse <Suggestion> >((req, res) =>
            {
                // We don't really care about the response for this test.
                res.Stream     = MockEmptyResponse;
                res.StatusCode = 200;

                esURI         = req.Uri;
                esContentType = req.ContentType;
                esMethod      = req.Method;
                requestBody   = conn.GetRequestPost(req);
            });

            // The URI does not matter, an InMemoryConnection never requests from the server.
            var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

            var            connectionSettings = new ConnectionSettings(pool, conn);
            IElasticClient client             = new ElasticClient(connectionSettings);

            // Setup the mocked Options
            IOptions <DrugDictionaryAPIOptions> clientOptions = GetMockOptions();

            clientOptions.Value.Autosuggest.MaxSuggestionLength = data.MaxSuggestionLength;

            ESAutosuggestQueryService query = new ESAutosuggestQueryService(client, clientOptions, new NullLogger <ESAutosuggestQueryService>());

            // We don't really care that this returns anything (for this test), only that the intercepting connection
            // sets up the request correctly.
            Suggestion[] result = await query.GetSuggestions(data.SearchText, data.MatchType, data.Size,
                                                             data.IncludeResourceTypes, data.IncludeNameTypes, data.ExcludeNameTypes);

            Assert.Equal("/drugv1/terms/_search", esURI.AbsolutePath);
            Assert.Equal("application/json", esContentType);
            Assert.Equal(HttpMethod.POST, esMethod);
            Assert.Equal(data.ExpectedData, requestBody, new JTokenEqualityComparer());
        }
예제 #7
0
        public async void GetCount_Request(BaseTermsQueryCountTestData data)
        {
            Uri        esURI         = null;
            string     esContentType = String.Empty;
            HttpMethod esMethod      = HttpMethod.DELETE; // Basically, something other than the expected value.

            JObject requestBody = null;

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.CountResponse>((req, res) =>
            {
                // We don't really care about the response for this test.
                res.Stream     = GetMockCountResponse();
                res.StatusCode = 200;

                esURI         = req.Uri;
                esContentType = req.ContentType;
                esMethod      = req.Method;
                requestBody   = conn.GetRequestPost(req);
            });

            // The URI does not matter, an InMemoryConnection never requests from the server.
            var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

            var            connectionSettings = new ConnectionSettings(pool, conn);
            IElasticClient client             = new ElasticClient(connectionSettings);

            // Setup the mocked Options
            IOptions <GlossaryAPIOptions> clientOptions = GetMockOptions();

            ESTermsQueryService query = new ESTermsQueryService(client, clientOptions, new NullLogger <ESTermsQueryService>());

            // We don't really care that this returns anything (for this test), only that the intercepting connection
            // sets up the request correctly.
            long result = await query.GetCount(data.DictionaryName, data.Audience, data.Language);

            Assert.Equal("/glossaryv1/terms/_count", esURI.AbsolutePath);
            Assert.Equal("application/json", esContentType);
            Assert.Equal(HttpMethod.POST, esMethod);
            Assert.Equal(data.ExpectedData, requestBody, new JTokenEqualityComparer());
        }
예제 #8
0
        public async void GetCount_Response(BaseTermsCountResponseData data)
        {
            Uri        esURI         = null;
            string     esContentType = String.Empty;
            HttpMethod esMethod      = HttpMethod.DELETE; // Basically, something other than the expected value.

            JObject requestBody = null;

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.CountResponse>((req, res) =>
            {
                res.Stream     = TestingTools.GetTestFileAsStream("ESTermsQueryData/GetCount/" + data.TestFilename);
                res.StatusCode = 200;

                esURI         = req.Uri;
                esContentType = req.ContentType;
                esMethod      = req.Method;
                requestBody   = conn.GetRequestPost(req);
            });

            // The URI does not matter, an InMemoryConnection never requests from the server.
            var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

            var            connectionSettings = new ConnectionSettings(pool, conn);
            IElasticClient client             = new ElasticClient(connectionSettings);

            // Setup the mocked Options
            IOptions <GlossaryAPIOptions> clientOptions = GetMockOptions();

            ESTermsQueryService query = new ESTermsQueryService(client, clientOptions, new NullLogger <ESTermsQueryService>());

            // We don't really care about the inputs. What matters is the return, which is controlled by the mock ES connection.
            long result = await query.GetCount("Cancer.gov", AudienceType.Patient, "es");

            Assert.Equal(data.ExpectedCount, result);
        }
        public void GetKLA_Build_SubType()
        {
            //Create new ESRegAggConnection...

            string actualPath   = "";
            string expectedPath = "r4r_v1/resource/_search"; //Use index in config

            JObject actualRequest   = null;
            JObject expectedRequest = JObject.Parse(@"
                {
                    ""size"": 0,
                    ""query"": {
                        ""bool"": {
                            ""filter"": [
                                { ""term"": { ""toolTypes.key"": { ""value"": ""datasets_databases"" }}}
                            ]
                        }
                    },
                    ""aggs"": {
                        ""toolSubtypes_agg"": {
                            ""nested"": {
                                ""path"": ""toolSubtypes""
                            },
                            ""aggs"": {
                                ""toolSubtypes_filter"": {
                                    ""filter"": {
                                        ""term"": { ""toolSubtypes.parentKey"": { ""value"": ""datasets_databases"" } }                                        
                                    },
                                    ""aggs"": {
                                        ""toolSubtypes_key"": {
                                            ""terms"": {
                                                ""field"": ""toolSubtypes.key"",
                                                ""size"": 999
                                            },
                                            ""aggs"": {
                                                ""toolSubtypes_label"": {
                                                    ""terms"": {
                                                        ""field"": ""toolSubtypes.label""
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } 
            ");

            /*
             */

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            //SearchResponse<Resource> <-- type
            conn.RegisterRequestHandlerForType <SearchResponse <Resource> >((req, res) =>
            {
                actualPath    = req.Path;
                actualRequest = conn.GetRequestPost(req);
            });

            ESResourceAggregationService aggSvc = this.GetService <ESResourceAggregationService>(conn);

            try
            {
                KeyLabelAggResult[] aggResults = aggSvc.GetKeyLabelAggregation(
                    "toolSubtypes",
                    new ResourceQuery {
                    Filters = new Dictionary <string, string[]> {
                        { "toolTypes", new string[] { "datasets_databases" } }
                    }
                }
                    );
            }
            catch (Exception ex) {
                int i = 1;
            } //We don't care how it processes the results...


            Assert.Equal(expectedPath, actualPath);
            Assert.Equal(expectedRequest, actualRequest, new JTokenEqualityComparer());
        }
        public async void GetByName_TestRequestSetup()
        {
            JObject actualRequest   = null;
            JObject expectedRequest = JObject.Parse(@"
                {
                    ""sort"": [
                        {
                            ""term_name"": {}
                        }
                    ],
                    ""query"": {
                        ""bool"": {
                            ""must"": [
                                {
                                    ""term"": {
                                        ""language"": {
                                            ""value"": ""en""
                                        }
                                    }
                                },
                                {
                                    ""term"": {
                                        ""audience"": {
                                            ""value"": ""Patient""
                                        }
                                    }
                                },
                                {
                                    ""term"": {
                                        ""dictionary"": {
                                            ""value"": ""Cancer.gov""
                                        }
                                    }
                                },
                                {
                                    ""term"": {
                                        ""pretty_url_name"": {
                                            ""value"": ""s-1""
                                        }
                                    }
                                }
                            ]
                        }
                    }
                }"
                                                    );

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.SearchResponse <GlossaryTerm> >((req, res) =>
            {
                res.Stream = TestingTools.GetTestFileAsStream("ESTermsQueryData/GetByName/s-1.json");

                res.StatusCode = 200;

                actualRequest = conn.GetRequestPost(req);
            });

            // While this has a URI, it does not matter, an InMemoryConnection never requests
            // from the server.
            var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

            var            connectionSettings = new ConnectionSettings(pool, conn);
            IElasticClient client             = new ElasticClient(connectionSettings);

            // Setup the mocked Options
            IOptions <GlossaryAPIOptions> gTermsClientOptions = GetMockOptions();

            ESTermsQueryService termsClient = new ESTermsQueryService(client, gTermsClientOptions, new NullLogger <ESTermsQueryService>());

            try
            {
                var results = await termsClient.GetByName("Cancer.gov", AudienceType.Patient, "en", "s-1");
            }
            catch (Exception) { }

            Assert.Equal(expectedRequest, actualRequest, new JTokenEqualityComparer());
        }
예제 #11
0
        public void QueryResources_SingleFilter_Keyword()
        {
            //Create new ESRegAggConnection...

            string actualPath   = "";
            string expectedPath = "r4r_v1/resource/_search"; //Use index in config

            JObject actualRequest   = null;
            JObject expectedRequest = JObject.Parse(@"
                {
                  ""from"": 0,
                  ""size"": 20,
                  ""_source"": {
                    ""includes"": [
                      ""id"",
                      ""title"",
                      ""website"",
                      ""body"",
                      ""description"",
                      ""toolTypes"",
                      ""researchAreas"",
                      ""researchTypes"",
                      ""resourceAccess"",
                      ""docs"",
                      ""pocs""
                    ]
                  },
                  ""sort"": [
                    { ""_score"": { } },
                    { ""id"": { } }
                  ],
                  ""query"": {
                    ""bool"": {
                      ""filter"": [
                        {""term"": { ""researchTypes.key"": { ""value"": ""basic"" }}}
                      ],
                      ""must"": [                        
                        {
                          ""bool"": {
                            ""should"": [
                              { ""common"": { ""title._fulltext"": { ""query"": ""CGCI"", ""cutoff_frequency"": 1.0, ""low_freq_operator"": ""and"", ""boost"": 1.0 } } },
                              { ""match"": { ""title._fulltext"": { ""query"": ""CGCI"", ""boost"": 1.0 } } },
                              { ""match"": { ""title._fulltext"": { ""query"": ""CGCI"", ""boost"": 1.0, ""type"": ""phrase"" } } },
                              { ""common"": { ""body._fulltext"": { ""query"": ""CGCI"", ""cutoff_frequency"": 1.0, ""low_freq_operator"": ""and"", ""boost"": 1.0 } } },
                              { ""match"": { ""body._fulltext"": { ""query"": ""CGCI"", ""boost"": 1.0 } } },
                              { ""match"": { ""body._fulltext"": { ""query"": ""CGCI"", ""boost"": 1.0, ""type"": ""phrase"" } } },
                              { ""match"": { ""pocs.lastname._fulltext"": { ""query"": ""CGCI"", ""boost"": 1.0 } } },
                              { ""match"": { ""pocs.firstname._fulltext"": { ""query"": ""CGCI"", ""boost"": 1.0 } } },
                              { ""match"": { ""pocs.middlename._fulltext"": { ""query"": ""CGCI"", ""boost"": 1.0 } } }
                            ]
                          }
                        }
                      ]
                    } 
                  }
                } 
            ");

            /*
             */

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            //SearchResponse<Resource> <-- type
            conn.RegisterRequestHandlerForType <SearchResponse <Resource> >((req, res) =>
            {
                actualPath    = req.Path;
                actualRequest = conn.GetRequestPost(req);
            });

            var svc = this.GetService <ESResourceQueryService>(conn);

            try
            {
                var results = svc.QueryResources(
                    query: new ResourceQuery
                {
                    Keyword = "CGCI",
                    Filters = new Dictionary <string, string[]> {
                        { "researchTypes", new string[] { "basic" } }
                    }
                },
                    includeFields: new string[]
                {
                    "id",
                    "title",
                    "website",
                    "body",
                    "description",
                    "toolTypes",
                    "researchAreas",
                    "researchTypes",
                    "resourceAccess",
                    "docs",
                    "pocs"
                }
                    );
            }
            catch (Exception) { } //We don't care how it processes the results...


            Assert.Equal(expectedPath, actualPath);
            Assert.Equal(expectedRequest, actualRequest, new JTokenEqualityComparer());
        }