示例#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 GetSuggestions_TestErrorResponse()
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.SearchResponse <Suggestion> >((req, res) =>
            {
                // Simulate an error.
                res.Stream     = null;
                res.StatusCode = 500;
            });

            // 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();

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

            // We don't care about the inputs, only in the error response.
            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(
                () => query.GetSuggestions("Cancer.gov", AudienceType.HealthProfessional, "es", "chicken", MatchType.Contains, 200)
                );

            Assert.Equal(500, ex.HttpStatusCode);
        }
        public async void GetSuggestions_TestEmptyESResults()
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

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

            // 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();

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

            // We don't really care about the inputs, only the result.
            Suggestion[] result = await query.GetSuggestions("Cancer.gov", AudienceType.HealthProfessional, "es", "chicken", MatchType.Contains, 200);

            Assert.Empty(result);
        }
        public async void GetBestBetForDisplay_TestAPIConnectionFailure()
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.GetResponse <BestBetsCategoryDisplay> >((req, res) =>
            {
                res.StatusCode = 500;
            });

            //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 <CGBBIndexOptions> bbClientOptions = GetMockOptions();

            ESBestBetsDisplayService bbClient = new ESBestBetsDisplayService(client, bbClientOptions, new NullLogger <ESBestBetsDisplayService>());

            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(() => bbClient.GetBestBetForDisplay("live", "431121"));

            Assert.Equal(500, ex.HttpStatusCode);
        }
        /// <summary>
        /// Helper function to get an instance of a ESBBIndexerService Only needing to setup
        /// the connection request handler callbacks. (via connSetupCallback)
        /// </summary>
        /// <param name="aliasName"></param>
        /// <param name="connSetupCallback"></param>
        /// <returns></returns>
        protected ESBBIndexerService GetIndexerService(string aliasName, Action <ElasticsearchInterceptingConnection> connSetupCallback)
        {
            //Create connection and handle request.
            ElasticsearchInterceptingConnection interceptConnection = new ElasticsearchInterceptingConnection();

            connSetupCallback(interceptConnection);

            Mock <IOptions <ESBBIndexerServiceOptions> > options = new Mock <IOptions <ESBBIndexerServiceOptions> >();

            options
            .SetupGet(o => o.Value)
            .Returns(new ESBBIndexerServiceOptions()
            {
                AliasName = aliasName
            });

            //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, interceptConnection);

            IElasticClient client = new ElasticClient(connectionSettings);

            ESBBIndexerService service = new ESBBIndexerService(
                client,
                options.Object
                );

            return(service);
        }
示例#7
0
        public async void GetCount_InvalidResponse()
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.CountResponse>((req, res) =>
            {
                string partial   = @"{
                    ""count"": 8458,
                    ""_shards"": {";
                byte[] byteArray = Encoding.UTF8.GetBytes(partial);
                res.Stream       = new MemoryStream(byteArray);
                res.StatusCode   = 200;
            });

            // 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 care about the inputs, only in the error response.
            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(
                () => query.GetCount("Cancer.gov", AudienceType.HealthProfessional, "es")
                );

            Assert.Equal(500, ex.HttpStatusCode);
        }
