Пример #1
0
        public async void QuickTests()
        {
            var dataFileName = "test_image.jpg";

            using (MockContext context = MockContext.Start(this.GetType().Name))
            {
                HttpMockServer.Initialize(this.GetType().Name, "QuickTests", RecorderMode);

                var projectId = CreateTrainedImageClassificationProject();

                ICustomVisionTrainingClient client = GetTrainingClient();

                using (FileStream stream = new FileStream(Path.Combine("TestImages", dataFileName), FileMode.Open))
                {
                    var imageResult = await client.QuickTestImageAsync(projectId, stream);

                    Assert.NotEqual(Guid.Empty, imageResult.Id);
                    Assert.NotEqual(Guid.Empty, imageResult.Iteration);
                    Assert.Equal(projectId, imageResult.Project);
                    Assert.NotEqual(0, imageResult.Predictions.Count);
                    Assert.InRange(imageResult.Predictions[0].Probability, 0.9, 1);
                    Assert.Equal("Tag1", imageResult.Predictions[0].TagName);
                }

                string imageUrl  = "https://raw.githubusercontent.com/Microsoft/Cognitive-CustomVision-Windows/master/Samples/Images/Test/test_image.jpg";
                var    urlResult = await client.QuickTestImageUrlAsync(projectId, new ImageUrl(imageUrl));

                Assert.NotEqual(Guid.Empty, urlResult.Id);
                Assert.NotEqual(Guid.Empty, urlResult.Iteration);
                Assert.Equal(projectId, urlResult.Project);
                Assert.NotEqual(0, urlResult.Predictions.Count);
                Assert.InRange(urlResult.Predictions[0].Probability, 0.9, 1);
                Assert.Equal("Tag1", urlResult.Predictions[0].TagName);

                await client.DeleteProjectAsync(projectId);
            }
        }
        public async void GetTaggedImages()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                HttpMockServer.Initialize(this.GetType(), "GetTaggedImages", RecorderMode);

                using (var project = CreateTrainedImageClassificationProject())
                    using (ICustomVisionTrainingClient client = GetTrainingClient())
                    {
                        var images = await client.GetTaggedImagesAsync(project.ProjectId);

                        var tag1 = images[0].Tags[0].TagId;

                        var imagesWithTag1 = 0;

                        Assert.Equal(10, images.Count);
                        foreach (var image in images)
                        {
                            Assert.NotEqual(Guid.Empty, image.Id);
                            Assert.NotEmpty(image.OriginalImageUri);
                            Assert.NotEmpty(image.ResizedImageUri);
                            Assert.NotEmpty(image.ThumbnailUri);
                            Assert.NotEqual(0, image.Width);
                            Assert.NotEqual(0, image.Height);
                            Assert.Equal(1, image.Tags.Count);
                            if (image.Tags[0].TagId == tag1)
                            {
                                imagesWithTag1++;
                            }
                        }

                        var tag1Images = await client.GetTaggedImagesAsync(project.ProjectId, null, new Guid[] { tag1 });

                        Assert.Equal(imagesWithTag1, tag1Images.Count);
                    }
            }
        }
Пример #3
0
        public void VideoTrending()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                HttpMockServer.Initialize(this.GetType(), "VideoTrending");

                IVideoSearchClient client = new VideoSearchClient(new ApiKeyServiceClientCredentials(SubscriptionKey), HttpMockServer.CreateInstance());

                var resp = client.Videos.TrendingAsync().Result;

                Assert.NotNull(resp);

                Assert.NotNull(resp.BannerTiles);
                Assert.True(resp.BannerTiles.Count > 0);

                var bannerTile = resp.BannerTiles[0];
                Assert.NotNull(bannerTile.Image);
                Assert.NotNull(bannerTile.Query);

                Assert.NotNull(resp.Categories);
                Assert.True(resp.Categories.Count > 0);

                var category = resp.Categories[0];
                Assert.NotNull(category.Title);
                Assert.NotNull(category.Subcategories);
                Assert.True(category.Subcategories.Count > 0);

                var subCategory = category.Subcategories[0];
                Assert.NotNull(subCategory.Title);
                Assert.NotNull(subCategory.Tiles);
                Assert.True(subCategory.Tiles.Count > 0);

                var subCategoryTile = subCategory.Tiles[0];
                Assert.NotNull(subCategoryTile.Image);
                Assert.NotNull(subCategoryTile.Query);
            }
        }
