Beispiel #1
0
        /// <summary>
        /// Verify that controller throws the correct exception when no collection is specified.
        /// </summary>
        /// <param name="collectionValue">A string specifying the collection to search.</param>
        public void Get_EmptyCollection_ReturnsError(String collectionValue)
        {
            // The file needs to exist so it can be deserialized, but we don't make
            // use of the actual content.
            string testFile = "Search.CGov.En.BreastCancer.json";

            IOptions <AutosuggestIndexOptions> config = GetMockedAutosuggestIndexOptions();
            AutosuggestController ctrl = new AutosuggestController(
                ElasticTools.GetInMemoryElasticClient(testFile),
                config,
                NullLogger <AutosuggestController> .Instance
                );

            Exception ex = Assert.Throws <APIErrorException>(
                // Parameters don't matter, and for this test we don't care about saving the results
                () =>
                ctrl.Get(
                    collectionValue,
                    "en",
                    "some term"
                    )
                );

            // Search without a collection should report bad request (400)
            Assert.Equal(400, ((APIErrorException)ex).HttpStatusCode);
        }
        public void GetQueryForFullTextField_MultipleMatchTypes()
        {
            var       fullTextFieldQueries = this._junkSvc.TEST_GetQueryForFullTextField("testfield", "testkeyword", 1, new string[] { "common", "match_phrase" });
            BoolQuery actual = new BoolQuery
            {
                Should = fullTextFieldQueries
            };

            var expectedStr = @" 
                {
                    ""bool"": {
                        ""should"": [
                            { ""common"": { ""testfield"": { ""query"": ""testkeyword"", ""cutoff_frequency"": 1.0, ""low_freq_operator"": ""and"", ""boost"": 1.0 } } },
                            { ""match"": { ""testfield"": { ""query"": ""testkeyword"", ""boost"": 1.0, ""type"": ""phrase"" } } }
                        ],
                        ""minimum_should_match"": null,
                        ""disable_coord"": null,
                        ""_name"": null,
                        ""boost"": null
                    }
                }
            ";

            ElasticTools.AssertQueryJson(expectedStr, actual);
        }
        public void GetQueryForMatchType_Common()
        {
            var query       = this._junkSvc.TEST_GetQueryForMatchType("testfield", "testkeyword", 1, "common");
            var expectedStr = @" 
                { ""common"": { ""testfield"": { ""query"": ""testkeyword"", ""cutoff_frequency"": 1.0, ""low_freq_operator"": ""and"", ""boost"": 1.0 } } }
            ";

            ElasticTools.AssertQueryJson(expectedStr, query);
        }
        public void GetQueryForMatchType_MatchPhrase()
        {
            var query       = this._junkSvc.TEST_GetQueryForMatchType("testfield", "testkeyword", 1, "match_phrase");
            var expectedStr = @" 
                { ""match"": { ""testfield"": { ""query"": ""testkeyword"", ""boost"": 1.0, ""type"": ""phrase"" } } }
            ";

            ElasticTools.AssertQueryJson(expectedStr, query);
        }
        public void GetQueryForField()
        {
            var query       = this._junkSvc.TEST_GetQueryForField("testfield", "testval");
            var expectedStr = @"
                { ""term"": { ""testfield"": { ""value"": ""testval"" } } }
            ";

            ElasticTools.AssertQueryJson(expectedStr, query);
        }
        public void GetKeywordQuery_Scenarios(string keyword, string[] expectedFullTextQuery)
        {
            var actual = this._junkSvc.TEST_GetKeywordQuery(keyword);

            string pre      = @"{ ""bool"": { ""should"": [";
            string post     = @"], ""minimum_should_match"": null, ""disable_coord"": null,""_name"": null,""boost"": null } }";
            string expected = pre + string.Join(',', expectedFullTextQuery) + post;

            ElasticTools.AssertQueryJson(expected, actual);
        }
