Exemple #1
0
        public async Task IncludesAdditionalInformationIfAvailable()
        {
            var formattedResponse =
                "Service request failed." + s_nl +
                "Status: 210 (Reason)" + s_nl +
                s_nl +
                "Additional Information:" + s_nl +
                "a: a-value" + s_nl +
                "b: b-value" + s_nl +
                s_nl +
                "Headers:" + s_nl +
                "Custom-Header: Value" + s_nl +
                "x-ms-requestId: 123" + s_nl;

            var response = new MockResponse(210, "Reason");

            response.AddHeader(new HttpHeader("Custom-Header", "Value"));
            response.AddHeader(new HttpHeader("x-ms-requestId", "123"));

            RequestFailedException exception = await ClientDiagnostics.CreateRequestFailedExceptionAsync(response, additionalInfo : new Dictionary <string, string>()
            {
                { "a", "a-value" },
                { "b", "b-value" },
            });

            Assert.AreEqual(formattedResponse, exception.Message);
            Assert.AreEqual("a-value", exception.Data["a"]);
            Assert.AreEqual("b-value", exception.Data["b"]);
        }
        public async Task FormatsResponseContentForTextContentTypes()
        {
            var formattedResponse =
                "Status: 210" + _nl +
                "ReasonPhrase: Reason" + _nl +
                _nl +
                "Headers:" + _nl +
                "Content-Type: text/json" + _nl +
                "x-ms-requestId: 123" + _nl +
                _nl +
                "Content:" + _nl +
                "{\"errorCode\": 1}" + _nl;

            var response = new MockResponse(210, "Reason");

            response.AddHeader(new HttpHeader("Content-Type", "text/json"));
            response.AddHeader(new HttpHeader("x-ms-requestId", "123"));
            response.SetContent("{\"errorCode\": 1}");

            var exception = await response.CreateRequestFailedExceptionAsync();

            Assert.AreEqual("Request failed with status code 210", exception.Message);
            Assert.AreEqual(formattedResponse, exception.ResponseDetails);
            Assert.AreEqual("Azure.RequestFailedException: " + exception.Message + _nl + exception.ResponseDetails, exception.ToString());
        }
Exemple #3
0
        public void DateReturnsDateHeaderValueFirst()
        {
            var mockResponse = new MockResponse(200);

            mockResponse.AddHeader(new HttpHeader("x-ms-date", "Sun, 29 Sep 2013 01:02:03 GMT"));
            mockResponse.AddHeader(new HttpHeader("Date", "Sun, 29 Sep 2013 09:02:03 GMT"));

            Assert.AreEqual(new DateTimeOffset(2013, 9, 29, 9, 2, 3, TimeSpan.Zero), mockResponse.Headers.Date);
        }
Exemple #4
0
        public async Task ResourceDeleteSupportNoContentReturnCode()
        {
            var mockResponse = new MockResponse((int)HttpStatusCode.NoContent);
            var content      = JsonDocument.Parse("{}").RootElement.ToString();
            var header       = new HttpHeader("x-ms-request-id", "1");

            mockResponse.AddHeader(header);
            mockResponse.SetContent(content);

            var mockTransport = new MockTransport(mockResponse);
            var client        = GetResourceManagementClient(mockTransport);

            string resourceName = "site3";
            string resourceProviderNamespace  = "Microsoft.Web";
            string resourceProviderApiVersion = "2014-01-04";
            string resourceType = "sites";

            try
            {
                await client.Resources.StartDeleteAsync("foo",
                                                        resourceProviderNamespace,
                                                        "",
                                                        resourceType,
                                                        resourceName,
                                                        resourceProviderApiVersion);
            }
            catch (Exception ex)
            {
                Assert.NotNull(ex);
            }
        }