示例#8
0
        public void GetTokenCount_Responses(
            string searchTerm,
            string language,
            object[] responseTokens,
            int expectedCount
            )
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <AnalyzeResponse>(
                (req, res) =>
            {
                JObject resObject   = new JObject();
                resObject["tokens"] = JArray.FromObject(responseTokens);
                byte[] byteArray    = Encoding.UTF8.GetBytes(resObject.ToString());

                res.Stream     = new MemoryStream(byteArray);
                res.StatusCode = 200;
            }
                );

            //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);

            ESTokenAnalyzerService service = new ESTokenAnalyzerService(client, new NullLogger <ESTokenAnalyzerService>());
            int actualCount = service.GetTokenCount(searchTerm);

            Assert.Equal(expectedCount, actualCount);
        }
        public async void Search_TestAPIConnectionFailure()
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.SearchResponse <GlossaryTerm> >((req, res) =>
            {
                res.StatusCode = 500;
            });

            // 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>());

            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(() => termsClient.Search("Cancer.gov", AudienceType.Patient, "en", "chicken", MatchType.Begins, 10, 0, false));

            Assert.Equal(500, ex.HttpStatusCode);
        }
        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 RegisterRequestHandlerForType_DuplicateTypes()
        {
            void callback(RequestData req, ElasticsearchInterceptingConnection.ResponseData res)
            {
            }

            void callback2(RequestData req, ElasticsearchInterceptingConnection.ResponseData res)
            {
            }

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            // First registration should always succeed.
            conn.RegisterRequestHandlerForType <Nest.SearchResponse <MockType> >(callback);

            // Second registration for same type should always fail.
            Exception ex = Assert.Throws <ArgumentException>(
                () => conn.RegisterRequestHandlerForType <Nest.SearchResponse <MockType> >(callback)
                );

            Assert.Equal(
                "There is already a handler defined that would be called for type. Trying to add for: Nest.SearchResponse`1[NCI.OCPL.Api.Common.ElasticsearchInterceptingConnectionTest+MockType], Already Existing: Nest.SearchResponse`1[NCI.OCPL.Api.Common.ElasticsearchInterceptingConnectionTest+MockType]",
                ex.Message
                );

            // Second registration for the same type should still fail with a different handler.
            ex = Assert.Throws <ArgumentException>(
                () => conn.RegisterRequestHandlerForType <Nest.SearchResponse <MockType> >(callback2)
                );
        }
        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());
        }
        public void GetKLA_TestQueryNull()
        {
            ElasticsearchInterceptingConnection conn   = new ElasticsearchInterceptingConnection();
            ESResourceAggregationService        aggSvc = this.GetService <ESResourceAggregationService>(conn);

            Assert.ThrowsAny <Exception>(() => {
                KeyLabelAggResult[] aggResults = aggSvc.GetKeyLabelAggregation(
                    "toolSubtypes",
                    null
                    );
            });
        }
示例#14
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 void GetKLA_Build_SubType_Missing_Tooltype()
        {
            ElasticsearchInterceptingConnection conn   = new ElasticsearchInterceptingConnection();
            ESResourceAggregationService        aggSvc = this.GetService <ESResourceAggregationService>(conn);

            Assert.ThrowsAny <Exception>(() => {
                KeyLabelAggResult[] aggResults = aggSvc.GetKeyLabelAggregation(
                    "toolSubtypes",
                    new ResourceQuery
                {
                    Filters = new Dictionary <string, string[]> {
                    }
                }
                    );
            });
        }
        public void GetKLA_TestBadFacet()
        {
            ElasticsearchInterceptingConnection conn   = new ElasticsearchInterceptingConnection();
            ESResourceAggregationService        aggSvc = this.GetService <ESResourceAggregationService>(conn);

            Assert.ThrowsAny <Exception>(() => {
                KeyLabelAggResult[] aggResults = aggSvc.GetKeyLabelAggregation(
                    "chicken",
                    new ResourceQuery {
                    Filters = new Dictionary <string, string[]> {
                        { "toolTypes", new string[] { "datasets_databases" } }
                    }
                }
                    );
            });
        }
        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());
        }
示例#18
0
        public async void GetByIdForGlossaryTerm(BaseTermQueryTestData data)
        {
            Uri esURI = null;

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.GetResponse <GlossaryTerm> >((req, res) =>
            {
                //Get the file name for this round
                res.Stream = TestingTools.GetTestFileAsStream("ESTermQueryData/" + data.ESTermID + ".json");

                res.StatusCode = 200;

                esURI = req.Uri;
            });

            //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> gTermClientOptions = GetMockOptions();

            ESTermQueryService termClient = new ESTermQueryService(client, gTermClientOptions, new NullLogger <ESTermQueryService>());

            // We don't actually care that this returns anything - only that the intercepting connection
            // sets up the request URI correctly.
            GlossaryTerm actDisplay = await termClient.GetById(
                data.DictionaryName,
                data.Audience,
                data.Language,
                data.TermID,
                new string[] {}
                );


            Assert.Equal(
                esURI.Segments,
                new string[] { "/", "glossaryv1/", "terms/", data.ESTermID },
                new ArrayComparer()
                );
        }
        public void RegisterRequestHandlerForType_DifferentTypes()
        {
            void callback(RequestData req, ElasticsearchInterceptingConnection.ResponseData res)
            {
            }

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            // This registration should always succeed.
            conn.RegisterRequestHandlerForType <Nest.SearchResponse <MockType> >(callback);

            // This registration should also succeed.
            Exception ex = Record.Exception(
                () => conn.RegisterRequestHandlerForType <Nest.SearchResponse <MockType2> >(callback)
                );

            Assert.Null(ex);
        }