Пример #4
0
        public void TestNormalDistributionSeries()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "TestNormalDistributionSeries");
                IAnomalyDetectorClient client = GetAnomalyDetectorClient(HttpMockServer.CreateInstance());

                var startTime = DateTime.Parse("2018-05-01T00:00:00Z");

                double sigma      = 0.01;
                double step       = 0.0008;
                int    len        = 99;
                double start      = -(len / 2) * step;
                var    singleTile = new List <double>();
                for (int i = 0; i < len; ++i)
                {
                    double x = start + step * i;
                    singleTile.Add(1 / (sigma * Math.Sqrt(2 * Math.PI)) * Math.Exp(-x * x / (2 * sigma * sigma)));
                }

                var series = new List <Point>();
                for (int i = 0; i < len * 4; ++i)
                {
                    series.Add(new Point(startTime.AddDays(i), singleTile[i % len]));
                }

                Request request = new Request(series, Granularity.Daily);
                var     result  = client.EntireDetectAsync(request).Result;
                Assert.Equal(len, result.Period);
                Assert.DoesNotContain(true, result.IsAnomaly);

                int anomalyIndex = FakeRandom(len, len * 4 - 1);
                request.Series[anomalyIndex].Value = 100;
                result = client.EntireDetectAsync(request).Result;
                Assert.True(result.IsAnomaly[anomalyIndex]);
            }
        }
        public void TestListStorageTargetByCache()
        {
            this.testOutputHelper.WriteLine($"Running in {HttpMockServer.GetCurrentMode()} mode.");
            using (StorageCacheTestContext context = new StorageCacheTestContext(this))
            {
                var client = context.GetClient <StorageCacheManagementClient>();
                client.ApiVersion = Constants.DefaultAPIVersion;
                this.fixture.CacheHelper.StoragecacheManagementClient = client;
                StorageTarget storageTarget;
                try
                {
                    storageTarget = this.fixture.CacheHelper.GetStorageTarget(this.fixture.Cache.Name, this.fixture.ResourceGroup.Name);
                }
                catch (CloudErrorException)
                {
                    storageTarget = this.storageAccountsFixture.AddClfsStorageAccount(context, waitForStorageTarget: false, waitForPermissions: false);
                }

                IList <StorageTarget> storageTargetListResponse = this.fixture.CacheHelper.StoragecacheManagementClient.StorageTargets.ListByCache(this.fixture.ResourceGroup.Name, this.fixture.Cache.Name).Value;
                Assert.True(storageTargetListResponse.Count >= 1);
                bool found = false;
                foreach (StorageTarget response in storageTargetListResponse)
                {
                    if (string.Equals(response.Name, storageTarget.Name))
                    {
                        found = true;
                        Assert.Equal(storageTarget.Id, response.Id, ignoreCase: true);
                        Assert.Equal(storageTarget.Clfs.Target, response.Clfs.Target);
                        Assert.Equal(storageTarget.Type, response.Type);
                        Assert.Equal(storageTarget.Junctions[0].NamespacePath, response.Junctions[0].NamespacePath);
                        Assert.Equal(storageTarget.Junctions[0].TargetPath, response.Junctions[0].TargetPath);
                    }
                }

                Assert.True(found, string.Format("Storage target {0} not found in the list response.", storageTarget.Name));
            }
        }
        public void ReadFileInStreamTest()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                HttpMockServer.Initialize(this.GetType(), "ReadFileInStreamTest");

                using (IComputerVisionClient client = GetComputerVisionClient(HttpMockServer.CreateInstance()))
                    using (FileStream stream = new FileStream(GetTestImagePath("whiteboard.jpg"), FileMode.Open))
                    {
                        ReadInStreamHeaders headers = client.ReadInStreamWithHttpMessagesAsync(stream).Result.Headers;

                        Assert.NotNull(headers.OperationLocation);

                        ReadOperationResult readOperationResult = GetRecognitionResultWithPolling(client, headers.OperationLocation);

                        Assert.NotNull(readOperationResult);
                        Assert.Equal(OperationStatusCodes.Succeeded, readOperationResult.Status);

                        Assert.NotNull(readOperationResult.AnalyzeResult);
                        Assert.Equal(1, readOperationResult.AnalyzeResult.ReadResults.Count);

                        var recognitionResult = readOperationResult.AnalyzeResult.ReadResults[0];

                        Assert.Equal(1, recognitionResult.Page);
                        Assert.Equal(1000, recognitionResult.Width);
                        Assert.Equal(664, recognitionResult.Height);
                        Assert.Equal(TextRecognitionResultDimensionUnit.Pixel, recognitionResult.Unit);

                        Assert.Equal(
                            new string[] { "you must be the change", "you want to see in the world!" }.OrderBy(t => t),
                            recognitionResult.Lines.Select(line => line.Text).OrderBy(t => t));
                        Assert.Equal(2, recognitionResult.Lines.Count);
                        Assert.Equal(5, recognitionResult.Lines[0].Words.Count);
                        Assert.Equal(7, recognitionResult.Lines[1].Words.Count);
                    }
            }
        }