Exemple #5
0
        public async Task ResourceDeleteValidateMessage()
        {
            var mockResponse = new MockResponse((int)HttpStatusCode.OK);
            var content      = JsonDocument.Parse("{}").RootElement.ToString();
            var header       = new HttpHeader("x-ms-request-id", "1");

            mockResponse.AddHeader(header);
            mockResponse.SetContent(content);

            var mockTransport = new MockTransport(mockResponse);
            var client        = GetResourceManagementClient(mockTransport);

            string resourceName = "site3";
            string resourceProviderNamespace  = "Microsoft.Web";
            string resourceProviderApiVersion = "2014-01-04";
            string resourceType = "sites";
            await client.Resources.StartDeleteAsync("foo",
                                                    resourceProviderNamespace,
                                                    "",
                                                    resourceType,
                                                    resourceName,
                                                    resourceProviderApiVersion);

            // Validate headers
            var request = mockTransport.Requests[0];

            Assert.AreEqual(HttpMethod.Delete.Method, request.Method.Method);
            Assert.IsTrue(request.Headers.Contains("Authorization"));
        }
Exemple #6
0
        public async Task ResourceExistsValidateMissingMessage()
        {
            var mockResponse = new MockResponse((int)HttpStatusCode.NotFound);
            var header       = new HttpHeader("x-ms-request-id", "1");

            mockResponse.AddHeader(header);

            var mockTransport = new MockTransport(mockResponse);
            var client        = GetResourceManagementClient(mockTransport);

            string resourceName = Guid.NewGuid().ToString();
            string resourceProviderNamespace  = "Microsoft.Web";
            string resourceProviderApiVersion = "2014-01-04";
            string resourceType = "sites";

            var result = await client.Resources.CheckExistenceAsync(
                "foo",
                resourceProviderNamespace,
                "",
                resourceType,
                resourceName,
                resourceProviderApiVersion);

            // Validate headers
            var request = mockTransport.Requests[0];

            Assert.AreEqual(HttpMethod.Head.Method, request.Method.Method);
            Assert.IsTrue(request.Headers.Contains("Authorization"));

            // Validate result
            Assert.NotNull(result);
        }
Exemple #7
0
        public async Task ResourceCreateByIdForWebsiteValidatePayload()
        {
            var mockResponse = new MockResponse((int)HttpStatusCode.OK);
            var content      = "{'location':'South Central US','tags':null,'properties':{'name':'mySite','state':'Running','hostNames':['csmr14v5efk0.antares-int.windows-int.net'],'webSpace':'csmrgqinwpwky-SouthCentralUSwebspace','selfLink':'https://antpreview1.api.admin-antares-int.windows-int.net:454/20130801/websystems/websites/web/subscriptions/abc123/webspaces/csmrgqinwpwky-SouthCentralUSwebspace/sites/csmr14v5efk0','repositorySiteName':'csmr14v5efk0','owner':null,'usageState':0,'enabled':true,'adminEnabled':true,'enabledHostNames':['csmr14v5efk0.antares-int.windows-int.net','csmr14v5efk0.scm.antares-int.windows-int.net'],'siteProperties':{'metadata':null,'properties':[],'appSettings':null},'availabilityState':0,'sslCertificates':[],'csrs':[],'cers':null,'siteMode':'Standard','hostNameSslStates':[{'name':'csmr14v5efk0.antares-int.windows-int.net','sslState':0,'ipBasedSslResult':null,'virtualIP':null,'thumbprint':null,'toUpdate':null,'toUpdateIpBasedSsl':null,'ipBasedSslState':0},{'name':'csmr14v5efk0.scm.antares-int.windows-int.net','sslState':0,'ipBasedSslResult':null,'virtualIP':null,'thumbprint':null,'toUpdate':null,'toUpdateIpBasedSsl':null,'ipBasedSslState':0}],'computeMode':1,'serverFarm':'DefaultServerFarm1','lastModifiedTimeUtc':'2014-02-21T00:49:30.477','storageRecoveryDefaultState':'Running','contentAvailabilityState':0,'runtimeAvailabilityState':0,'siteConfig':null,'deploymentId':'csmr14v5efk0','trafficManagerHostNames':[]}}".Replace("'", "\"");
            var header       = new HttpHeader("x-ms-request-id", "1");

            mockResponse.AddHeader(header);
            mockResponse.SetContent(content);

            var mockTransport = new MockTransport(mockResponse);
            var client        = GetResourceManagementClient(mockTransport);

            var raw = await client.Resources.StartCreateOrUpdateByIdAsync(
                "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite",
                "2014-01-04",
                new GenericResource
            {
                Location   = "South Central US",
                Properties = @"{
                            'name':'mySite',
	                        'siteMode': 'Standard',
                            'computeMode':'Dedicated'
                        }"
            }
                );

            var result = (await WaitForCompletionAsync(raw)).Value;

            // Validate result
            Assert.AreEqual("South Central US", result.Location);
        }
