public void Get_EnglishTerm(string searchTerm, BaseCategoryTestData data)
        {
            Mock <IBestBetsDisplayService> displayService = new Mock <IBestBetsDisplayService>();

            displayService
            .Setup(
                dispSvc => dispSvc.GetBestBetForDisplay(
                    It.Is <string>(catID => catID == data.ExpectedData.ID)
                    )
                )
            .Returns(TestingTools.DeserializeXML <CancerGovBestBet>(data.TestFilePath));

            Mock <IBestBetsMatchService> matchService = new Mock <IBestBetsMatchService>();

            matchService
            .Setup(
                matchSvc => matchSvc.GetMatches(
                    It.Is <string>(lang => lang == "en"),
                    It.Is <string>(term => term == searchTerm)
                    )
                )
            .Returns(new string[] { data.ExpectedData.ID });

            // Create instance of controller
            BestBetsController controller = new BestBetsController(
                matchService.Object,
                displayService.Object,
                NullLogger <BestBetsController> .Instance
                );

            IBestBetDisplay[] actualItems = controller.Get("en", searchTerm);

            Assert.Equal(actualItems, new IBestBetDisplay[] { data.ExpectedData }, new IBestBetDisplayComparer());
        }
        public async void GetAll_TestRequestSetup(GetAll_Request_Base data)
        {
            JObject actualRequest = null;

            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.SearchResponse <GlossaryTerm> >((req, res) =>
            {
                res.Stream = TestingTools.GetTestFileAsStream("ESTermsQueryData/GetAll/getall_response_results.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.GetAll(data.Dictionary, data.Audience, data.LangCode, data.Size, data.From, data.IncludeAdditionalInfo);
            }
            catch (Exception) { }

            Assert.Equal(data.ExpectedRequest, actualRequest, new JTokenEqualityComparer());
        }
        void SynonymsMappedCorrectly(SynonymTestData data)
        {
            // Load test BestBet object
            string           filePath = data.TestFilePath;
            CancerGovBestBet testData = TestingTools.DeserializeXML <CancerGovBestBet>(filePath);

            // Put the expected matches into a dictionary for fast lookup.
            Dictionary <string, BestBetsMatch> dictExpectedMatches = new Dictionary <string, BestBetsMatch>();

            foreach (BestBetsMatch item in data.ExpectedMatches)
            {
                dictExpectedMatches.Add(item.Synonym, item);
            }

            // Create a BestBetMapper from a test BestBet.
            BestBetSynonymMapper mapper = new BestBetSynonymMapper(
                GetTokenizerServiceForData(data),
                testData
                );

            Assert.All(mapper, match => {
                string synonym = match.Synonym;
                Assert.True(dictExpectedMatches.ContainsKey(synonym));
                Assert.Equal(dictExpectedMatches[synonym], match, new BestBetsMatchComparer());
            });
        }
Esempio n. 4
0
        public void CreateIndex_QueryValidation()
        {
            string aliasName = "TestAlias";

            ESBBIndexerService service = this.GetIndexerService(
                aliasName,
                conn =>
            {
                conn.RegisterRequestHandlerForType <Nest.CreateIndexResponse>((req, res) =>
                {
                    res.StatusCode = 200;
                    res.Stream     = TestingTools.GetTestFileAsStream("ES_Acknowledged_True_Response.json");
                });
            }
                );

            string currTimeStamp = DateTime.Now.ToString("yyyyMMddHHmmss");

            string actualIndexName = service.CreateTimeStampedIndex();
            string actualTimeStamp = actualIndexName.Replace(aliasName, "");

            long currAsLong   = long.Parse(currTimeStamp);
            long actualAsLong = long.Parse(actualTimeStamp);

            //Give it up to a 5 sec difference.
            Assert.InRange(actualAsLong, currAsLong - 5, currAsLong);
        }
        /// <summary>
        /// Loads a SynonymTestData object based on a JSON file.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>SynonymTestData.</returns>
        public static SynonymTestData LoadTestData(string path)
        {
            string content = File.ReadAllText(
                TestingTools.GetPathToTestFile("SynonymTestData/" + path)
                );

            return(JsonConvert.DeserializeObject <SynonymTestData>(content));
        }
        public void Can_Deserialize_XML(BaseCategoryTestData data)
        {
            //Setup the expected object.
            CancerGovBestBet actCat = TestingTools.DeserializeXML <CancerGovBestBet>(data.TestFilePath);

            //Compare Object
            Assert.Equal(data.ExpectedData, actCat, new IBestBetCategoryComparer());
        }
        public async void GetByNameTerms()
        {
            Mock <ITermsQueryService> termsQueryService = new Mock <ITermsQueryService>();
            TermsController           controller        = new TermsController(NullLogger <TermsController> .Instance, termsQueryService.Object);

            GlossaryTerm glossaryTerm = new GlossaryTerm()
            {
                TermId        = 44771,
                Language      = "en",
                Dictionary    = "Cancer.gov",
                Audience      = AudienceType.Patient,
                TermName      = "S-phase fraction",
                FirstLetter   = "s",
                PrettyUrlName = "s-phase-fraction",
                Definition    = new Definition()
                {
                    Text = "A measure of the percentage of cells in a tumor that are in the phase of the cell cycle during which DNA is synthesized. The S-phase fraction may be used with the proliferative index to give a more complete understanding of how fast a tumor is growing.",
                    Html = "A measure of the percentage of cells in a tumor that are in the phase of the cell cycle during which DNA is synthesized. The S-phase fraction may be used with the proliferative index to give a more complete understanding of how fast a tumor is growing."
                },
                Pronunciation = new Pronunciation()
                {
                    Key   = "(... fayz FRAK-shun)",
                    Audio = "https://nci-media-dev.cancer.gov/audio/pdq/705947.mp3"
                },
                Media            = new IMedia[] {},
                RelatedResources = new IRelatedResource[] { }
            };

            termsQueryService.Setup(
                termQSvc => termQSvc.GetByName(
                    It.IsAny <string>(),
                    It.IsAny <AudienceType>(),
                    It.IsAny <string>(),
                    It.IsAny <string>()
                    )
                )
            .Returns(Task.FromResult(glossaryTerm));

            GlossaryTerm term = await controller.GetByName("Cancer.gov", AudienceType.Patient, "en", "s-phase-fraction");

            JObject actual   = JObject.Parse(JsonConvert.SerializeObject(term));
            JObject expected = JObject.Parse(File.ReadAllText(TestingTools.GetPathToTestFile("TermsControllerData/TestData_GetByName.json")));

            // Verify that the service layer is called:
            //  a) with the expected values.
            //  b) exactly once.
            termsQueryService.Verify(
                svc => svc.GetByName("cancer.gov", AudienceType.Patient, "en", "s-phase-fraction"),
                Times.Once
                );

            Assert.Equal(glossaryTerm, term, new GlossaryTermComparer());
            Assert.Equal(expected, actual, new JTokenEqualityComparer());
        }
        public async void GetByName_WithFallback_TermsPatient_NotTitleCase()
        {
            Mock <ITermsQueryService> termQueryService = new Mock <ITermsQueryService>();
            GlossaryTerm glossaryTerm = new GlossaryTerm()
            {
                TermId        = 44771,
                Language      = "en",
                Dictionary    = "Cancer.gov",
                Audience      = AudienceType.Patient,
                TermName      = "S-phase fraction",
                FirstLetter   = "s",
                PrettyUrlName = "s-phase-fraction",
                Definition    = new Definition()
                {
                    Text = "A measure of the percentage of cells in a tumor that are in the phase of the cell cycle during which DNA is synthesized. The S-phase fraction may be used with the proliferative index to give a more complete understanding of how fast a tumor is growing.",
                    Html = "A measure of the percentage of cells in a tumor that are in the phase of the cell cycle during which DNA is synthesized. The S-phase fraction may be used with the proliferative index to give a more complete understanding of how fast a tumor is growing."
                },
                Pronunciation = new Pronunciation()
                {
                    Key   = "(... fayz FRAK-shun)",
                    Audio = "https://nci-media-dev.cancer.gov/audio/pdq/705947.mp3"
                },
                Media            = new IMedia[] { },
                RelatedResources = new IRelatedResource[] { }
            };

            // "cancer.gov" (not the requested "Cancer.gov") and Patient would be the only call to the terms query service, returning the term.
            termQueryService.Setup(
                termQSvc => termQSvc.GetByName(
                    It.Is <String>(dictionary => dictionary == "cancer.gov"),
                    It.Is <AudienceType>(audience => audience == AudienceType.Patient),
                    It.Is <string>(language => language == "en"),
                    It.Is <string>(prettyUrlName => prettyUrlName == "s-phase-fraction")
                    )
                )
            .Returns(Task.FromResult(glossaryTerm));

            TermsController controller = new TermsController(NullLogger <TermsController> .Instance, termQueryService.Object);
            GlossaryTerm    gsTerm     = await controller.GetByName("Cancer.gov", AudienceType.Patient, "en", "s-phase-fraction", true);

            // Verify that the expected and actual Term are the same.
            JObject actual   = JObject.Parse(JsonConvert.SerializeObject(gsTerm));
            JObject expected = JObject.Parse(File.ReadAllText(TestingTools.GetPathToTestFile("TermsControllerData/TestData_GetWithFallback_TermsPatient.json")));

            Assert.Equal(expected, actual, new JTokenEqualityComparer());

            // Verify that the service layer is called correctly with the lowercased-dictionary fallback combination:
            termQueryService.Verify(
                svc => svc.GetByName("cancer.gov", AudienceType.Patient, "en", "s-phase-fraction"),
                Times.Once
                );
        }
        public void OptimizedSucceeded()
        {
            string aliasName = "bestbets";
            string indexName = aliasName + "20161207125500";

            string actualPath           = string.Empty;
            object actualRequestOptions = null;

            ESBBIndexerService service = this.GetIndexerService(
                aliasName,
                conn =>
            {
                //This is the handler for the Optimize call
                conn.RegisterRequestHandlerForType <Nest.ForceMergeResponse>((req, res) =>
                {
                    //Store off Request
                    actualPath           = req.Path;
                    actualRequestOptions = conn.GetRequestPost(req);

                    //Setup Response
                    res.StatusCode = 200;
                    res.Stream     = TestingTools.GetTestFileAsStream("ForceMerge_Good_Response.json");
                });
            }
                );

            bool succeeded = service.OptimizeIndex(indexName);

            //Make sure the Request is the expected request
            //Params for this are actual query params.

            // Hostname doesn't matter, just needed so we have an absolute Uri (relative Uri allows very few operations).

            Uri actualReqUri = new Uri(
                "http://localhost" + actualPath,
                UriKind.Absolute);


            Uri expectedUri = new Uri(
                "http://localhost" + indexName + "/_forcemerge?wait_for_merge=true&max_num_segments=1",
                UriKind.Absolute);

            //Check the path/parameters are as expected
            Assert.Equal(expectedUri, actualReqUri, new UriComparer());

            //Check that there was not request body
            Assert.Null(actualRequestOptions);

            //Technically, there is no condition where false would be returned as
            //an exception would be thrown.
            Assert.True(succeeded);
        }
Esempio n. 10
0
        /// <summary>
        /// Creates a new instance of the ESResAggSvcConnection class
        /// </summary>
        /// <param name="testFile">The JSON file for the test response</param>
        public ESResQSvcGetConn(string testFile, int status = 200)
        {
            this.TestFile = testFile;

            //This section is for registering the intercepters for the request.

            //Add Handlers
            this.RegisterRequestHandlerForType <Nest.GetResponse <Resource> >((req, res) =>
            {
                //Get the file name for this round
                res.Stream = TestingTools.GetTestFileAsStream(GetTestFileName());

                res.StatusCode = status;
            });
        }
Esempio n. 11
0
        /// <summary>
        /// Creates a new instance of the ESMatchTokenizerConnection class
        /// </summary>
        /// <param name="testFilePrefix">The prefix of the test files</param>
        public ESHealthTokenizerConnection(string testFilePrefix)
        {
            this.TestFilePrefix = testFilePrefix;

            //Add Handlers
            this.RegisterRequestHandlerForType <Nest.ClusterHealthResponse>((req, res) =>
            {
                //I don't care about the request for this... for now.

                //Get the file name for this round
                res.Stream = TestingTools.GetTestFileAsStream(GetTestFileName());

                res.StatusCode = 200;
            });
        }
Esempio n. 12
0
        /// <summary>
        /// Creates a new instance of the ESMatchConnection class
        /// </summary>
        /// <param name="testFilePrefix">The prefix of the test files</param>
        public ESHealthConnection(string testFilePrefix)
        {
            this.TestFilePrefix = testFilePrefix;

            //Add Handlers
            this.RegisterRequestHandlerForType <Nest.ClusterHealthResponse>((req, res) =>
            {
                // Health check is a GET request (e.g. https://localhost:9299/_cluster/health/bestbets?pretty)
                // so we don't need to do anything special, just load the data file.
                //Get the file name for this round
                res.Stream = TestingTools.GetTestFileAsStream(GetTestFileName());

                res.StatusCode = 200;
            });
        }
Esempio n. 13
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()
                );
        }
        void CorrectNumberOfSynonymsFound(SynonymTestData data)
        {
            // Load test BestBet object
            string           filePath = data.TestFilePath;
            CancerGovBestBet testData = TestingTools.DeserializeXML <CancerGovBestBet>(filePath);

            int expectedCount = data.ExpectedMatches.Count();

            // Create a BestBetMapper from a test BestBet.
            BestBetSynonymMapper mapper = new BestBetSynonymMapper(
                GetTokenizerServiceForData(data),
                testData
                );

            int actualCount = mapper.Count();

            // Verify that returned list of BestBetMatch objects matches what's expected.
            Assert.Equal(expectedCount, actualCount);
        }