Пример #7
0
        public void SubmitHiveJobError()
        {
            using (var context = UndoContext.Current)
            {
                context.Start();

                var client = TestUtils.GetHDInsightJobManagementClient();

                var parameters = new HiveJobSubmissionParameters
                {
                    Query     = "FAKEQUERY;",
                    StatusDir = "jobstatus"
                };

                var response = client.JobManagement.SubmitHiveJob(parameters);
                Assert.NotNull(response);
                Assert.Equal(response.StatusCode, HttpStatusCode.OK);

                var jobId = response.JobSubmissionJsonResponse.Id;
                Assert.Contains("job_", jobId, StringComparison.InvariantCulture);

                var jobStatus = client.JobManagement.WaitForJobCompletionAsync(jobId).Result;

                Assert.True(jobStatus.JobDetail.ExitValue > 0);

                var storageAccess = GetStorageAccessObject();

                if (HttpMockServer.GetCurrentMode() == HttpRecorderMode.Record)
                {
                    var output = client.JobManagement.GetJobErrorLogs(jobId, storageAccess);
                    Assert.NotNull(output);
                    Assert.True(output.Length > 0);
                    string errorTextOutput = Convert(output);
                    Assert.True(!string.IsNullOrEmpty(errorTextOutput));
                }
            }
        }
        public TClient CreateCustomClient <TClient>(params object[] parameters) where TClient : ServiceClient <TClient>
        {
            TClient client = ManagementClients.FirstOrDefault(o => o is TClient) as TClient;

            if (client == null)
            {
                if (throwWhenNotAvailable)
                {
                    throw new ArgumentException(
                              string.Format("TestManagementClientHelper class wasn't initialized with the {0} client.",
                                            typeof(TClient).Name));
                }
                else
                {
                    var realClientFactory = new ClientFactory();
                    var realClient        = realClientFactory.CreateCustomClient <TClient>(parameters);
                    var newRealClient     = realClient.WithHandler(HttpMockServer.CreateInstance());
                    realClient.Dispose();
                    return(newRealClient);
                }
            }

            return(client);
        }
        public EnvironmentSetupHelper()
        {
            var datastore = new MemoryDataStore();

            AzureSession.DataStore = datastore;
            var profile = new AzureProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));

            AzurePSCmdlet.CurrentProfile = profile;
            AzureSession.DataStore       = datastore;
            ProfileClient = new ProfileClient(profile);

            // Ignore SSL errors
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true;

            // Set RunningMocked
            if (HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback)
            {
                TestMockSupport.RunningMocked = true;
            }
            else
            {
                TestMockSupport.RunningMocked = false;
            }
        }
Пример #10
0
        public async void DownloadRegions()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                HttpMockServer.Initialize(this.GetType(), "DownloadRegions", RecorderMode);

                using (var project = CreateTrainedObjDetectionProject())
                {
                    ICustomVisionTrainingClient client = BaseTests.GetTrainingClient();

                    var images = await client.GetTaggedImagesAsync(project.ProjectId);

                    foreach (var img in images)
                    {
                        Assert.NotNull(img.Regions);
                        Assert.Equal(1, img.Regions.Count);
                        Assert.InRange(img.Regions[0].Left, 0, 1);
                        Assert.InRange(img.Regions[0].Top, 0, 1);
                        Assert.InRange(img.Regions[0].Width, 0, 1);
                        Assert.InRange(img.Regions[0].Height, 0, 1);
                    }
                }
            }
        }