Exemple #8
0
        public async Task HasChangedValuesDontMatch()
        {
            var response = new MockResponse(200);

            string version1        = Guid.NewGuid().ToString();
            var    version1Setting = s_testSetting.Clone();

            version1Setting.ETag = new ETag(version1);

            string version2        = Guid.NewGuid().ToString();
            var    version2Setting = s_testSetting.Clone();

            version2Setting.ETag = new ETag(version2);

            response.SetContent(SerializationHelpers.Serialize(version2Setting, SerializeSetting));
            response.AddHeader(new HttpHeader("ETag", version2Setting.ETag.ToString()));

            var mockTransport           = new MockTransport(response);
            ConfigurationClient service = CreateTestService(mockTransport);

            bool hasChanged = await service.HasChangedAsync(version1Setting);

            MockRequest request = mockTransport.SingleRequest;

            AssertRequestCommon(request);
            Assert.AreEqual(RequestMethod.Head, request.Method);
            Assert.AreEqual($"https://contoso.appconfig.io/kv/test_key?label=test_label&api-version={s_version}", request.UriBuilder.ToString());
            Assert.IsTrue(response.Headers.TryGetValue("ETag", out string etag));
            Assert.AreEqual(version2, etag);
            Assert.IsTrue(hasChanged);
        }
        public void FailedTransaction()
        {
            var client = InstrumentClient(
                new ConfidentialLedgerClient(
                    new("https://client"),
                    new MockCredential(),
                    new ConfidentialLedgerClientOptions
            {
                Transport = new MockTransport(
                    req =>
                {
                    if (req.Uri.Path.Contains($"transactions/{transactionId}/status"))
                    {
                        var success = new MockResponse(500);
                        success.SetContent("success");
                        return(success);
                    }
                    var failed = new MockResponse(200);
                    failed.AddHeader("x-ms-ccf-transaction-id", transactionId);
                    failed.SetContent("failed");
                    return(failed);
                })
            }));

            var ex = Assert.ThrowsAsync <InvalidOperationException>(
                async() => await client.PostLedgerEntryAsync(RequestContent.Create(new { contents = "test" }), null, true, default));

            Assert.That(ex.Message, Does.Contain(transactionId));
        }
        public async Task StartBuildModelEncodesBlankSpaces()
        {
            var mockResponse = new MockResponse(202);

            mockResponse.AddHeader(new HttpHeader("operation-location", "host/operations/00000000000000000000000000000000?api-version=2021-07-30-preview"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var options       = new DocumentAnalysisClientOptions()
            {
                Transport = mockTransport
            };
            var client = CreateInstrumentedClient(options);

            var encodedUriString = "https://fakeuri.com/blank%20space";
            var decodedUriString = "https://fakeuri.com/blank space";

            await client.StartBuildModelAsync(new Uri(encodedUriString), DocumentBuildMode.Template);

            await client.StartBuildModelAsync(new Uri(decodedUriString), DocumentBuildMode.Template);

            Assert.AreEqual(2, mockTransport.Requests.Count);

            foreach (var request in mockTransport.Requests)
            {
                var requestBody = GetString(request.Content);

                Assert.True(requestBody.Contains(encodedUriString));
                Assert.False(requestBody.Contains(decodedUriString));
            }
        }
        public async Task AnalyzeOperationRecognizePiiEntitiesWithPiiOptions()
        {
            var mockResponse = new MockResponse(202);

            mockResponse.AddHeader(new HttpHeader("Operation-Location", "something/jobs/2a96a91f-7edf-4931-a880-3fdee1d56f15?api-version=myVersion"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var client        = CreateTestClient(mockTransport);

            var documents = new List <string>
            {
                "Elon Musk is the CEO of SpaceX and Tesla."
            };

            var options = new RecognizePiiEntitiesOptions();

            var actions = new RecognizePiiEntitiesAction(options);

            TextAnalyticsActions batchActions = new TextAnalyticsActions()
            {
                RecognizePiiEntitiesActions = new List <RecognizePiiEntitiesAction>()
                {
                    actions
                },
            };

            await client.StartAnalyzeActionsAsync(documents, batchActions);

            var contentString = GetString(mockTransport.Requests.Single().Content);

            ValidateRequestOptions(contentString);
            Assert.AreEqual(-1, contentString.IndexOf("domain"));
            Assert.AreEqual(-1, contentString.IndexOf("piiCategories"));
        }
Exemple #12
0
        internal CallingServerClient CreateMockCallingServerClient(int responseCode, object?responseContent = null, HttpHeader[]?httpHeaders = null)
        {
            var mockResponse = new MockResponse(responseCode);

            if (responseContent != null)
            {
                if (responseContent is string responseContentString)
                {
                    mockResponse.SetContent(responseContentString);
                }
                else if (responseContent is byte[] responseContentObjectArr)
                {
                    mockResponse.SetContent(responseContentObjectArr);
                }
            }

            if (httpHeaders != null)
            {
                for (int i = 0; i < httpHeaders.Length; i++)
                {
                    mockResponse.AddHeader(httpHeaders[i]);
                }
            }

            var callingServerClientOptions = new CallingServerClientOptions
            {
                Transport = new MockTransport(mockResponse)
            };

            return(new CallingServerClient(connectionString, callingServerClientOptions));
        }
        public async Task StartRecognizeContentFromUriEncodesBlankSpaces()
        {
            var mockResponse = new MockResponse(202);
            mockResponse.AddHeader(new HttpHeader(Constants.OperationLocationHeader, "host/layout/analyzeResults/00000000000000000000000000000000"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var options = new FormRecognizerClientOptions() { Transport = mockTransport };
            var client = CreateInstrumentedClient(options);

            var encodedUriString = "https://fakeuri.com/blank%20space";
            var decodedUriString = "https://fakeuri.com/blank space";

            await client.StartRecognizeContentFromUriAsync(new Uri(encodedUriString));
            await client.StartRecognizeContentFromUriAsync(new Uri(decodedUriString));

            Assert.AreEqual(2, mockTransport.Requests.Count);

            foreach (var request in mockTransport.Requests)
            {
                var requestBody = GetString(request.Content);

                Assert.True(requestBody.Contains(encodedUriString));
                Assert.False(requestBody.Contains(decodedUriString));
            }
        }
Exemple #14
0
        public async Task GettingErrorRequestProducesEvents()
        {
            var response = new MockResponse(500);
            response.SetContent(new byte[] { 6, 7, 8, 9, 0 });
            response.AddHeader(new HttpHeader("Custom-Response-Header", "Improved value"));

            MockTransport mockTransport = CreateMockTransport(response);

            var pipeline = new HttpPipeline(mockTransport, new[] { new LoggingPolicy(logContent: true, int.MaxValue, s_allowedHeaders, s_allowedQueryParameters, "Test-SDK") });
            string requestId = null;

            await SendRequestAsync(pipeline, request =>
            {
                request.Method = RequestMethod.Get;
                request.Uri.Reset(new Uri("https://contoso.a.io"));
                request.Headers.Add("Date", "3/26/2019");
                request.Headers.Add("Custom-Header", "Value");
                request.Content = RequestContent.Create(new byte[] { 1, 2, 3, 4, 5 });
                requestId = request.ClientRequestId;
            });

            EventWrittenEventArgs e = _listener.SingleEventById(ErrorResponseEvent);
            Assert.AreEqual(EventLevel.Warning, e.Level);
            Assert.AreEqual("ErrorResponse", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty<string>("requestId"));
            Assert.AreEqual(e.GetProperty<int>("status"), 500);
            StringAssert.Contains($"Custom-Response-Header:Improved value{Environment.NewLine}", e.GetProperty<string>("headers"));

            e = _listener.SingleEventById(ErrorResponseContentEvent);
            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("ErrorResponseContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty<string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 6, 7, 8, 9, 0 }, e.GetProperty<byte[]>("content"));
        }
Exemple #15
0
        public async Task DataFeedSourceSendsSecretDuringCreation(DataFeedSource dataSource, string secretPropertyName)
        {
            MockResponse createResponse = new MockResponse(201);

            createResponse.AddHeader(new HttpHeader("Location", $"https://fakeresource.cognitiveservices.azure.com/metricsadvisor/v1.0/dataFeeds/{FakeGuid}"));

            MockResponse getResponse = new MockResponse(200);

            getResponse.SetContent(DataFeedResponseContent);

            MockTransport mockTransport = new MockTransport(createResponse, getResponse);
            MetricsAdvisorAdministrationClient adminClient = CreateInstrumentedAdministrationClient(mockTransport);
            DataFeed dataFeed = new DataFeed()
            {
                Name              = "name",
                DataSource        = dataSource,
                Granularity       = new DataFeedGranularity(DataFeedGranularityType.Daily),
                Schema            = new DataFeedSchema(),
                IngestionSettings = new DataFeedIngestionSettings(DateTimeOffset.UtcNow)
            };

            dataFeed.Schema.MetricColumns.Add(new DataFeedMetric("metric"));

            await adminClient.CreateDataFeedAsync(dataFeed);

            MockRequest request = mockTransport.Requests.First();
            string      content = ReadContent(request);

            Assert.That(content, ContainsJsonString(secretPropertyName, "secret"));
        }
        public async Task StartTrainingEncodesBlankSpaces()
        {
            var mockResponse = new MockResponse(201);

            mockResponse.AddHeader(new HttpHeader("Location", "host/custom/models/00000000000000000000000000000000"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var options       = new FormRecognizerClientOptions()
            {
                Transport = mockTransport
            };
            var client = CreateInstrumentedClient(options);

            var encodedUriString = "https://fakeuri.com/blank%20space";
            var decodedUriString = "https://fakeuri.com/blank space";

            await client.StartTrainingAsync(new Uri(encodedUriString), useTrainingLabels : false);

            await client.StartTrainingAsync(new Uri(decodedUriString), useTrainingLabels : false);

            Assert.AreEqual(2, mockTransport.Requests.Count);

            foreach (var request in mockTransport.Requests)
            {
                var requestBody = GetString(request.Content);

                Assert.True(requestBody.Contains(encodedUriString));
                Assert.False(requestBody.Contains(decodedUriString));
            }
        }
        public async Task CreateHealthcareOperationSetsOperationId()
        {
            var mockResponse = new MockResponse(202);

            mockResponse.AddHeader(new HttpHeader("Operation-Location", "something/jobs/2a96a91f-7edf-4931-a880-3fdee1d56f15"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var client        = CreateTestClient(mockTransport);

            var documents = new List <TextDocumentInput>
            {
                new TextDocumentInput("134234", "Subject is taking 100mg of ibuprofen twice daily")
                {
                    Language = "en",
                },
                new TextDocumentInput("324232", "Can cause rapid or irregular heartbeat, delirium, panic, psychosis, and heart failure.")
                {
                    Language = "en",
                }
            };

            AnalyzeHealthcareEntitiesOperation operation = await client.StartAnalyzeHealthcareEntitiesAsync(documents);

            OperationContinuationToken continuationToken = OperationContinuationToken.Deserialize(operation.Id);

            Assert.IsFalse(continuationToken.ShowStats);
            Assert.AreEqual("2a96a91f-7edf-4931-a880-3fdee1d56f15", continuationToken.JobId);
            Assert.AreEqual(2, continuationToken.InputDocumentOrder.Count);
            Assert.AreEqual(0, continuationToken.InputDocumentOrder["134234"]);
            Assert.AreEqual(1, continuationToken.InputDocumentOrder["324232"]);
        }
        public async Task CreateAnalyzeOperationConvenienceSetsOperationId()
        {
            var mockResponse = new MockResponse(202);

            mockResponse.AddHeader(new HttpHeader("Operation-Location", "something/jobs/2a96a91f-7edf-4931-a880-3fdee1d56f15"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var client        = CreateTestClient(mockTransport);

            var documents = new List <string>
            {
                "Elon Musk is the CEO of SpaceX and Tesla.",
                "Microsoft was founded by Bill Gates and Paul Allen.",
                "My cat and my dog might need to see a veterinarian."
            };

            TextAnalyticsActions batchActions = new TextAnalyticsActions()
            {
                ExtractKeyPhrasesActions = new List <ExtractKeyPhrasesAction>()
                {
                    new ExtractKeyPhrasesAction()
                },
            };

            AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(documents, batchActions);

            OperationContinuationToken continuationToken = OperationContinuationToken.Deserialize(operation.Id);

            Assert.IsNull(continuationToken.ShowStats);
            Assert.AreEqual("2a96a91f-7edf-4931-a880-3fdee1d56f15", continuationToken.JobId);
            Assert.AreEqual(3, continuationToken.InputDocumentOrder.Count);
            Assert.AreEqual(0, continuationToken.InputDocumentOrder["0"]);
            Assert.AreEqual(1, continuationToken.InputDocumentOrder["1"]);
            Assert.AreEqual(2, continuationToken.InputDocumentOrder["2"]);
        }
Exemple #19
0
        public void RetryAfterWithConstantFallbackMs(
            [Values("retry-after-ms", "x-ms-retry-after-ms", null)] string headerName,
            [Values(
                 new int[] { 500, 5000, 1250, 2000 },
                 new int[] { 500, 500, 1250 },
                 new int[] { 500, 5000, 1250, 2000, 10000, 7500 })] int[] delayValues,
            [Values(500, 1000, 2000, 5000, null)] int?suggestedWaitInMs)
        {
            var      strategy   = new RetryAfterDelayStrategy();
            TimeSpan actual     = TimeSpan.Zero;
            TimeSpan?suggestion = suggestedWaitInMs.HasValue ? TimeSpan.FromMilliseconds(suggestedWaitInMs.Value) : null;
            int      expected   = 0;

            for (int i = 0; i < delayValues.Length; i++)
            {
                var response = new MockResponse(200);
                expected += GetExpected(headerName, delayValues[i], suggestedWaitInMs, (int)ConstantDelayStrategy.DefaultPollingInterval.TotalMilliseconds);
                if (headerName is not null)
                {
                    response.AddHeader(new HttpHeader(headerName, delayValues[i].ToString()));
                }
                actual += strategy.GetNextDelay(response, suggestion);
            }

            Assert.AreEqual(TimeSpan.FromMilliseconds(expected), actual);
        }
Exemple #20
0
        public async Task AnalyzeOperationKeyPhrasesFromRequestOptions()
        {
            var mockResponse = new MockResponse(202);

            mockResponse.AddHeader(new HttpHeader("Operation-Location", "something/jobs/2a96a91f-7edf-4931-a880-3fdee1d56f15"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var client        = CreateTestClient(mockTransport);

            var documents = new List <string>
            {
                "Elon Musk is the CEO of SpaceX and Tesla."
            };

            var options = new TextAnalyticsRequestOptions();

            var actions = new ExtractKeyPhrasesAction(options);

            TextAnalyticsActions batchActions = new()
            {
                ExtractKeyPhrasesActions = new List <ExtractKeyPhrasesAction>()
                {
                    actions
                },
            };

            await client.StartAnalyzeActionsAsync(documents, batchActions);

            var contentString = GetString(mockTransport.Requests.Single().Content);

            ValidateRequestOptions(contentString);
        }
Exemple #21
0
        public void RetryAfterWithExponentialFallbackS(
            [Values("Retry-After", null)] string headerName,
            [Values(
                 new int[] { 1, 2, 1, 2 },
                 new int[] { 1, 1, 2 },
                 new int[] { 1, 5, 2, 2, 10, 8 },
                 new int[] { 1, 5, 1, 2, 10, 8, 20, 20, 20, 20, 20, 20, 20 })] int[] delayValues,
            [Values(1, 2, 5, null)] int?suggestedWaitInMs)
        {
            var fallbackStrategy = new ExponentialDelayStrategy();

            TimeSpan[] defaultDelays = fallbackStrategy.GetType().GetField("_pollingSequence", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null) as TimeSpan[];
            var        strategy      = new RetryAfterDelayStrategy(fallbackStrategy);
            TimeSpan   actual        = TimeSpan.Zero;
            TimeSpan?  suggestion    = suggestedWaitInMs.HasValue ? TimeSpan.FromSeconds(suggestedWaitInMs.Value) : null;
            int        expected      = 0;

            for (int i = 0; i < delayValues.Length; i++)
            {
                var response = new MockResponse(200);
                //ignore suggestion for exponential
                expected += GetExpected(headerName, delayValues[i], null, (int)defaultDelays[Math.Min(i, defaultDelays.Length - 1)].TotalSeconds);
                if (headerName is not null)
                {
                    response.AddHeader(new HttpHeader(headerName, delayValues[i].ToString()));
                }
                actual += strategy.GetNextDelay(response, suggestion);
            }

            Assert.AreEqual(TimeSpan.FromSeconds(expected), actual);
        }
Exemple #22
0
        public async Task AnalyzeOperationAnalyzeSentimentWithAnalyzeSentimentOptions()
        {
            var mockResponse = new MockResponse(202);

            mockResponse.AddHeader(new HttpHeader("Operation-Location", "something/jobs/2a96a91f-7edf-4931-a880-3fdee1d56f15"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var client        = CreateTestClient(mockTransport);

            var documents = new List <string>
            {
                "Elon Musk is the CEO of SpaceX and Tesla."
            };

            var options = new AnalyzeSentimentOptions();

            var actions = new AnalyzeSentimentAction(options);

            TextAnalyticsActions batchActions = new TextAnalyticsActions()
            {
                AnalyzeSentimentActions = new List <AnalyzeSentimentAction>()
                {
                    actions
                },
            };

            await client.StartAnalyzeActionsAsync(documents, batchActions);

            var contentString = GetString(mockTransport.Requests.Single().Content);

            ValidateRequestOptions(contentString);
            Assert.AreEqual(-1, contentString.IndexOf("opinionMining"));
        }
Exemple #23
0
        public void AnalyzeOperationAnalyzeSentimentWithTwoActions()
        {
            var mockResponse = new MockResponse(202);

            mockResponse.AddHeader(new HttpHeader("Operation-Location", "something/jobs/2a96a91f-7edf-4931-a880-3fdee1d56f15"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var client        = CreateTestClient(mockTransport);

            var documents = new List <string>
            {
                "Elon Musk is the CEO of SpaceX and Tesla."
            };

            TextAnalyticsActions batchActions = new()
            {
                AnalyzeSentimentActions = new List <AnalyzeSentimentAction>()
                {
                    new AnalyzeSentimentAction(),
                    new AnalyzeSentimentAction()
                    {
                        ModelVersion = "InvalidVersion"
                    }
                },
            };

            ArgumentException ex = Assert.ThrowsAsync <ArgumentException>(async() => await client.StartAnalyzeActionsAsync(documents, batchActions));

            Assert.AreEqual("Multiple of the same action is not currently supported.", ex.Message);
        }
        public async Task StartRecognizeInvoicesSendsUserSpecifiedLocale(string locale)
        {
            var mockResponse = new MockResponse(202);

            mockResponse.AddHeader(new HttpHeader(Constants.OperationLocationHeader, "host/prebuilt/invoice/analyzeResults/00000000000000000000000000000000"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var options       = new FormRecognizerClientOptions()
            {
                Transport = mockTransport
            };
            var client = CreateInstrumentedClient(options);

            using var stream = FormRecognizerTestEnvironment.CreateStream(TestFile.InvoiceJpg);
            var recognizeOptions = new RecognizeInvoicesOptions {
                Locale = locale
            };
            await client.StartRecognizeInvoicesAsync(stream, recognizeOptions);

            var requestUriQuery = mockTransport.Requests.Single().Uri.Query;

            var localeQuery = "locale=";
            var index       = requestUriQuery.IndexOf(localeQuery);
            var length      = requestUriQuery.Length - (index + localeQuery.Length);

            Assert.AreEqual(locale, requestUriQuery.Substring(index + localeQuery.Length, length));
        }
Exemple #25
0
        public async Task UpdatesCachedValue()
        {
            string headerName   = "Sync-Token";
            string header1Value = "testSyncToken=A";
            string header2Value = "testSyncToken=B";

            var response1 = new MockResponse(200);

            response1.AddHeader(new HttpHeader(headerName, header1Value + ";sn=1"));

            var response2 = new MockResponse(200);

            response2.AddHeader(new HttpHeader(headerName, header2Value + ";sn=2"));

            MockTransport transport = CreateMockTransport(response1, response2, new MockResponse(200));
            var           policy    = new SyncTokenPolicy();

            await SendGetRequest(transport, policy);
            await SendGetRequest(transport, policy);
            await SendGetRequest(transport, policy);

            Assert.True(transport.Requests[1].Headers.TryGetValue(headerName, out string req1Value));
            Assert.True(transport.Requests[2].Headers.TryGetValue(headerName, out string req2Value));

            Assert.AreEqual(header1Value, req1Value);
            Assert.AreEqual(header2Value, req2Value);
        }
Exemple #26
0
        public async Task CachesHeaderValue()
        {
            string headerName   = "Sync-Token";
            string idTokenValue = "jtqGc1I4=MDoyOA==";
            string seqNoValue   = ";sn=28";
            string headerValue  = idTokenValue + seqNoValue;

            var syncTokenReponse = new MockResponse(200);

            syncTokenReponse.AddHeader(new HttpHeader(headerName, headerValue));

            MockTransport transport = CreateMockTransport(syncTokenReponse, new MockResponse(200));
            var           policy    = new SyncTokenPolicy();

            var response = await SendGetRequest(transport, policy);

            Assert.False(transport.Requests[0].Headers.TryGetValue(headerName, out _));
            Assert.True(response.Headers.TryGetValue(headerName, out string responseValue));
            Assert.AreEqual(headerValue, responseValue);

            await SendGetRequest(transport, policy);

            Assert.True(transport.Requests[1].Headers.TryGetValue(headerName, out string requestValue));
            Assert.AreEqual(idTokenValue, requestValue);
        }
Exemple #27
0
        public async Task ResourceGroupGetValidateMessage()
        {
            var mockResponse = new MockResponse((int)HttpStatusCode.OK);
            var content      = @"{
                    'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio',
                    'name': 'foo',
                    'location': 'WestEurope',
                    'properties': {
                        'provisioningState': 'Succeeded'
                     }
                }".Replace("'", "\"");
            var header       = new HttpHeader("x-ms-request-id", "1");

            mockResponse.AddHeader(header);
            mockResponse.SetContent(content);

            var mockTransport = new MockTransport(mockResponse);
            var client        = GetResourceManagementClient(mockTransport);

            var result = (await client.ResourceGroups.GetAsync("foo")).Value;

            // Validate headers
            var request = mockTransport.Requests[0];

            Assert.AreEqual(HttpMethod.Get.Method, request.Method.Method);
            Assert.IsTrue(request.Headers.Contains("Authorization"));

            // Validate result
            Assert.AreEqual("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.Id);
            Assert.AreEqual("WestEurope", result.Location);
            Assert.AreEqual("foo", result.Name);
            Assert.AreEqual("Succeeded", result.Properties.ProvisioningState);
            Assert.True(result.Properties.ProvisioningState == "Succeeded");
        }
Exemple #28
0
        public void RequestIdReturnsRequestIdHeaderValue()
        {
            var mockResponse = new MockResponse(200);

            mockResponse.AddHeader(new HttpHeader("x-ms-request-id", "abcde"));

            Assert.AreEqual("abcde", mockResponse.Headers.RequestId);
        }
Exemple #29
0
        public void ContentLengthParsedIfExist()
        {
            var mockResponse = new MockResponse(200);

            mockResponse.AddHeader(new HttpHeader("Content-Length", "100"));

            Assert.AreEqual(100, mockResponse.Headers.ContentLength);
        }
Exemple #30
0
        public void ContentTypeReturnsContentTypeHeaderValue()
        {
            var mockResponse = new MockResponse(200);

            mockResponse.AddHeader(new HttpHeader("Content-Type", "text/xml"));

            Assert.AreEqual("text/xml", mockResponse.Headers.ContentType);
        }