Beispiel #7
0
        [InlineData("ESHealthData/unexpected.json")]   // i.e. "Unexpected color"
        public void GetStatus_Unhealthy(string datafile)
        {
            IOptions <AutosuggestIndexOptions> config = GetMockedAutosuggestIndexOptions();
            AutosuggestController ctrl = new AutosuggestController(
                ElasticTools.GetInMemoryElasticClient(datafile),
                config,
                NullLogger <AutosuggestController> .Instance
                );

            APIErrorException ex = Assert.Throws <APIErrorException>(() => ctrl.GetStatus());

            Assert.Equal(500, ex.HttpStatusCode);
        }
        public void GetFullQuery_Scenarios(string keyword, string[] expectedFullTextQuery, Dictionary <string, string[]> filters, string[] expectedFilters)
        {
            var actual = this._junkSvc.TEST_GetFullQuery(keyword, filters);

            string preKeyword  = @"{ ""bool"": { ""must"": [ ";
            string postKeyword = @"], ";
            string preFilter   = @"""filter"": [";
            string postFilter  = @"], ""minimum_should_match"": null, ""disable_coord"": null,""_name"": null,""boost"": null } }";

            string expected = preKeyword + string.Join(',', expectedFullTextQuery) + postKeyword + preFilter + string.Join(',', expectedFilters) + postFilter;

            ElasticTools.AssertQueryJson(expected, actual);
        }
Beispiel #9
0
        public void GetStatus_Healthy(string datafile)
        {
            IOptions <AutosuggestIndexOptions> config = GetMockedAutosuggestIndexOptions();
            AutosuggestController ctrl = new AutosuggestController(
                ElasticTools.GetInMemoryElasticClient(datafile),
                config,
                NullLogger <AutosuggestController> .Instance
                );

            string status = ctrl.GetStatus();

            Assert.Equal(AutosuggestController.HEALTHY_STATUS, status, ignoreCase: true);
        }
        public void GetAllFiltersForQuery_Scenarios(Dictionary <string, string[]> filters, string[] expectedFilters)
        {
            var       filterQueries = this._junkSvc.TEST_GetAllFiltersForQuery(filters);
            BoolQuery actual        = new BoolQuery
            {
                Filter = filterQueries
            };

            string pre      = @"{ ""bool"": { ""filter"": [";
            string post     = @"], ""minimum_should_match"": null, ""disable_coord"": null,""_name"": null,""boost"": null}}";
            string expected = pre + string.Join(',', expectedFilters) + post;

            ElasticTools.AssertQueryJson(expected, actual);
        }
        public void GetQueryForFullTextField_Scenarios(string keyword, R4RAPIOptions.FullTextFieldConfig field, string[] expectedFullTextFieldQueries)
        {
            var       fullTextFieldQueries = this._junkSvc.TEST_GetQueryForFullTextField(field.FieldName, keyword, field.Boost, field.MatchTypes);
            BoolQuery actual = new BoolQuery
            {
                Should = fullTextFieldQueries
            };

            string pre      = @"{ ""bool"": { ""should"": [";
            string post     = @"], ""minimum_should_match"": null, ""disable_coord"": null,""_name"": null,""boost"": null } }";
            string expected = pre + string.Join(',', expectedFullTextFieldQueries) + post;

            ElasticTools.AssertQueryJson(expected, actual);
        }
        /// <summary>
        /// Verify that the request sent to ES for a single term is being set up correctly.
        /// </summary>
        public void Check_For_Correct_Request_Data()
        {
            string term = "Breast Cancer";

            ISearchTemplateRequest actualReq = null;

            //Setup the client with the request handler callback to be executed later.
            IElasticClient client =
                ElasticTools.GetMockedSearchTemplateClient <Suggestion>(
                    req => actualReq = req,
                    resMock => {
                //Make sure we say that the response is valid.
                resMock.Setup(res => res.IsValid).Returns(true);
            }         // We don't care what the response looks like.
                    );

            IOptions <AutosuggestIndexOptions> config = GetMockedAutosuggestIndexOptions();
            AutosuggestController controller          = new AutosuggestController(
                client,
                config,
                NullLogger <AutosuggestController> .Instance
                );

            //NOTE: this is when actualReq will get set.
            controller.Get(
                "cgov",
                "en",
                term
                );

            SearchTemplateRequest <Suggestion> expReq = GetSearchRequest <Suggestion>(
                "cgov",                   // Search index to look in.
                "autosg_suggest_cgov_en", // Template name, preceded by the name of the directory it's stored in.
                term,                     // Search term
                10,                       // Max number of records to retrieve.
                "\"url\", \"title\", \"metatag.description\", \"metatag.dcterms.type\"",
                "all"
                );

            Assert.Equal(
                expReq,
                actualReq,
                new ElasticTools.SearchTemplateRequestComparer()
                );
        }
Beispiel #13
0
        [InlineData(500)] // Server error
        /// <summary>
        /// Verify that controller throws the correct exception when the
        /// ES client reports an error.
        /// </summary>
        /// <param name="offset">Offset into the list of results of the item to check.</param>
        /// <param name="expectedTerm">The expected term text</param>
        public void Handle_Failed_Query(int errorCode)
        {
            IOptions <AutosuggestIndexOptions> config = GetMockedAutosuggestIndexOptions();
            AutosuggestController ctrl = new AutosuggestController(
                ElasticTools.GetErrorElasticClient(errorCode),
                config,
                NullLogger <AutosuggestController> .Instance
                );

            Assert.Throws <APIErrorException>(
                // Parameters don't matter, and for this test we don't care about saving the results
                () =>
                ctrl.Get(
                    "cgov",
                    "en",
                    "breast cancer"
                    )
                );
        }
        public void GetFullTextQuery_TwoFields()
        {
            var fullTextQuery = this._junkSvc.TEST_GetFullTextQuery(
                "testkeyword",
                new R4RAPIOptions.FullTextFieldConfig[]
            {
                new R4RAPIOptions.FullTextFieldConfig
                {
                    FieldName  = "testfield1",
                    Boost      = 1,
                    MatchTypes = new string[] { "common", "match" }
                },
                new R4RAPIOptions.FullTextFieldConfig
                {
                    FieldName  = "testfield2",
                    Boost      = 1,
                    MatchTypes = new string[] { "common" }
                }
            });

            BoolQuery actual = new BoolQuery
            {
                Should = fullTextQuery
            };

            var expectedStr = @" 
                {
                    ""bool"": {
                        ""should"": [
                            { ""common"": { ""testfield1"": { ""query"": ""testkeyword"", ""cutoff_frequency"": 1.0, ""low_freq_operator"": ""and"", ""boost"": 1.0 } } },
                            { ""match"": { ""testfield1"": { ""query"": ""testkeyword"", ""boost"": 1.0 } } },
                            { ""common"": { ""testfield2"": { ""query"": ""testkeyword"", ""cutoff_frequency"": 1.0, ""low_freq_operator"": ""and"", ""boost"": 1.0 } } }
                        ],
                        ""minimum_should_match"": null,
                        ""disable_coord"": null,
                        ""_name"": null,
                        ""boost"": null
                    }
                }
            ";

            ElasticTools.AssertQueryJson(expectedStr, actual);
        }
Beispiel #15
0
        /// <summary>
        /// Test that the search results at arbitrary offsets
        /// in the collection are present
        /// </summary>
        public void Check_RequiredField_Present()
        {
            string testFile = "Search.CGov.En.BreastCancer.json";

            IOptions <SearchIndexOptions> config = GetMockSearchIndexConfig();
            SearchController ctrl = new SearchController(
                ElasticTools.GetInMemoryElasticClient(testFile),
                config,
                NullLogger <SearchController> .Instance
                );

            //Parameters don't matter in this case...
            SiteWideSearchResults results = ctrl.Get(
                "cgov",
                "en",
                "breast cancer"
                );

            Assert.All(results.Results, item => Assert.NotNull(item.URL));
        }
        /// <summary>
        /// Test that the list of results exists.
        /// </summary>
        public void Check_Results_Exist()
        {
            string testFile = "AutoSuggest.CGov.En.BreastCancer.json";

            IOptions <AutosuggestIndexOptions> config = GetMockedAutosuggestIndexOptions();
            AutosuggestController ctrl = new AutosuggestController(
                ElasticTools.GetInMemoryElasticClient(testFile),
                config,
                NullLogger <AutosuggestController> .Instance
                );

            //Parameters don't matter in this case...
            Suggestions results = ctrl.Get(
                "cgov",
                "en",
                "breast cancer"
                );

            Assert.NotEmpty(results.Results);
        }
        /// <summary>
        /// Test that the suggested search strings from arbitrary offsets
        /// in the collection have the correct values
        /// </summary>
        /// <param name="offset">Offset into the list of results of the item to check.</param>
        /// <param name="expectedTerm">The expected term text</param>
        public void Check_Arbitrary_Result(int offset, string expectedTerm)
        {
            string testFile = "AutoSuggest.CGov.En.BreastCancer.json";

            IOptions <AutosuggestIndexOptions> config = GetMockedAutosuggestIndexOptions();
            AutosuggestController ctrl = new AutosuggestController(
                ElasticTools.GetInMemoryElasticClient(testFile),
                config,
                NullLogger <AutosuggestController> .Instance
                );

            //Parameters don't matter in this case...
            Suggestions results = ctrl.Get(
                "cgov",
                "en",
                "breast cancer"
                );

            Assert.Equal(expectedTerm, results.Results[offset].Term);
        }
Beispiel #18
0
        /// <summary>
        /// Test that search mapping returns correct number of results for an empty result set.
        /// (And also that it doesn't explode!)
        /// </summary>
        public void No_Results_Has_Correct_Total()
        {
            string testFile = "Search.CGov.En.NoResults.json";

            IOptions <SearchIndexOptions> config = GetMockSearchIndexConfig();
            SearchController ctrl = new SearchController(
                ElasticTools.GetInMemoryElasticClient(testFile),
                config,
                NullLogger <SearchController> .Instance
                );

            //Parameters don't matter in this case...
            SiteWideSearchResults results = ctrl.Get(
                "cgov",
                "en",
                "breast cancer"
                );

            Assert.Empty(results.Results);
        }
        public void GetQueryForFilterField_GetMulti()
        {
            var query = this._junkSvc.TEST_GetQueryForFilterField("testfield", new string[] { "testval", "testval2" });

            //NOTE: ES automatically adds disable_coord,_name, and boost.
            var expectedStr = @"
                {
                    ""bool"": {
                        ""should"": [
                            { ""term"": { ""testfield"": { ""value"": ""testval"" } } },
                            { ""term"": { ""testfield"": { ""value"": ""testval2"" } } }
                        ], 
                        ""minimum_should_match"": 1,
                        ""disable_coord"": null,
                        ""_name"": null,
                        ""boost"": null
                    }
                }
            ";

            ElasticTools.AssertQueryJson(expectedStr, query);
        }
Beispiel #20
0
        [InlineData(500)] // Server error
        /// <summary>
        /// Verify that controller throws the correct exception when the
        /// ES client reports an error.
        /// </summary>
        /// <param name="offset">Offset into the list of results of the item to check.</param>
        /// <param name="expectedTerm">The expected term text</param>
        public void Handle_Failed_Query(int errorCode)
        {
            IOptions <SearchIndexOptions> config = GetMockSearchIndexConfig();
            SearchController ctrl = new SearchController(
                ElasticTools.GetErrorElasticClient(errorCode),
                config,
                NullLogger <SearchController> .Instance
                );

            Exception ex = Assert.Throws <APIErrorException>(
                // Parameters don't matter, and for this test we don't care about saving the results
                () =>
                ctrl.Get(
                    "cgov",
                    "en",
                    "breast cancer"
                    )
                );

            // Failed search request should always report 500.
            Assert.Equal(500, ((APIErrorException)ex).HttpStatusCode);
        }
Beispiel #21
0
        /// <summary>
        /// Test that the search result mapping returns null when an optional field is not present.
        /// Inputs for each call are obtained by iterating over the FieldData property.
        /// </summary>
        /// <param name="offset">Offset into testFile's set of search results.</param>
        /// <param name="nullTest">A test function of tupe Func&lt;SiteWideSearchResult, Boolean&gt; which checks
        /// wheter a specific field in the selected result is null.</param>
        /// <param name="fieldName">Name of the field being tested, used for display purposes.</param>
        public void Optional_Field_Is_Null(int offset, Object nullTest, string fieldName)
        {
            string testFile = "Search.CGov.En.AbsentFields.json";

            IOptions <SearchIndexOptions> config = GetMockSearchIndexConfig();
            SearchController ctrl = new SearchController(
                ElasticTools.GetInMemoryElasticClient(testFile),
                config,
                NullLogger <SearchController> .Instance
                );

            //Parameters don't matter in this case...
            SiteWideSearchResults results = ctrl.Get(
                "cgov",
                "en",
                "breast cancer"
                );

            SiteWideSearchResult item = results.Results[offset];

            Assert.True(((Func <SiteWideSearchResult, Boolean>)nullTest)(item), fieldName);
        }
Beispiel #22
0
        /// <summary>
        /// Verify that controller throws the correct exception when no search text is specified.
        /// </summary>
        /// <param name="termValue">A string the text to search for.</param>
        public void Get_EmptyTerm_ReturnsError(String termValue)
        {
            string testFile = "Search.CGov.En.BreastCancer.json";

            IOptions <AutosuggestIndexOptions> config = GetMockedAutosuggestIndexOptions();
            AutosuggestController ctrl = new AutosuggestController(
                ElasticTools.GetInMemoryElasticClient(testFile),
                config,
                NullLogger <AutosuggestController> .Instance
                );

            Exception ex = Assert.Throws <APIErrorException>(
                // Parameters don't matter, and for this test we don't care about saving the results
                () =>
                ctrl.Get(
                    "some collection",
                    "en",
                    termValue
                    )
                );

            // Search without something to search for should report bad request (400)
            Assert.Equal(400, ((APIErrorException)ex).HttpStatusCode);
        }