Пример #11
0
        public void AddZipFramesVideoReview()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    rvwStatus = ReviewStatus.UNPUBLISHED;
                    //CreateVideoReview();
                    api = ReviewAPI.FRAMES_ADD;
                    HttpMockServer.Initialize("ReviewAPIs", "AddZipFramesVideoReview");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    //results = Constants.GetVideoFramesReviewResponse(client, api, Content.VIDEO, MIMETypes.MULTI_PART_FORM_DATA.GetDescription(), teamName, ReviewIds[0], false);
                    results = Constants.GetVideoFramesReviewResponse(client, api, Content.VIDEO, MIMETypes.MULTI_PART_FORM_DATA.GetDescription(), teamName, "201712vc779930a65dc4de993d25bc21f53f928", false);

                    var review = results.AddFrames;
                    Assert.NotNull(review);
                    Assert.Equal(HttpStatusCode.NoContent, review.Response.StatusCode);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Пример #12
0
        public EnvironmentSetupHelper()
        {
            var datastore = new MemoryDataStore();

            AzureSession.DataStore = datastore;
            var profile   = new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));
            var rmprofile = new AzureRMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));

            rmprofile.Environments.Add("foo", AzureEnvironment.PublicEnvironments.Values.FirstOrDefault());
            rmprofile.Context = new AzureContext(new AzureSubscription(), new AzureAccount(), rmprofile.Environments["foo"], new AzureTenant());
            rmprofile.Context.Subscription.Environment = "foo";
            if (AzureRmProfileProvider.Instance.Profile == null)
            {
                AzureRmProfileProvider.Instance.Profile = rmprofile;
            }

            AzureSession.DataStore = datastore;            ProfileClient = new ProfileClient(profile);

            // Ignore SSL errors
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true;

            // Set RunningMocked
            TestMockSupport.RunningMocked = HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback;
        }