Esempio n. 15
0
        /// <summary>
        /// Creates a new instance of the ESMatchConnection class
        /// </summary>
        /// <param name="testFilePrefix">The prefix of the test files</param>
        public ESMatchConnection(string testFilePrefix)
        {
            this.TestFilePrefix = testFilePrefix;

            //Add Handlers
            this.RegisterRequestHandlerForType <Nest.SearchResponse <BestBetsMatch> >((req, res) =>
            {
                //Get the request parameters
                dynamic postObj = this.GetRequestPost(req);

                //Determine which round we are performing
                int numTokens = postObj["params"].matchedtokencount;

                //Get the file name for this round
                res.Stream = TestingTools.GetTestFileAsStream(GetTestFileName(numTokens));

                res.StatusCode = 200;
            });
        }
Esempio n. 16
0
        /// <summary>
        /// Creates a new instance of the ESMatchConnection class
        /// </summary>
        /// <param name="testFilePrefix">The prefix of the test files</param>
        public ESMatchConnection(string testFilePrefix)
        {
            this.TestFilePrefix = testFilePrefix;

            //Add Handlers
            this.RegisterRequestHandlerForType <Nest.SearchResponse <BestBetsMatch> >((req, res) =>
            {
                //Get the request parameters
                dynamic postObj = this.GetRequestPost(req);

                //Determine which round we are performing
                //int numTokens = postObj["params"].matchedtokencount;

                //If this is one item the bool node will be the nested match
                //if it is both exact and matches, then the bool node will
                //be a should. This code is tightly matched to the built query
                //in the implementation
                int numTokens = -1;

                var boolNode = postObj["query"]["bool"];
                if (boolNode["should"] != null)
                {
                    numTokens = boolNode["should"][0]
                                ["bool"]["must"][3]
                                ["match"]["synonym"]
                                ["minimum_should_match"].ToObject <int>();
                }
                else
                {
                    numTokens = boolNode["must"][3]
                                ["match"]["synonym"]
                                ["minimum_should_match"].ToObject <int>();
                }



                //Get the file name for this round
                res.Stream = TestingTools.GetTestFileAsStream(GetTestFileName(numTokens));

                res.StatusCode = 200;
            });
        }
        public void BestBetsEntry()
        {
            CancerResearchIdeas testData = new CancerResearchIdeas();


            // TODO: Create a TestData object.
            string TestFilePath = testData.TestFilePath;

            //Setup a mock handler, which is what HttpClient uses under the hood to fetch
            //data.
            var mockHttp = new MockHttpMessageHandler();

            string filePath = TestFilePath;

            ByteArrayContent content = new ByteArrayContent(TestingTools.GetTestFileAsBytes(filePath));

            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml");

            mockHttp
            .When(string.Format("https://www.cancer.gov/PublishedContent/BestBets/{0}", filePath))
            .Respond(System.Net.HttpStatusCode.OK, content);

            // Setup the mocked Options
            Mock <IOptions <PublishedContentListingServiceOptions> > clientOptions = new Mock <IOptions <PublishedContentListingServiceOptions> >();

            clientOptions
            .SetupGet(opt => opt.Value)
            .Returns(new PublishedContentListingServiceOptions()
            {
                Host = "https://www.cancer.gov"
            }
                     );


            IPublishedContentListingService publishedContentClient = new CDEPubContentListingService(new HttpClient(mockHttp),
                                                                                                     clientOptions.Object,
                                                                                                     NullLogger <CDEPubContentListingService> .Instance);

            CancerGovBestBet actualReturn = publishedContentClient.GetPublishedFile <CancerGovBestBet>(String.Format("/PublishedContent/BestBets/{0}", filePath));

            Assert.Equal(testData.ExpectedData, actualReturn, new IBestBetDisplayComparer());
        }
        public void HttpStatusError(System.Net.HttpStatusCode status)
        {
            string TestFilePath = "CDEPubContentListingService.ListAvailablePaths.json";

            //Setup a mock handler, which is what HttpClient uses under the hood to fetch
            //data.
            var mockHttp = new MockHttpMessageHandler();

            string filePath = TestFilePath;

            ByteArrayContent content = new ByteArrayContent(TestingTools.GetTestFileAsBytes(filePath));

            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            mockHttp
            .When("https://www.cancer.gov/PublishedContent/List")
            .Respond(status, content);

            // Setup the mocked Options
            Mock <IOptions <PublishedContentListingServiceOptions> > clientOptions = new Mock <IOptions <PublishedContentListingServiceOptions> >();

            clientOptions
            .SetupGet(opt => opt.Value)
            .Returns(new PublishedContentListingServiceOptions()
            {
                Host     = "https://www.cancer.gov",
                ListRoot = "/PublishedContent/List"
            }
                     );

            IPublishedContentListingService listClient = new CDEPubContentListingService(new HttpClient(mockHttp),
                                                                                         clientOptions.Object,
                                                                                         NullLogger <CDEPubContentListingService> .Instance);

            Exception ex = Assert.Throws <NCI.OCPL.Services.CDE.PublishedContentListing.APIErrorException>(
                // We don't care about the return value, only that an exception occured.
                () => listClient.ListAvailablePaths()
                );

            // All errors should return a status 500.
            Assert.Equal(500, ((NCI.OCPL.Services.CDE.PublishedContentListing.APIErrorException)ex).HttpStatusCode);
        }
        public void SingleAlias()
        {
            string aliasName            = "bestbets";
            string actualPath           = string.Empty;
            object actualRequestOptions = null;

            ESBBIndexerService service = this.GetIndexerService(
                aliasName,
                conn =>
            {
                //This is the handler for AliasExists calls
                conn.RegisterRequestHandlerForType <Nest.ExistsResponse>((req, res) =>
                {
                    //Just need to return 200 to say alias does exist
                    res.StatusCode = 200;
                    res.Stream     = null;
                    res.Exception  = null;
                });

                conn.RegisterRequestHandlerForType <Nest.GetAliasesResponse>((req, res) =>
                {
                    //Store off Request
                    actualPath           = req.Path;
                    actualRequestOptions = conn.GetRequestPost(req);

                    //Setup Response
                    res.StatusCode = 200;
                    res.Stream     = TestingTools.GetTestFileAsStream("GetIndicesForAlias_SingleItemResponse.json");
                });
            }
                );

            string[] actualIndices = service.GetIndicesForAlias();

            //Make sure the Request is the expected request
            Assert.Equal(aliasName + "/_alias", actualPath);
            Assert.Null(actualRequestOptions);

            //Make sure the response is the same.
            Assert.Equal(new string[] { "bestbets20161202152737" }, actualIndices);
        }
        public void DataLoading(string rootName, string dataPath)
        {
            // TODO: Create a TestData object.
            string TestFilePath = "CDEPubContentListingService.BestBets.json";

            //Setup a mock handler, which is what HttpClient uses under the hood to fetch
            //data.
            var mockHttp = new MockHttpMessageHandler();

            string filePath = TestFilePath;

            ByteArrayContent content = new ByteArrayContent(TestingTools.GetTestFileAsBytes(filePath));

            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            mockHttp
            .When(string.Format("https://www.cancer.gov/PublishedContent/List?root={0}&path={1}&fmt=json", rootName, dataPath))
            .Respond(System.Net.HttpStatusCode.OK, content);

            // Setup the mocked Options
            Mock <IOptions <PublishedContentListingServiceOptions> > clientOptions = new Mock <IOptions <PublishedContentListingServiceOptions> >();

            clientOptions
            .SetupGet(opt => opt.Value)
            .Returns(new PublishedContentListingServiceOptions()
            {
                Host     = "https://www.cancer.gov",
                ListRoot = "/PublishedContent/List",
                SpecificListPathFormatter = "?root={0}&path={1}&fmt=json"
            }
                     );

            IPublishedContentListingService listClient = new CDEPubContentListingService(new HttpClient(mockHttp),
                                                                                         clientOptions.Object,
                                                                                         NullLogger <CDEPubContentListingService> .Instance);

            IPublishedContentListing actualList = listClient.GetItemsForPath(rootName, dataPath);

            /// TODO: Make this a list comparison.
            Assert.NotNull(actualList);
        }