示例#20
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());
        }
        ///<summary>
        ///A private method to enrich data from file for Search
        ///</summary>
        private IElasticClient Search_GetElasticClientWithData(string searchTestType)
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.SearchResponse <GlossaryTerm> >((req, res) =>
            {
                //Get the file name for this round
                res.Stream = TestingTools.GetTestFileAsStream("ESTermsQueryData/Search/search_response_" + searchTestType + ".json");

                res.StatusCode = 200;
            });

            //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);

            return(client);
        }
        private IElasticClient GetElasticClientWithData(BaseDisplayTestData data)
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.GetResponse <BestBetsCategoryDisplay> >((req, res) =>
            {
                //Get the file name for this round
                res.Stream = TestingTools.GetTestFileAsStream("ESDisplayData/" + data.TestFilePath);

                res.StatusCode = 200;
            });

            //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);

            return(client);
        }
示例#23
0
        public void RegisterRequestHandlerForType_MultipleDefaults()
        {
            void callback(RequestData req, object res)
            {
            }

            void callback2(RequestData req, object res)
            {
            }

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            // First registration should always succeed.
            conn.RegisterDefaultHandler(callback);

            Exception ex = Assert.Throws <ArgumentException>(
                () => conn.RegisterDefaultHandler(callback2)
                );

            Assert.Equal("Cannot add more than one default handler", ex.Message);
        }
        public async void GetBestBetForDisplay_TestURISetup(BaseDisplayTestData data)
        {
            Uri esURI = null;

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.GetResponse <BestBetsCategoryDisplay> >((req, res) =>
            {
                //Get the file name for this round
                res.Stream = TestingTools.GetTestFileAsStream("ESDisplayData/" + data.TestFilePath);

                res.StatusCode = 200;

                esURI = req.Uri;
            });

            //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 <CGBBIndexOptions> bbClientOptions = GetMockOptions();

            ESBestBetsDisplayService bbClient = new ESBestBetsDisplayService(client, bbClientOptions, new NullLogger <ESBestBetsDisplayService>());

            // We don't actually care that this returns anything - only that the intercepting connection
            // sets up the request URI correctly.
            IBestBetDisplay actDisplay = await bbClient.GetBestBetForDisplay("preview", "431121");

            Assert.Equal(esURI.Segments, new string[] { "/", "bestbets_preview_v1/", "categorydisplay/", "431121" }, new ArrayComparer());

            actDisplay = await bbClient.GetBestBetForDisplay("live", "431121");

            Assert.Equal(esURI.Segments, new string[] { "/", "bestbets_live_v1/", "categorydisplay/", "431121" }, new ArrayComparer());
        }
示例#25
0
        public async void GetByIdForGlossaryTerm_TestInvalidResponse()
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.GetResponse <GlossaryTerm> >((req, res) =>
            {
            });

            //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> gTermClientOptions = GetMockOptions();

            ESTermQueryService termClient = new ESTermQueryService(client, gTermClientOptions, new NullLogger <ESTermQueryService>());
            APIErrorException  ex         = await Assert.ThrowsAsync <APIErrorException>(() => termClient.GetById("cancer.gov", AudienceType.Patient, "en", 43966L, new string[] {}));

            Assert.Equal(500, ex.HttpStatusCode);
        }
示例#26
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 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());
        }
        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());
        }
示例#29
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());
        }