Пример #13
0
        public void OcrImageTest()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                HttpMockServer.Initialize(this.GetType(), "OcrImageTest");

                string germanTextUrl = GetTestImageUrl("achtung.jpg");

                using (IComputerVisionClient client = GetComputerVisionClient(HttpMockServer.CreateInstance()))
                {
                    const bool DetectOrientation = true;
                    OcrResult  result            = client.RecognizePrintedTextAsync(DetectOrientation, germanTextUrl, OcrLanguages.De).Result;

                    Assert.Equal("de", result.Language);
                    Assert.Equal("Up", result.Orientation);
                    Assert.True(result.TextAngle > 0);
                    Assert.Equal(1, result.Regions.Count);
                    Assert.Equal(1, result.Regions[0].Lines.Count);
                    Assert.Equal(1, result.Regions[0].Lines[0].Words.Count);
                    Assert.Equal("ACHTUNG", result.Regions[0].Lines[0].Words[0].Text);
                    Assert.True(result.Regions[0].BoundingBox == result.Regions[0].Lines[0].BoundingBox);
                }
            }
        }
        public void AddImage()
        {
            try
            {
                using (MockContext context = MockContext.Start("ImageListManagement"))
                {
                    //GetImageLists();
                    //wait(2);
                    //imageListId = ((int)allImageLists[1].Id).ToString();

                    Constants.AddImage = new BodyModel("URL", "https://moderatorsampleimages.blob.core.windows.net/samples/sample.jpg");
                    api = ContentModeratorAPI.ADD_IMAGE;
                    HttpMockServer.Initialize("ImageListManagement", "AddImage");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    //results = Constants.GetResponse(client, api, imageListId);
                    results = Constants.GetResponse(client, api, "157299");
                    if (results.InnerException != null)
                    {
                        DeleteImage();
                        api = ContentModeratorAPI.ADD_IMAGE;
                        HttpMockServer.Initialize("ImageListManagement", "AddImage");
                        client  = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                        results = Constants.GetResponse(client, api, null);
                    }
                    var addImgeToListId = results.AddImage;

                    Assert.NotNull(addImgeToListId);
                    Assert.Equal(HttpStatusCode.OK, addImgeToListId.Response.StatusCode);
                    Assert.True(Helpers.Utilities.VerifyAddImageResponse(addImgeToListId.Body), "Add Image Response verification failed." + TestBase.ErrorMessage);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Пример #15
0
        public TestsFixture()
        {
            _context = new MockContext();
            MockContext.Start(this.GetType(), ".ctor");
            try
            {
                _redisEnterpriseCacheManagementHelper = new RedisEnterpriseCacheManagementHelper(this, _context);
                _redisEnterpriseCacheManagementHelper.TryRegisterSubscriptionForResource();

                ResourceGroupName        = TestUtilities.GenerateName("RedisEnterpriseCreateUpdate");
                RedisEnterpriseCacheName = TestUtilities.GenerateName("RedisEnterpriseCreateUpdate");
                DatabaseName             = "default";
                _redisEnterpriseCacheManagementHelper.TryCreateResourceGroup(ResourceGroupName, RedisEnterpriseCacheManagementHelper.Location);
            }
            catch (Exception)
            {
                Cleanup();
                throw;
            }
            finally
            {
                HttpMockServer.Flush();
            }
        }
        public TClient CreateClient <TClient>(bool addRestLogHandler, EventHandler <ClientCreatedArgs> clientCreatedHandler,
                                              params object[] parameters) where TClient : ServiceClient <TClient>
        {
            TClient client = ManagementClients.FirstOrDefault(o => o is TClient) as TClient;

            if (client == null)
            {
                if (throwWhenNotAvailable)
                {
                    throw new ArgumentException(
                              string.Format("TestManagementClientHelper class wasn't initialized with the {0} client.",
                                            typeof(TClient).Name));
                }
                else
                {
                    var realHelper = new ManagementClientHelper();
                    var realClient = realHelper.CreateClient <TClient>(addRestLogHandler, clientCreatedHandler, parameters);
                    realClient.WithHandler(HttpMockServer.CreateInstance());
                    return(realClient);
                }
            }

            return(client);
        }
Пример #17
0
        public void FaceFindSimilarLargeFaceListPositive()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "FaceFindSimilarLargeFaceListPositive");

                IFaceClient client          = GetFaceClient(HttpMockServer.CreateInstance());
                Guid?       faceId1         = null;
                string      largeFaceListId = "large-face-list-id";
                client.LargeFaceList.CreateAsync(largeFaceListId, "fakeLargeFaceList", recognitionModel: recognitionModel).Wait();
                try
                {
                    var satyaPersistedFaceIds = AddLargeFaceListFace(client, largeFaceListId, "Satya");
                    var gatesPersistedFaceIds = AddLargeFaceListFace(client, largeFaceListId, "Gates");
                    client.LargeFaceList.TrainAsync(largeFaceListId).Wait();

                    var trainingStatus = WaitForTraining(client, largeFaceListId);
                    Assert.Equal(TrainingStatusType.Succeeded, trainingStatus.Status);

                    using (FileStream stream = new FileStream(Path.Combine("TestImages", "Satya4.jpg"), FileMode.Open))
                    {
                        faceId1 = client.Face.DetectWithStreamAsync(stream, true, recognitionModel: recognitionModel).Result[0].FaceId;
                        Assert.NotNull(faceId1);
                    }

                    IList <SimilarFace> findSimilarResults = client.Face.FindSimilarAsync(faceId1.Value, largeFaceListId: largeFaceListId).Result;
                    Assert.True(findSimilarResults.Count > 0);
                    Assert.Contains(findSimilarResults[0].PersistedFaceId, satyaPersistedFaceIds);
                    Assert.True(findSimilarResults[0].Confidence > 0.5);
                }
                finally
                {
                    client.LargeFaceList.DeleteAsync(largeFaceListId).Wait();
                }
            }
        }