Esempio n. 21
0
        /// <summary>
        /// Creates a new instance of the ESResAggSvcConnection class
        /// </summary>
        /// <param name="testFile">The JSON file for the test response</param>
        public ESResAggSvcConnection(string testFile)
        {
            this.TestFile = testFile;

            //This section is for registering the intercepters for the request.

            //Add Handlers
            this.RegisterRequestHandlerForType <Nest.SearchResponse <Resource> >((req, res) =>
            {
                //Get the request parameters
                //dynamic postObj = this.GetRequestPost(req);

                //Determine which round we are performing
                //int numTokens = postObj["params"].matchedtokencount;

                //Get the file name for this round
                res.Stream = TestingTools.GetTestFileAsStream(GetTestFileName());

                res.StatusCode = 200;
            });
        }
        ///<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);
        }
        public void DataLoading()
        {
            string TestFilePath = "CDEPubContentListingService.ListAvailablePaths.json";

            //Setup a mock handler, which is what HttpClient uses under the hood to fetch
            //data.
            var mockHttp = new MockHttpMessageHandler();

            string filePath = TestFilePath;

            ByteArrayContent content = new ByteArrayContent(TestingTools.GetTestFileAsBytes(filePath));

            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            mockHttp
            .When("https://www.cancer.gov/PublishedContent/List")
            .Respond(System.Net.HttpStatusCode.OK, content);

            // Setup the mocked Options
            Mock <IOptions <PublishedContentListingServiceOptions> > clientOptions = new Mock <IOptions <PublishedContentListingServiceOptions> >();

            clientOptions
            .SetupGet(opt => opt.Value)
            .Returns(new PublishedContentListingServiceOptions()
            {
                Host     = "https://www.cancer.gov",
                ListRoot = "/PublishedContent/List"
            }
                     );

            IPublishedContentListingService listClient = new CDEPubContentListingService(new HttpClient(mockHttp),
                                                                                         clientOptions.Object,
                                                                                         NullLogger <CDEPubContentListingService> .Instance);

            IEnumerable <IPathListInfo> actualList = listClient.ListAvailablePaths();

            /// TODO: Make this a list comparison.
            Assert.NotNull(actualList);
        }
        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());
        }
Esempio n. 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);
        }
Esempio n. 27
0
        public void GetBestBetForDisplay_DataLoading(BaseCategoryTestData data)
        {
            //Setup a mock handler, which is what HttpClient uses under the hood to fetch
            //data.
            var mockHttp = new MockHttpMessageHandler();

            string filePath = data.TestFilePath;

            ByteArrayContent content = new ByteArrayContent(TestingTools.GetTestFileAsBytes(filePath));

            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/xml");

            mockHttp
            .When(string.Format("https://www.cancer.gov/PublishedContent/BestBets/{0}.xml", data.ExpectedData.ID))
            .Respond(System.Net.HttpStatusCode.OK, content);

            // Setup the mocked Options
            Mock <IOptions <CGBestBetsDisplayServiceOptions> > bbClientOptions = new Mock <IOptions <CGBestBetsDisplayServiceOptions> >();

            bbClientOptions
            .SetupGet(opt => opt.Value)
            .Returns(new CGBestBetsDisplayServiceOptions()
            {
                Host = "https://www.cancer.gov",
                BBCategoryPathFormatter = "/PublishedContent/BestBets/{0}.xml"
            }
                     );

            CGBestBetsDisplayService bbClient = new CGBestBetsDisplayService(new HttpClient(mockHttp),
                                                                             bbClientOptions.Object,
                                                                             NullLogger <CGBestBetsDisplayService> .Instance);

            IBestBetDisplay actDisplay = bbClient.GetBestBetForDisplay(data.ExpectedData.ID);

            Assert.Equal(data.ExpectedData, actDisplay, new IBestBetDisplayComparer());
        }
        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());
        }