Пример #18
0
        public void NewsCategory()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "NewsCategory");

                INewsSearchClient client = new NewsSearchClient(new ApiKeyServiceClientCredentials(SubscriptionKey), HttpMockServer.CreateInstance());

                var resp = client.News.CategoryAsync(category: "sports").Result;

                Assert.NotNull(resp);
                Assert.NotNull(resp.Value);
                Assert.True(resp.Value.Count > 0);

                var news = resp.Value[0];
                Assert.NotNull(news.Name);
                Assert.NotNull(news.Url);
                Assert.NotNull(news.Description);
                Assert.NotNull(news.DatePublished);
                Assert.NotNull(news.Provider);
                Assert.NotNull(news.Category);
                Assert.NotNull(news.Provider[0].Name);
            }
        }
Пример #19
0
        public void OcrImageInStreamTest()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                HttpMockServer.Initialize(this.GetType(), "OcrImageInStreamTest");

                using (IComputerVisionClient client = GetComputerVisionClient(HttpMockServer.CreateInstance()))
                    using (FileStream stream = new FileStream(GetTestImagePath("signage.jpg"), FileMode.Open))
                    {
                        const bool DetectOrientation = true;
                        OcrResult  result            = client.RecognizePrintedTextInStreamAsync(DetectOrientation, stream).Result;

                        Assert.Equal("en", result.Language);
                        Assert.Equal("Up", result.Orientation);
                        Assert.True(result.TextAngle < 0);
                        Assert.Equal(1, result.Regions.Count);
                        Assert.Equal(3, result.Regions[0].Lines.Count);
                        Assert.Equal(1, result.Regions[0].Lines[0].Words.Count);
                        Assert.Equal("WEST", result.Regions[0].Lines[0].Words[0].Text);
                        Assert.Equal("520", result.Regions[0].Lines[1].Words[0].Text);
                        Assert.Equal("Seattle", result.Regions[0].Lines[2].Words[0].Text);
                    }
            }
        }
Пример #20
0
        public void AnalyzeImageModelVersionTest()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                HttpMockServer.Initialize(this.GetType(), "AnalyzeImageModelVersionTest");

                using (IComputerVisionClient client = GetComputerVisionClient(HttpMockServer.CreateInstance()))
                    using (FileStream stream = new FileStream(GetTestImagePath("house.jpg"), FileMode.Open))
                    {
                        const string targetModelVersion = "2021-04-01";

                        ImageAnalysis result = client.AnalyzeImageInStreamAsync(
                            stream,
                            new List <VisualFeatureTypes?>()
                        {
                            VisualFeatureTypes.Categories
                        },
                            modelVersion: targetModelVersion)
                                               .Result;

                        Assert.Equal(targetModelVersion, result.ModelVersion);
                    }
            }
        }
Пример #21
0
        private static T AddMockHandler <T>(ref T client) where T : class
        {
            HttpMockServer server;

            try
            {
                server = HttpMockServer.CreateInstance();
            }
            catch (ApplicationException)
            {
                // mock server has never been initialized, we will need to initialize it.
                HttpMockServer.Initialize("TestEnvironment", "InitialCreation");
                server = HttpMockServer.CreateInstance();
            }

            var method = typeof(T).GetMethod("WithHandler", new Type[] { typeof(DelegatingHandler) });

            client = method.Invoke(client, new object[] { server }) as T;

            if (HttpMockServer.Mode != HttpRecorderMode.Playback)
            {
                return(client);
            }

            var initialTimeout = typeof(T).GetProperty("LongRunningOperationInitialTimeout", typeof(int));
            var retryTimeout   = typeof(T).GetProperty("LongRunningOperationRetryTimeout", typeof(int));

            if (initialTimeout == null || retryTimeout == null)
            {
                return(client);
            }

            initialTimeout.SetValue(client, 0);
            retryTimeout.SetValue(client, 0);
            return(client);
        }
 public void TestFlushCacheWithoutStorageTarget()
 {
     this.testOutputHelper.WriteLine($"Running in {HttpMockServer.GetCurrentMode()} mode.");
     using (StorageCacheTestContext context = new StorageCacheTestContext(this))
     {
         var client = context.GetClient <StorageCacheManagementClient>();
         client.ApiVersion = Constants.DefaultAPIVersion;
         client.Caches.Flush(this.fixture.ResourceGroup.Name, this.fixture.Cache.Name);
         this.fixture.CacheHelper.StoragecacheManagementClient = client;
         if (HttpMockServer.Mode == HttpRecorderMode.Record)
         {
             this.fixture.CacheHelper.WaitForCacheState(
                 this.fixture.CacheHelper.GetCacheHealthState,
                 this.fixture.Cache.Name,
                 "Flushing",
                 timeout: 120, polling_delay: 5).GetAwaiter().GetResult();
             this.fixture.CacheHelper.WaitForCacheState(
                 this.fixture.CacheHelper.GetCacheHealthState,
                 this.fixture.Cache.Name,
                 "Healthy",
                 polling_delay: 5).GetAwaiter().GetResult();
         }
     }
 }