Esempio n. 29
0
        public async void GetById()
        {
            Mock <ITermQueryService> termQueryService = new Mock <ITermQueryService>();

            string[]      requestedFields = { "TermName", "Pronunciation", "Definition" };
            Pronunciation pronunciation   = new Pronunciation("Pronunciation Key", "pronunciation");
            Definition    definition      = new Definition("<html><h1>Definition</h1></html>", "Sample definition");
            GlossaryTerm  glossaryTerm    = new GlossaryTerm
            {
                TermId           = 1234L,
                Language         = "EN",
                Dictionary       = "Dictionary",
                Audience         = AudienceType.Patient,
                TermName         = "TermName",
                FirstLetter      = "t",
                PrettyUrlName    = "www.glossary-api.com",
                Pronunciation    = pronunciation,
                Definition       = definition,
                RelatedResources = new IRelatedResource[] {
                    new LinkResource()
                    {
                        Type = RelatedResourceType.External,
                        Text = "Link to Google",
                        Url  = new System.Uri("https://www.google.com")
                    },
                    new LinkResource()
                    {
                        Type = RelatedResourceType.DrugSummary,
                        Text = "Bevacizumab",
                        Url  = new System.Uri("https://www.cancer.gov/about-cancer/treatment/drugs/bevacizumab")
                    },
                    new LinkResource()
                    {
                        Type = RelatedResourceType.Summary,
                        Text = "Lung cancer treatment",
                        Url  = new System.Uri("https://www.cancer.gov/types/lung/patient/small-cell-lung-treatment-pdq")
                    },
                    new GlossaryResource()
                    {
                        Type          = RelatedResourceType.GlossaryTerm,
                        Text          = "stage II cutaneous T-cell lymphoma",
                        TermId        = 43966,
                        Audience      = AudienceType.Patient,
                        PrettyUrlName = "stage-ii-cutaneous-t-cell-lymphoma"
                    }
                }
            };

            termQueryService.Setup(
                termQSvc => termQSvc.GetById(
                    It.IsAny <String>(),
                    It.IsAny <AudienceType>(),
                    It.IsAny <string>(),
                    It.IsAny <long>(),
                    It.IsAny <string[]>()
                    )
                )
            .Returns(Task.FromResult(glossaryTerm));

            TermController controller = new TermController(termQueryService.Object);
            GlossaryTerm   gsTerm     = await controller.GetById("Dictionary", AudienceType.Patient, "EN", 1234L, requestedFields);

            string actualJsonValue   = JsonConvert.SerializeObject(gsTerm);
            string expectedJsonValue = File.ReadAllText(TestingTools.GetPathToTestFile("TestData.json"));

            // Verify that the service layer is called:
            // a) with the expected values.
            // b) exactly once.
            termQueryService.Verify(
                svc => svc.GetById("Dictionary", AudienceType.Patient, "EN", 1234L, new string[] { "TermName", "Pronunciation", "Definition" }),
                Times.Once
                );

            Assert.Equal(expectedJsonValue, actualJsonValue);
        }
        public async void Search_HandlesResults()
        {
            GlossaryTermResults glossaryTermResults = new GlossaryTermResults()
            {
                Results = new GlossaryTerm[] {
                    new GlossaryTerm()
                    {
                        TermId        = 46716,
                        Language      = "en",
                        Dictionary    = "Cancer.gov",
                        Audience      = AudienceType.Patient,
                        TermName      = "S-1",
                        FirstLetter   = "s",
                        PrettyUrlName = "s-1",
                        Definition    = new Definition()
                        {
                            Text = "A drug that is being studied for its ability to enhance the effectiveness of fluorouracil and prevent gastrointestinal side effects caused by fluorouracil. It belongs to the family of drugs called antimetabolites.",
                            Html = "A drug that is being studied for its ability to enhance the effectiveness of fluorouracil and prevent gastrointestinal side effects caused by fluorouracil. It belongs to the family of drugs called antimetabolites."
                        },
                        Pronunciation    = null,
                        Media            = new IMedia[] {},
                        RelatedResources = new IRelatedResource[] { }
                    },
                    new GlossaryTerm()
                    {
                        TermId        = 44771,
                        Language      = "en",
                        Dictionary    = "Cancer.gov",
                        Audience      = AudienceType.Patient,
                        TermName      = "S-phase fraction",
                        FirstLetter   = "s",
                        PrettyUrlName = "s-phase-fraction",
                        Definition    = new Definition()
                        {
                            Text = "A measure of the percentage of cells in a tumor that are in the phase of the cell cycle during which DNA is synthesized. The S-phase fraction may be used with the proliferative index to give a more complete understanding of how fast a tumor is growing.",
                            Html = "A measure of the percentage of cells in a tumor that are in the phase of the cell cycle during which DNA is synthesized. The S-phase fraction may be used with the proliferative index to give a more complete understanding of how fast a tumor is growing."
                        },
                        Pronunciation = new Pronunciation()
                        {
                            Key   = "(... fayz FRAK-shun)",
                            Audio = "https://nci-media-dev.cancer.gov/audio/pdq/705947.mp3"
                        },
                        Media            = new IMedia[] {},
                        RelatedResources = new IRelatedResource[] { }
                    },
                    new GlossaryTerm()
                    {
                        TermId        = 572148,
                        Language      = "en",
                        Dictionary    = "Cancer.gov",
                        Audience      = AudienceType.Patient,
                        TermName      = "S100 calcium binding protein A8",
                        FirstLetter   = "s",
                        PrettyUrlName = "s100-calcium-binding-protein-a8",
                        Definition    = new Definition()
                        {
                            Text = "A protein that is made by many different types of cells and is involved in processes that take place both inside and outside of the cell. It is made in larger amounts in inflammatory diseases such as rheumatoid arthritis, and in some types of cancer. It is being studied as a biomarker for breast cancer. Also called calgranulin A.",
                            Html = "A protein that is made by many different types of cells and is involved in processes that take place both inside and outside of the cell. It is made in larger amounts in inflammatory diseases such as rheumatoid arthritis, and in some types of cancer. It is being studied as a biomarker for breast cancer. Also called calgranulin A."
                        },
                        Pronunciation = new Pronunciation()
                        {
                            Key   = "(… KAL-see-um … PROH-teen …)",
                            Audio = "https://nci-media-dev.cancer.gov/audio/pdq/720720.mp3"
                        },
                        Media            = new IMedia[] {},
                        RelatedResources = new IRelatedResource[] { }
                    },
                    new GlossaryTerm()
                    {
                        TermId        = 572151,
                        Language      = "en",
                        Dictionary    = "Cancer.gov",
                        Audience      = AudienceType.Patient,
                        TermName      = "S100 calcium binding protein A9",
                        FirstLetter   = "s",
                        PrettyUrlName = "s100-calcium-binding-protein-a9",
                        Definition    = new Definition()
                        {
                            Text = "A protein that is made by many different types of cells and is involved in processes that take place both inside and outside of the cell. It is made in larger amounts in inflammatory diseases such as rheumatoid arthritis, and in some types of cancer. It is being studied as a biomarker for breast cancer. Also called calgranulin B.",
                            Html = "A protein that is made by many different types of cells and is involved in processes that take place both inside and outside of the cell. It is made in larger amounts in inflammatory diseases such as rheumatoid arthritis, and in some types of cancer. It is being studied as a biomarker for breast cancer. Also called calgranulin B."
                        },
                        Pronunciation = new Pronunciation()
                        {
                            Key   = "(… KAL-see-um … PROH-teen …)",
                            Audio = "https://nci-media-dev.cancer.gov/audio/pdq/720722.mp3"
                        },
                        Media            = new IMedia[] {},
                        RelatedResources = new IRelatedResource[] { }
                    },
                    new GlossaryTerm()
                    {
                        TermId        = 651217,
                        Language      = "en",
                        Dictionary    = "Cancer.gov",
                        Audience      = AudienceType.Patient,
                        TermName      = "SAB",
                        FirstLetter   = "s",
                        PrettyUrlName = "sab",
                        Definition    = new Definition()
                        {
                            Text = "A temporary loss of feeling in the abdomen and/or the lower part of the body. Special drugs called anesthetics are injected into the fluid in the lower part of the spinal column to cause the loss of feeling. The patient stays awake during the procedure.  It is a type of regional anesthesia. Also called spinal anesthesia, spinal block,  and subarachnoid block.",
                            Html = "A temporary loss of feeling in the abdomen and/or the lower part of the body. Special drugs called anesthetics are injected into the fluid in the lower part of the spinal column to cause the loss of feeling. The patient stays awake during the procedure.  It is a type of regional anesthesia. Also called spinal anesthesia, spinal block,  and subarachnoid block."
                        },
                        Pronunciation    = null,
                        Media            = new IMedia[] {},
                        RelatedResources = new IRelatedResource[] { }
                    }
                },
                Meta = new ResultsMetadata()
                {
                    TotalResults = 854,
                    From         = 0
                },
                Links = null
            };

            Mock <ITermsQueryService> termsQueryService = getDumbSearchSvcMock(glossaryTermResults);
            TermsController           controller        = new TermsController(NullLogger <TermsController> .Instance, termsQueryService.Object);


            GlossaryTermResults termResults = await controller.Search("Cancer.gov", AudienceType.Patient, "en", "chicken", MatchType.Begins, 5, 0, true);

            JObject actual   = JObject.Parse(JsonConvert.SerializeObject(termResults));
            JObject expected = JObject.Parse(File.ReadAllText(TestingTools.GetPathToTestFile("TermsControllerData/TestData_Expand.json")));

            // Verify that the service layer is called:
            //  a) with the expected values.
            //  b) exactly once.
            termsQueryService.Verify(
                svc => svc.Search("Cancer.gov", AudienceType.Patient, "en", "chicken", MatchType.Begins, 5, 0, true),
                Times.Once
                );

            Assert.Equal(glossaryTermResults.Results, termResults.Results, new GlossaryTermComparer());
            Assert.Equal(glossaryTermResults.Meta.TotalResults, termResults.Meta.TotalResults);
            Assert.Equal(glossaryTermResults.Meta.From, termResults.Meta.From);
            Assert.Equal(expected, actual, new JTokenEqualityComparer());
        }