Пример #23
0
        public void NewsTrending()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "NewsTrending");

                INewsSearchClient client = new NewsSearchClient(new ApiKeyServiceClientCredentials(SubscriptionKey), HttpMockServer.CreateInstance());

                var resp = client.News.TrendingAsync().Result;

                Assert.NotNull(resp);
                Assert.NotNull(resp.Value);
                Assert.True(resp.Value.Count > 0);

                var trendingTopic = resp.Value[0];
                Assert.NotNull(trendingTopic.Name);
                Assert.NotNull(trendingTopic.WebSearchUrl);
                Assert.NotNull(trendingTopic.NewsSearchUrl);
                Assert.NotNull(trendingTopic.Image);
                Assert.NotNull(trendingTopic.Image.Url);
                Assert.NotNull(trendingTopic.Query);
                Assert.NotNull(trendingTopic.Query.Text);
            }
        }
Пример #24
0
        public void AnalyzeImageInStreamTest()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "AnalyzeImageInStreamTest");

                using (IComputerVisionClient client = GetComputerVisionClient(HttpMockServer.CreateInstance()))
                    using (FileStream stream = new FileStream(GetTestImagePath("house.jpg"), FileMode.Open))
                    {
                        ImageAnalysis result = client.AnalyzeImageInStreamAsync(
                            stream,
                            new List <VisualFeatureTypes>()
                        {
                            VisualFeatureTypes.Adult,
                            VisualFeatureTypes.Categories,
                            VisualFeatureTypes.Color,
                            VisualFeatureTypes.Faces,
                            VisualFeatureTypes.ImageType,
                            VisualFeatureTypes.Tags
                        })
                                               .Result;

                        Assert.Equal("grass", result.Tags[0].Name);
                        Assert.True(result.Tags[0].Confidence > 0.9);
                        Assert.Equal("Jpeg", result.Metadata.Format);
                        Assert.False(result.Adult.IsAdultContent);
                        Assert.False(result.Adult.IsRacyContent);
                        Assert.True(result.Adult.AdultScore < 0.1);
                        Assert.True(result.Adult.RacyScore < 0.1);
                        Assert.Equal("building_", result.Categories[0].Name);
                        Assert.True(result.Categories[0].Score > 0.5);
                        Assert.Equal("Green", result.Color.DominantColorBackground);
                        Assert.Equal("Green", result.Color.DominantColorForeground);
                    }
            }
        }
Пример #25
0
        public void CreateVideoReview()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    api = ReviewAPI.REVIEW_CREATE;
                    HttpMockServer.Initialize("ReviewAPIs", "CreateVideoReview");
                    client  = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    results = Constants.GetReviewResponse(client, api, Content.VIDEO, MIMETypes.JSON.GetDescription(), teamName, null, null, null, null, null, rvwStatus);

                    var review = results.CreateReview;
                    Assert.NotNull(review);
                    Assert.Equal(HttpStatusCode.OK, review.Response.StatusCode);
                    ReviewIds = review.Body.ToList();
                    Assert.True(ReviewIds.Count > 0, "Video Reviewid did not get generated");
                    Assert.NotNull(ReviewIds[0]);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        private void OnClientCreated(object sender, ClientCreatedArgs e)
        {
            e.AddHandlerToClient(HttpMockServer.CreateInstance());
            bool runningMocked = (HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback);

            TestMockSupport.RunningMocked = runningMocked;
            if (runningMocked)
            {
                PropertyInfo initTimeoutProp  = e.ClientType.GetProperty("LongRunningOperationInitialTimeout");
                PropertyInfo retryTimeoutProp = e.ClientType.GetProperty("LongRunningOperationRetryTimeout");
                if (initTimeoutProp != null && retryTimeoutProp != null)
                {
                    initTimeoutProp.SetValue(e.CreatedClient, 0, null);
                    retryTimeoutProp.SetValue(e.CreatedClient, 0, null);
                }
            }
            else
            {
                if (!HttpMockServer.Variables.ContainsKey(Variables.SubscriptionId))
                {
                    HttpMockServer.Variables.Add(Variables.SubscriptionId, testSubscrption.SubscriptionId);
                }
            }
        }
Пример #27
0
 public void DeleteTermList()
 {
     try
     {
         using (MockContext context = MockContext.Start("TextListManagement"))
         {
             //GetTermLists();
             //wait(2);// should wait as the plan permits 1 trans/sec
             api = ContentModeratorAPI.DELETE_TERM_LIST;
             //TermListIdToDelete = ((int)allTermLists[0].Id).ToString();
             HttpMockServer.Initialize("TextListManagement", "DeleteTermList");
             client  = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
             results = Constants.GetResponse(client, api, "66");
             var deleteTermLists = results.DeleteTermLists;
             Assert.NotNull(deleteTermLists);
             Assert.Equal(HttpStatusCode.OK, deleteTermLists.Response.StatusCode);
             Assert.Equal("", deleteTermLists.Body);
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
Пример #28
0
        public void QnAMakerPreviewRuntimeGenerateAnswerTest()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                HttpMockServer.Initialize(this.GetType(), "QnAMakerPreviewRuntimeGenerateAnswerTest");

                var client   = GetQnAMakerClient(HttpMockServer.CreateInstance());
                var queryDTO = new QueryDTO();
                queryDTO.Question          = "new question";
                queryDTO.Top               = 3;
                queryDTO.IsTest            = true;
                queryDTO.AnswerSpanRequest = new QueryDTOAnswerSpanRequest()
                {
                    Enable             = true,
                    ScoreThreshold     = 5.0,
                    TopAnswersWithSpan = 1
                };

                var answer = client.Knowledgebase.GenerateAnswerAsync(KbId, queryDTO).Result;
                Assert.Equal(1, answer.Answers.Count);
                Assert.NotEmpty(answer.Answers[0].AnswerSpan.Text);
                Assert.Equal(100, answer.Answers[0].Score);
            }
        }
        public HttpClient CreateHttpClient(string serviceUrl, HttpMessageHandler effectiveHandler)
        {
            if (serviceUrl == null)
            {
                throw new ArgumentNullException("serviceUrl");
            }
            if (effectiveHandler == null)
            {
                throw new ArgumentNullException("effectiveHandler");
            }
            var mockHandler = HttpMockServer.CreateInstance();

            mockHandler.InnerHandler = effectiveHandler;

            HttpClient client = new HttpClient(mockHandler)
            {
                BaseAddress = new Uri(serviceUrl),
                MaxResponseContentBufferSize = 30 * 1024 * 1024
            };

            client.DefaultRequestHeaders.Accept.Clear();

            return(client);
        }
Пример #30
0
        public void FindFacesRaw()
        {
            try
            {
                using (MockContext context = MockContext.Start("ImageModerator"))
                {
                    HttpMockServer.Initialize("ImageModerator", "FindFacesRaw");

                    //wait(2);


                    Stream imgStream = new FileStream(rawImageCurrentPath, FileMode.Open, FileAccess.Read);
                    api    = ContentModeratorAPI.FIND_FACES;
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());

                    results = Constants.GetImageResponseRaw(client, api, "", imgStream, MIMETypes.IMAGE_JPEG.GetDescription());
                    if (results.InnerException == null)
                    {
                        var findfaces = results.FoundFaces;
                        Assert.NotNull(findfaces);
                        Assert.Equal(HttpStatusCode.OK, findfaces.Response.StatusCode);
                        Assert.True(Helpers.Utilities.VerifyFoundFaces(findfaces.Body), TestBase.ErrorMessage);
                    }
                    else
                    {
                        var ex = results.InnerException;
                        Assert.NotNull(ex);
                        Assert.Equal(HttpStatusCode.BadRequest, ex.Response.StatusCode);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }