Exemplo n.º 1
0
 public override void setUp()
 {
     base.setUp();
     advertisedRefs = new List<Ref>();
     transport = new MockTransport(db, new URIish(), advertisedRefs);
     refUpdates = new List<RemoteRefUpdate>();
     connectionUpdateStatus = RemoteRefUpdate.UpdateStatus.OK;
 }
Exemplo n.º 2
0
        public async Task RespectsRetryAfterHeaderWithDate()
        {
            var responseClassifier = new MockResponseClassifier(retriableCodes: new [] { 500 });

            var(policy, gate) = CreateRetryPolicy(maxRetries: 3);
            var mockTransport = new MockTransport();
            var task          = SendGetRequest(mockTransport, policy, responseClassifier);

            MockResponse mockResponse = new MockResponse(500);

            // Use large value to avoid time based flakiness
            mockResponse.AddHeader(new HttpHeader("Retry-After", DateTimeOffset.Now.AddHours(5).ToString("R")));

            await mockTransport.RequestGate.Cycle(mockResponse);

            var retryDelay = await gate.Cycle();

            await mockTransport.RequestGate.Cycle(new MockResponse(501));

            var response = await task.TimeoutAfterDefault();

            Assert.Less(TimeSpan.FromHours(4), retryDelay);
            Assert.AreEqual(501, response.Status);
        }
Exemplo n.º 3
0
        public async Task RetryingEmitsEventSourceEvent()
        {
            var listener = new TestEventListener();

            listener.EnableEvents(HttpPipelineEventSource.Singleton, EventLevel.Informational);

            var(policy, gate) = CreateRetryPolicy(retriableCodes: new [] { 500 }, maxRetries: 2);
            var mockTransport = new MockTransport();
            var task          = SendRequest(mockTransport, policy);

            var request = await mockTransport.RequestGate.Cycle(new MockResponse(500));

            for (int i = 0; i < 2; i++)
            {
                await gate.Cycle();

                await mockTransport.RequestGate.Cycle(new MockResponse(500));
            }

            await task.TimeoutAfterDefault();

            AssertRetryEvent(listener, request, 1);
            AssertRetryEvent(listener, request, 2);
        }
Exemplo n.º 4
0
        public async Task UsesDefaultAuthScope(string host, string expectedScope)
        {
            var mockTransport = MockTransport.FromMessageCallback(_ => new MockResponse(200).SetContent("{}"));

            Mock <MockCredential> mock = new() { CallBase = true };

            string[] scopes = null;
            mock.Setup(m => m.GetTokenAsync(It.IsAny <TokenRequestContext>(), It.IsAny <CancellationToken>()))
            .Callback <TokenRequestContext, CancellationToken>((c, _) => scopes = c.Scopes)
            .CallBase();

            var options = new MetricsQueryClientOptions()
            {
                Transport = mockTransport
            };

            var client = host == null ?
                         new MetricsQueryClient(mock.Object, options) :
                         new MetricsQueryClient(new Uri(host), mock.Object, options);

            await client.QueryResourceAsync("", new string[] {});

            Assert.AreEqual(new[] { expectedScope }, scopes);
        }
        public async Task StartRecognizeContentSendsUserSpecifiedContentType()
        {
            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);

            using var stream = FormRecognizerTestEnvironment.CreateStream(TestFile.InvoiceLeTiff);
            var recognizeOptions = new RecognizeOptions {
                ContentType = FormContentType.Jpeg
            };
            await client.StartRecognizeContentAsync(stream, recognizeOptions);

            var request = mockTransport.Requests.Single();

            Assert.True(request.Headers.TryGetValue("Content-Type", out var contentType));
            Assert.AreEqual("image/jpeg", contentType);
        }
Exemplo n.º 6
0
        public async Task BlocksUnsafeRedirect()
        {
            using var testListener = new TestEventListener();
            testListener.EnableEvents(AzureCoreEventSource.Singleton, EventLevel.Verbose);

            var mockTransport = new MockTransport(_ =>
                                                  new MockResponse(300).AddHeader("Location", "http://new.host/"));

            var response = await SendRequestAsync(mockTransport, request =>
            {
                request.Uri.Reset(new Uri("https://example.com/"));
            }, RedirectPolicy.Shared);

            Assert.AreEqual(300, response.Status);
            Assert.AreEqual(1, mockTransport.Requests.Count);

            var e = testListener.SingleEventById(21);

            Assert.AreEqual(EventLevel.Warning, e.Level);
            Assert.AreEqual("RequestRedirectBlocked", e.EventName);
            Assert.AreEqual(mockTransport.Requests[0].ClientRequestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual("https://example.com/", e.GetProperty <string>("from"));
            Assert.AreEqual("http://new.host/", e.GetProperty <string>("to"));
        }
Exemplo n.º 7
0
        public async Task MsHeadersArePreferredOverRetryAfter(string headerName)
        {
            var responseClassifier = new MockResponseClassifier(retriableCodes: new [] { 500 });

            var(policy, gate) = CreateRetryPolicy(maxRetries: 3);
            var mockTransport = new MockTransport();
            var task          = SendGetRequest(mockTransport, policy, responseClassifier);

            MockResponse mockResponse = new MockResponse(500);

            mockResponse.AddHeader(new HttpHeader("Retry-After", "1"));
            mockResponse.AddHeader(new HttpHeader(headerName, "120000"));

            await mockTransport.RequestGate.Cycle(mockResponse);

            var retryDelay = await gate.Cycle();

            await mockTransport.RequestGate.Cycle(new MockResponse(501));

            var response = await task.TimeoutAfterDefault();

            Assert.AreEqual(TimeSpan.FromMilliseconds(120000), retryDelay);
            Assert.AreEqual(501, response.Status);
        }
Exemplo n.º 8
0
        public async Task ComponentNameAndVersionReadFromAssembly()
        {
            string userAgent = null;

            var mockTransport = new MockTransport(
                req => {
                Assert.True(req.TryGetHeader("User-Agent", out userAgent));
                return(new MockResponse(200));
            });

            var pipeline = HttpPipeline.Build(new TestClientOptions()
            {
                Transport = mockTransport
            }, new HttpPipelinePolicy[0]);

            var request = pipeline.CreateRequest();

            request.SetRequestLine(HttpPipelineMethod.Get, new Uri("https://contoso.a.io"));
            await pipeline.SendRequestAsync(request, CancellationToken.None);

            var assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            Assert.AreEqual(userAgent, $"azsdk-net-base-test/{assemblyVersion} ({RuntimeInformation.FrameworkDescription}; {RuntimeInformation.OSDescription})");
        }
        public async Task AnalyzeOperationRecognizeEntitiesWithDisableServiceLogs()
        {
            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 actions = new RecognizeEntitiesAction()
            {
                DisableServiceLogs = true
            };

            TextAnalyticsActions batchActions = new TextAnalyticsActions()
            {
                RecognizeEntitiesActions = new List <RecognizeEntitiesAction>()
                {
                    actions
                },
            };

            await client.StartAnalyzeActionsAsync(documents, batchActions);

            var    contentString = GetString(mockTransport.Requests.Single().Content);
            string logging       = contentString.Substring(contentString.IndexOf("loggingOptOut"), 19);

            var expectedContent = "loggingOptOut\":true";

            Assert.AreEqual(expectedContent, logging);
        }
Exemplo n.º 10
0
        public async Task AnalyzeOperationWithActionsError()
        {
            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(@"
                {
                    ""displayName"": ""AnalyzeOperationBatchWithErrorTest"",
                    ""jobId"": ""75d521bc-c2aa-4d8a-aabe-713e72d53a2d"",
                    ""lastUpdateDateTime"": ""2021-03-03T22:39:37Z"",
                    ""createdDateTime"": ""2021-03-03T22:39:36Z"",
                    ""expirationDateTime"": ""2021-03-04T22:39:36Z"",
                    ""status"": ""succeeded"",
                    ""errors"": [
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/entityRecognitionPiiTasks/0""
                      },
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/entityRecognitionTasks/0""
                      },
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/keyPhraseExtractionTasks/0""
                      },
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/entityLinkingTasks/0""
                      },
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/sentimentAnalysisTasks/0""
                      }
                    ],
                    ""tasks"": {
                      ""details"": {
                        ""name"": ""AnalyzeOperationBatchWithErrorTest"",
                        ""lastUpdateDateTime"": ""2021-03-03T22:39:37Z""
                      },
                      ""completed"": 0,
                      ""failed"": 5,
                      ""inProgress"": 0,
                      ""total"": 5,
                      ""entityRecognitionTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ],
                      ""entityRecognitionPiiTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ],
                      ""keyPhraseExtractionTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ],
                      ""entityLinkingTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ],
                      ""sentimentAnalysisTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ]
                    }
                }"));

            var mockResponse = new MockResponse(200);

            mockResponse.ContentStream = stream;

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

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

            TextAnalyticsActions batchActions = new TextAnalyticsActions()
            {
                ExtractKeyPhrasesActions = new List <ExtractKeyPhrasesAction>()
                {
                    new ExtractKeyPhrasesAction()
                },
                RecognizeEntitiesActions = new List <RecognizeEntitiesAction>()
                {
                    new RecognizeEntitiesAction()
                },
                RecognizePiiEntitiesActions = new List <RecognizePiiEntitiesAction>()
                {
                    new RecognizePiiEntitiesAction()
                },
                RecognizeLinkedEntitiesActions = new List <RecognizeLinkedEntitiesAction>()
                {
                    new RecognizeLinkedEntitiesAction()
                },
                AnalyzeSentimentActions = new List <AnalyzeSentimentAction>()
                {
                    new AnalyzeSentimentAction()
                },
                DisplayName = "AnalyzeOperationBatchWithErrorTest"
            };

            var operation = new AnalyzeActionsOperation("75d521bc-c2aa-4d8a-aabe-713e72d53a2d", client);
            await operation.UpdateStatusAsync();

            Assert.AreEqual(5, operation.ActionsFailed);
            Assert.AreEqual(0, operation.ActionsSucceeded);
            Assert.AreEqual(0, operation.ActionsInProgress);
            Assert.AreEqual(5, operation.ActionsTotal);

            //Take the first page
            AnalyzeActionsResult resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();

            RecognizeEntitiesActionResult       entitiesActionsResults         = resultCollection.RecognizeEntitiesResults.FirstOrDefault();
            ExtractKeyPhrasesActionResult       keyPhrasesActionsResults       = resultCollection.ExtractKeyPhrasesResults.FirstOrDefault();
            RecognizePiiEntitiesActionResult    piiActionsResults              = resultCollection.RecognizePiiEntitiesResults.FirstOrDefault();
            RecognizeLinkedEntitiesActionResult entityLinkingActionsResults    = resultCollection.RecognizeLinkedEntitiesResults.FirstOrDefault();
            AnalyzeSentimentActionResult        analyzeSentimentActionsResults = resultCollection.AnalyzeSentimentResults.FirstOrDefault();

            Assert.IsTrue(entitiesActionsResults.HasError);
            Assert.Throws <InvalidOperationException>(() => entitiesActionsResults.DocumentsResults.GetType());

            Assert.IsTrue(keyPhrasesActionsResults.HasError);
            Assert.Throws <InvalidOperationException>(() => keyPhrasesActionsResults.DocumentsResults.GetType());

            Assert.IsTrue(piiActionsResults.HasError);
            Assert.Throws <InvalidOperationException>(() => piiActionsResults.DocumentsResults.GetType());

            Assert.IsTrue(entityLinkingActionsResults.HasError);
            Assert.Throws <InvalidOperationException>(() => entityLinkingActionsResults.DocumentsResults.GetType());

            Assert.IsTrue(analyzeSentimentActionsResults.HasError);
            Assert.Throws <InvalidOperationException>(() => analyzeSentimentActionsResults.DocumentsResults.GetType());
        }
        public async Task SetsTraceParentExtension(bool inclTraceparent, bool inclTracestate)
        {
            var mockTransport = new MockTransport(new MockResponse(200));
            var options       = new EventGridPublisherClientOptions
            {
                Transport = mockTransport
            };
            EventGridPublisherClient client =
                new EventGridPublisherClient(
                    new Uri("http://localHost"),
                    new AzureKeyCredential("fakeKey"),
                    options);
            var activity = new Activity($"{nameof(EventGridPublisherClient)}.{nameof(EventGridPublisherClient.SendEvents)}");

            activity.SetW3CFormat();
            activity.Start();
            List <CloudEvent> eventsList = new List <CloudEvent>();

            for (int i = 0; i < 10; i++)
            {
                var cloudEvent =
                    new CloudEvent(
                        "record",
                        new Uri("http://localHost"),
                        Guid.NewGuid().ToString(),
                        DateTime.Now);

                if (inclTraceparent && inclTracestate && i % 2 == 0)
                {
                    cloudEvent.GetAttributes().Add("traceparent", "traceparentValue");
                }
                if (inclTracestate && i % 2 == 0)
                {
                    cloudEvent.GetAttributes().Add("tracestate", "param:value");
                }
                eventsList.Add(cloudEvent);
            }
            await client.SendCloudEventsAsync(eventsList);

            activity.Stop();
            List <CloudEvent>        cloudEvents = DeserializeRequest(mockTransport.SingleRequest);
            IEnumerator <CloudEvent> cloudEnum   = eventsList.GetEnumerator();

            foreach (CloudEvent cloudEvent in cloudEvents)
            {
                cloudEnum.MoveNext();
                IDictionary <string, object> cloudEventAttr = cloudEnum.Current.GetAttributes();
                if (cloudEventAttr.ContainsKey(TraceParentHeaderName) &&
                    cloudEventAttr.ContainsKey(TraceStateHeaderName))
                {
                    Assert.AreEqual(
                        cloudEventAttr[TraceParentHeaderName],
                        cloudEvent.GetAttributes()[TraceParentHeaderName]);

                    Assert.AreEqual(
                        cloudEventAttr[TraceStateHeaderName],
                        cloudEvent.GetAttributes()[TraceStateHeaderName]);
                }
                else if (cloudEventAttr.ContainsKey(TraceParentHeaderName))
                {
                    Assert.AreEqual(
                        cloudEventAttr[TraceParentHeaderName],
                        cloudEvent.GetAttributes()[TraceParentHeaderName]);
                }
                else if (cloudEventAttr.ContainsKey(TraceStateHeaderName))
                {
                    Assert.AreEqual(
                        cloudEventAttr[TraceStateHeaderName],
                        cloudEvent.GetAttributes()[TraceStateHeaderName]);
                }
                else
                {
                    Assert.AreEqual(
                        activity.Id,
                        cloudEvent.GetAttributes()[TraceParentHeaderName]);
                }
            }
        }
        public async Task RecognizeEntitiesResultsSorted_NoErrors()
        {
            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(@"
                {
                    ""documents"": [
                        {
                            ""id"": ""1"",
                            ""entities"": [
                                {
                                    ""name"": ""Microsoft"",
                                    ""matches"": [
                                        {
                                            ""text"": ""Microsoft"",
                                            ""offset"": 0,
                                            ""length"": 9,
                                            ""confidenceScore"": 0.26
                                        }
                                    ],
                                    ""language"": ""en"",
                                    ""id"": ""Microsoft"",
                                    ""url"": ""https://en.wikipedia.org/wiki/Microsoft"",
                                    ""dataSource"": ""Wikipedia""
                                }
                            ],
                            ""warnings"": []
                        },
                        {
                            ""id"": ""2"",
                            ""entities"": [
                                {
                                    ""name"": ""Microsoft"",
                                    ""matches"": [
                                        {
                                            ""text"": ""Microsoft"",
                                            ""offset"": 0,
                                            ""length"": 9,
                                            ""confidenceScore"": 0.26
                                        }
                                    ],
                                    ""language"": ""en"",
                                    ""id"": ""Microsoft"",
                                    ""url"": ""https://en.wikipedia.org/wiki/Microsoft"",
                                    ""dataSource"": ""Wikipedia""
                                }
                            ],
                            ""warnings"": []
                        }
                    ],
                    ""errors"": [],
                    ""modelVersion"": ""2020-02-01""
                }"));

            var mockResponse = new MockResponse(200);

            mockResponse.ContentStream = stream;

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

            var documents = new List <TextDocumentInput>()
            {
                new TextDocumentInput("1", "Microsoft was founded"),
                new TextDocumentInput("2", "Microsoft was founded"),
            };

            var response = await client.RecognizeEntitiesBatchAsync(documents, new TextAnalyticsRequestOptions());

            var resultCollection = response.Value;

            Assert.AreEqual("1", resultCollection[0].Id);
            Assert.AreEqual("2", resultCollection[1].Id);
        }
Exemplo n.º 13
0
        public void StartUnitializedTransportTest()
        {
            MockTransport transport = new MockTransport(mockUri);

            transport.Start();
        }
Exemplo n.º 14
0
        public async Task DeploymentTestsGetValidateMessage()
        {
            var mockResponse = new MockResponse((int)HttpStatusCode.OK);
            var content      = @"{
                    'resourceGroup': 'foo',
                    'name':'myrealease-3.14',
                    'properties':{
                        'provisioningState':'Succeeded',    
                        'timestamp':'2014-01-05T12:30:43.00Z',
                        'mode':'Incremental',
                        'correlationId':'12345',
		                'templateLink': {
                           'uri': 'http://wa/template.json',
                           'contentVersion': '1.0.0.0',
                           'contentHash': {
                              'algorithm': 'sha256',
                              'value': 'yyz7xhhshfasf'
                           }
                        },
                        'parametersLink': {
                           'uri': 'http://wa/parameters.json',
                           'contentVersion': '1.0.0.0',
                           'contentHash': {
                              'algorithm': 'sha256',
                              'value': 'yyz7xhhshfasf'
                           }
                        },
                        'parameters': {
                            'key' : {
                                'type':'string',           
                                'value':'user'
                            }
		                },
                        'outputs': {
                            'key' : {
                                'type':'string',           
                                'value':'user'
                            }
                        }        
                    },
                    'tags': {
                        'tagsTestKey': 'tagsTestValue'
                    }
                }".Replace("'", "\"");

            mockResponse.SetContent(content);

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

            var result = (await client.Deployments.GetAsync("foo", "bar")).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("myrealease-3.14", result.Name);
            Assert.AreEqual("Succeeded", result.Properties.ProvisioningState);
            Assert.AreEqual("12345", result.Properties.CorrelationId);
            Assert.AreEqual(new DateTimeOffset(2014, 1, 5, 12, 30, 43, new TimeSpan()), result.Properties.Timestamp);
            Assert.AreEqual(DeploymentMode.Incremental, result.Properties.Mode);
            Assert.AreEqual("http://wa/template.json", result.Properties.TemplateLink.Uri.ToString());
            Assert.AreEqual("1.0.0.0", result.Properties.TemplateLink.ContentVersion);
            Assert.IsTrue(JsonSerializer.Serialize(result.Properties.Parameters).Contains("\"type\":\"string\""));
            Assert.IsTrue(JsonSerializer.Serialize(result.Properties.Outputs).Contains("\"type\":\"string\""));
            Assert.NotNull(result.Tags);
            Assert.True(result.Tags.ContainsKey("tagsTestKey"));
            Assert.AreEqual("tagsTestValue", result.Tags["tagsTestKey"]);
        }
Exemplo n.º 15
0
        public async Task DeploymentTestsCreateValidateMessage()
        {
            var mockResponse = new MockResponse((int)HttpStatusCode.Created);
            var content      = @"{
                    'id': 'foo',
                    'name':'myrealease-3.14',
                    'properties':{
                        'provisioningState':'Succeeded',    
                        'timestamp':'2014-01-05T12:30:43.00Z',
                        'mode':'Incremental',
                        'template': { 'api-version' : '123' },
		                'templateLink': {
                           'uri': 'http://wa/template.json',
                           'contentVersion': '1.0.0.0',
                           'contentHash': {
                              'algorithm': 'sha256',
                              'value': 'yyz7xhhshfasf'
                           }
                        },
                        'parametersLink': {
                           'uri': 'http://wa/parameters.json',
                           'contentVersion': '1.0.0.0',
                           'contentHash': {
                              'algorithm': 'sha256',
                              'value': 'yyz7xhhshfasf'
                           }
                        },
                        'parameters': {
                            'key' : {
                                'type':'string',           
                                'value':'user'
                            }
		                },
                        'outputs': {
                            'key' : {
                                'type':'string',           
                                'value':'user'
                            }
                        }        
                    }
                }".Replace("'", "\"");

            mockResponse.SetContent(content);

            var dictionary = new Dictionary <string, object> {
                { "param1", "value1" },
                { "param2", true },
                { "param3", new Dictionary <string, object>()
                  {
                      { "param3_1", 123 },
                      { "param3_2", "value3_2" },
                  } }
            };
            var parameters = new Deployment
                             (
                new DeploymentProperties(DeploymentMode.Incremental)
            {
                Template     = "{\"api-version\": \"123\"}",
                TemplateLink = new TemplateLink("http://abc/def/template.json")
                {
                    ContentVersion = "1.0.0.0"
                },
                Parameters     = JsonSerializer.Serialize(dictionary),
                ParametersLink = new ParametersLink("http://abc/def/template.json")
                {
                    ContentVersion = "1.0.0.0"
                }
            }
                             );

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

            DeploymentsCreateOrUpdateOperation raw = await client.Deployments.StartCreateOrUpdateAsync("foo", "myrealease-3.14", parameters);

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

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

            Assert.IsTrue(request.Headers.Contains(new HttpHeader("Content-Type", "application/json")));
            Assert.AreEqual(HttpMethod.Put.Method, request.Method.Method);
            Assert.IsTrue(request.Headers.Contains("Authorization"));

            // Validate payload
            Stream stream = new MemoryStream();
            await request.Content.WriteToAsync(stream, default);

            stream.Position = 0;
            var resquestContent = new StreamReader(stream).ReadToEnd();
            var json            = JsonDocument.Parse(resquestContent).RootElement;

            Assert.AreEqual("Incremental", json.GetProperty("properties").GetProperty("mode").GetString());
            Assert.AreEqual("http://abc/def/template.json", json.GetProperty("properties").GetProperty("templateLink").GetProperty("uri").GetString());
            Assert.AreEqual("1.0.0.0", json.GetProperty("properties").GetProperty("templateLink").GetProperty("contentVersion").GetString());
            Assert.AreEqual("1.0.0.0", json.GetProperty("properties").GetProperty("parametersLink").GetProperty("contentVersion").GetString());
            Assert.AreEqual("value1", json.GetProperty("properties").GetProperty("parameters").GetProperty("param1").GetString());
            Assert.True(json.GetProperty("properties").GetProperty("parameters").GetProperty("param2").GetBoolean());
            Assert.AreEqual(123, json.GetProperty("properties").GetProperty("parameters").GetProperty("param3").GetProperty("param3_1").GetInt32());
            Assert.AreEqual("value3_2", json.GetProperty("properties").GetProperty("parameters").GetProperty("param3").GetProperty("param3_2").GetString());
            Assert.AreEqual("123", json.GetProperty("properties").GetProperty("template").GetProperty("api-version").GetString());

            // Validate result
            Assert.AreEqual("foo", result.Id);
            Assert.AreEqual("myrealease-3.14", result.Name);
            Assert.AreEqual("Succeeded", result.Properties.ProvisioningState);
            Assert.AreEqual(new DateTimeOffset(2014, 1, 5, 12, 30, 43, new TimeSpan()), result.Properties.Timestamp);
            Assert.AreEqual(DeploymentMode.Incremental, result.Properties.Mode);
            Assert.AreEqual("http://wa/template.json", result.Properties.TemplateLink.Uri);
            Assert.AreEqual("1.0.0.0", result.Properties.TemplateLink.ContentVersion);
            Assert.IsTrue(JsonSerializer.Serialize(result.Properties.Parameters).Contains("\"type\":\"string\""));
            Assert.IsTrue(JsonSerializer.Serialize(result.Properties.Outputs).Contains("\"type\":\"string\""));
        }
Exemplo n.º 16
0
        public async Task DeploymentTestsTemplateAsJsonString()
        {
            List <string> dividedCases = new List <string> {
                (@"{
                '$schema': 'http://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#',
                'contentVersion': '1.0.0.0',
                'parameters': {
                    'storageAccountName': {
		                'value': 'tianotest04'
	                }
                }
            }").Replace("'", "\""),
                (@"{
                'storageAccountName': {
		            'value': 'tianotest04'
	            }
            }").Replace("'", "\"")
            };

            foreach (var parameterString in dividedCases)
            {
                var mockResponse = new MockResponse((int)HttpStatusCode.Created);
                var responseBody = (@"{
                    'id': 'foo',
                    'name': 'test-release-3',
                    'properties': {
                        'parameters': {
                            'storageAccountName': {
				                'type': 'String',
				                'value': 'tianotest04'
			                }
		                },
		                'mode': 'Incremental',
		                'provisioningState': 'Succeeded',
		                'timestamp': '2016-07-12T17:36:39.2398177Z',
		                'duration': 'PT0.5966357S',
		                'correlationId': 'c0d728d5-5b97-41b9-b79a-abcd9eb5fe4a'
	                }
                }").Replace("'", "\"");
                mockResponse.SetContent(responseBody);

                var templateString = (@"{
                    '$schema': 'http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#',
                    'contentVersion': '1.0.0.0',
                    'parameters': {
                        'storageAccountName': {
		                    'type': 'string'
	                    }
                    },
                    'resources': [
                    ],
                    'outputs': {  }
                }").Replace("'", "\"");

                JsonElement jsonParameter = JsonSerializer.Deserialize <JsonElement>(parameterString);
                if (!jsonParameter.TryGetProperty("parameters", out JsonElement parameter))
                {
                    parameter = jsonParameter;
                }
                var mockTransport = new MockTransport(mockResponse);
                var client        = GetResourceManagementClient(mockTransport);

                var parameters = new Deployment
                                 (
                    new DeploymentProperties(DeploymentMode.Incremental)
                {
                    Template       = templateString,
                    ParametersJson = parameter
                }
                                 );

                var raw = await client.Deployments.StartCreateOrUpdateAsync("foo", "myrealease-3.14", parameters);

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

                // Validate headers
                var request = mockTransport.Requests[0];
                Assert.IsTrue(request.Headers.Contains(new HttpHeader("Content-Type", "application/json")));
                Assert.AreEqual(HttpMethod.Put.Method, request.Method.Method);
                Assert.IsTrue(request.Headers.Contains("Authorization"));

                // Validate payload
                Stream stream = new MemoryStream();
                await request.Content.WriteToAsync(stream, default);

                stream.Position = 0;
                var resquestContent = new StreamReader(stream).ReadToEnd();
                var json            = JsonDocument.Parse(resquestContent).RootElement;
                Assert.AreEqual("Incremental", json.GetProperty("properties").GetProperty("mode").GetString());
                Assert.AreEqual("tianotest04", json.GetProperty("properties").GetProperty("parameters").GetProperty("storageAccountName").GetProperty("value").GetString());
                Assert.AreEqual("1.0.0.0", json.GetProperty("properties").GetProperty("template").GetProperty("contentVersion").GetString());

                // Validate result
                Assert.AreEqual("foo", result.Id);
                Assert.AreEqual("test-release-3", result.Name);
                Assert.AreEqual("Succeeded", result.Properties.ProvisioningState);
                Assert.AreEqual(DeploymentMode.Incremental, result.Properties.Mode);
                Assert.IsTrue(JsonSerializer.Serialize(result.Properties.Parameters).Contains("\"value\":\"tianotest04\""));
            }
        }
Exemplo n.º 17
0
        public void AnalyzeOperationWithGenericError()
        {
            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(@"
                {
                    ""displayName"": ""AnalyzeOperationBatchWithErrorTest"",
                    ""jobId"": ""75d521bc-c2aa-4d8a-aabe-713e72d53a2d"",
                    ""lastUpdateDateTime"": ""2021-03-03T22:39:37Z"",
                    ""createdDateTime"": ""2021-03-03T22:39:36Z"",
                    ""expirationDateTime"": ""2021-03-04T22:39:36Z"",
                    ""status"": ""failed"",
                    ""errors"": [
                      {
                        ""code"": ""InternalServerError"",
                        ""message"": ""Some error""
                      }
                    ],
                    ""tasks"": {
                      ""details"": {
                        ""name"": ""AnalyzeOperationBatchWithErrorTest"",
                        ""lastUpdateDateTime"": ""2021-03-03T22:39:37Z""
                      },
                      ""completed"": 0,
                      ""failed"": 1,
                      ""inProgress"": 0,
                      ""total"": 1,
                      ""entityRecognitionTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ]
                    }
                }"));

            var mockResponse = new MockResponse(200);

            mockResponse.ContentStream = stream;

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

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

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

            var operation             = new AnalyzeActionsOperation("75d521bc-c2aa-4d8a-aabe-713e72d53a2d", client);
            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(async() => await operation.UpdateStatusAsync());

            Assert.AreEqual("InternalServerError", ex.ErrorCode);
            Assert.IsTrue(ex.Message.Contains("Some error"));
        }
Exemplo n.º 18
0
        public async Task SetsTraceParentExtension(bool inclTraceparent, bool inclTracestate)
        {
            var mockTransport = new MockTransport(new MockResponse(200));
            var options       = new EventGridPublisherClientOptions
            {
                Transport = mockTransport
            };
            EventGridPublisherClient client =
                new EventGridPublisherClient(
                    new Uri("http://localHost"),
                    new AzureKeyCredential("fakeKey"),
                    options);
            var activity = new Activity($"{nameof(EventGridPublisherClient)}.{nameof(EventGridPublisherClient.SendEvents)}");

            activity.SetW3CFormat();
            activity.Start();
            List <CloudEvent> inputEvents = new List <CloudEvent>();

            for (int i = 0; i < 10; i++)
            {
                var cloudEvent =
                    new CloudEvent
                {
                    Subject = "record",
                    Source  = new Uri("http://localHost"),
                    Id      = Guid.NewGuid().ToString(),
                    Time    = DateTime.Now,
                    Type    = "test"
                };

                if (inclTraceparent && inclTracestate && i % 2 == 0)
                {
                    cloudEvent.SetAttributeFromString("traceparent", "traceparentValue");
                }
                if (inclTracestate && i % 2 == 0)
                {
                    cloudEvent.SetAttributeFromString("tracestate", "param:value");
                }
                inputEvents.Add(cloudEvent);
            }
            await client.SendCloudNativeCloudEventsAsync(inputEvents);

            activity.Stop();
            List <CloudEvent>        endEvents = DeserializeRequest(mockTransport.SingleRequest);
            IEnumerator <CloudEvent> inputEnum = inputEvents.GetEnumerator();

            foreach (CloudEvent cloudEvent in endEvents)
            {
                inputEnum.MoveNext();
                var inputAttributes = inputEnum.Current.GetPopulatedAttributes().Select(pair => pair.Key.Name).ToList();
                if (inputAttributes.Contains(TraceParentHeaderName) &&
                    inputAttributes.Contains(TraceStateHeaderName))
                {
                    Assert.AreEqual(
                        inputEnum.Current[TraceParentHeaderName],
                        cloudEvent[TraceParentHeaderName]);

                    Assert.AreEqual(
                        inputEnum.Current[TraceStateHeaderName],
                        cloudEvent[TraceStateHeaderName]);
                }
                else if (inputAttributes.Contains(TraceParentHeaderName))
                {
                    Assert.AreEqual(
                        inputEnum.Current[TraceParentHeaderName],
                        cloudEvent[TraceParentHeaderName]);
                }
                else if (inputAttributes.Contains(TraceStateHeaderName))
                {
                    Assert.AreEqual(
                        inputEnum.Current[TraceStateHeaderName],
                        cloudEvent[TraceStateHeaderName]);
                }
                else
                {
                    Assert.AreEqual(
                        activity.Id,
                        cloudEvent[TraceParentHeaderName]);
                }
            }
        }
Exemplo n.º 19
0
        public async Task ResourceGetCreateOrUpdateDeleteAndExistsThrowExceptionWithoutApiVersion()
        {
            var mockResponse = new MockResponse((int)HttpStatusCode.OK);
            var content      = JsonDocument.Parse("{}").RootElement.ToString();

            mockResponse.SetContent(content);

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

            var    resourceName = "site3";
            var    resourceProviderNamespace  = "Microsoft.Web";
            string resourceProviderApiVersion = null;
            var    resourceType   = "sites";
            var    parentResourse = string.Empty;

            var resource = new GenericResource
            {
                Location   = "South Central US",
                Properties = @"{
                                'name':'site3',
	                            'siteMode': 'Standard',
                                'computeMode':'Dedicated'
                            }"
            };

            try
            {
                await client.Resources.GetAsync(
                    "foo",
                    resourceProviderNamespace,
                    parentResourse,
                    resourceType,
                    resourceName,
                    resourceProviderApiVersion);
            }
            catch (Exception ex)
            {
                Assert.NotNull(ex);
            }

            try
            {
                await client.Resources.CheckExistenceAsync(
                    "foo",
                    resourceProviderNamespace,
                    parentResourse,
                    resourceType,
                    resourceName,
                    resourceProviderApiVersion);
            }
            catch (Exception ex)
            {
                Assert.NotNull(ex);
            }
            try
            {
                await client.Resources.StartCreateOrUpdateAsync(
                    "foo",
                    resourceProviderNamespace,
                    parentResourse,
                    resourceType,
                    resourceName,
                    resourceProviderApiVersion,
                    resource);
            }
            catch (Exception ex)
            {
                Assert.NotNull(ex);
            }
            try
            {
                await client.Resources.StartDeleteAsync(
                    "foo",
                    resourceProviderNamespace,
                    parentResourse,
                    resourceType,
                    resourceName,
                    resourceProviderApiVersion);
            }
            catch (Exception ex)
            {
                Assert.NotNull(ex);
            }
        }
Exemplo n.º 20
0
        public async Task ListDeploymentOperationsWithRealPayloadReadsJsonInStatusMessage()
        {
            var mockResponse = new MockResponse((int)HttpStatusCode.OK);
            var content      = @"{
                  'value': [
                    {
                      'id': '/subscriptions/abcd1234/resourcegroups/foo/deployments/testdeploy/operations/334558C2218CAEB0',
                      'subscriptionId': 'abcd1234',
                      'resourceGroup': 'foo',
                      'deploymentName': 'testdeploy',
                      'operationId': '334558C2218CAEB0',
                      'properties': {
                        'provisioningState': 'Failed',
                        'timestamp': '2014-03-14T23:43:31.8688746Z',
                        'trackingId': '4f258f91-edd5-4d71-87c2-fac9a4b5cbbd',
                        'statusCode': 'Conflict',
                        'statusMessage': {
                          'Code': 'Conflict',
                          'Message': 'Website with given name ilygreTest4 already exists.',
                          'Target': null,
                          'Details': [
                            {
                              'Message': 'Website with given name ilygreTest4 already exists.'
                            },
                            {
                              'Code': 'Conflict'
                            },
                            {
                              'ErrorEntity': {
                                'Code': 'Conflict',
                                'Message': 'Website with given name ilygreTest4 already exists.',
                                'ExtendedCode': '54001',
                                'MessageTemplate': 'Website with given name {0} already exists.',
                                'Parameters': [
                                  'ilygreTest4'
                                ],
                                'InnerErrors': null
                              }
                            }
                          ],
                          'Innererror': null
                        },
                        'targetResource': {
                          'id':
                '/subscriptions/abcd1234/resourcegroups/foo/providers/Microsoft.Web/Sites/ilygreTest4',
                          'subscriptionId': 'abcd1234',
                          'resourceGroup': 'foo',
                          'resourceType': 'Microsoft.Web/Sites',
                          'resourceName': 'ilygreTest4'
                        }
                      }
                    },
                    {
                      'id':
                '/subscriptions/abcd1234/resourcegroups/foo/deployments/testdeploy/operations/6B9A5A38C94E6F14',
                      'subscriptionId': 'abcd1234',
                      'resourceGroup': 'foo',
                      'deploymentName': 'testdeploy',
                      'operationId': '6B9A5A38C94E6F14',
                      'properties': {
                        'provisioningState': 'Succeeded',
                        'timestamp': '2014-03-14T23:43:25.2101422Z',
                        'trackingId': '2ff7a8ad-abf3-47f6-8ce0-e4aae8c26065',
                        'statusCode': 'OK',
                        'statusMessage': null,
                        'targetResource': {
                          'id':
                '/subscriptions/abcd1234/resourcegroups/foo/providers/Microsoft.Web/serverFarms/ilygreTest4Host',
                          'subscriptionId': 'abcd1234',
                          'resourceGroup': 'foo',
                          'resourceType': 'Microsoft.Web/serverFarms',
                          'resourceName': 'ilygreTest4Host'
                        }
                      }
                    }
                  ]
                }".Replace("'", "\"");

            mockResponse.SetContent(content);

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

            var result = await client.Deployment.ListAsync("foo", "bar", null).ToEnumerableAsync();

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

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

            Assert.True(((Dictionary <string, object>)result.First().Properties.StatusMessage).Count != 0);
        }
        public async Task AnalyzeOperationWithActionsError()
        {
            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(@"
                {
                    ""displayName"": ""AnalyzeOperationBatchWithErrorTest"",
                    ""jobId"": ""75d521bc-c2aa-4d8a-aabe-713e72d53a2d"",
                    ""lastUpdateDateTime"": ""2021-03-03T22:39:37Z"",
                    ""createdDateTime"": ""2021-03-03T22:39:36Z"",
                    ""expirationDateTime"": ""2021-03-04T22:39:36Z"",
                    ""status"": ""succeeded"",
                    ""errors"": [
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/entityRecognitionPiiTasks/0""
                      },
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/entityRecognitionTasks/0""
                      },
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/keyPhraseExtractionTasks/0""
                      },
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/entityLinkingTasks/0""
                      },
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/sentimentAnalysisTasks/0""
                      },
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/extractiveSummarizationTasks/0""
                      },
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/customEntityRecognitionTasks/0""
                      },
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/customSingleClassificationTasks/0""
                      },
                      {
                        ""code"": ""InvalidRequest"",
                        ""message"": ""Some error"",
                        ""target"": ""#/tasks/customMultiClassificationTasks/0""
                      }
                    ],
                    ""tasks"": {
                      ""details"": {
                        ""name"": ""AnalyzeOperationBatchWithErrorTest"",
                        ""lastUpdateDateTime"": ""2021-03-03T22:39:37Z""
                      },
                      ""completed"": 0,
                      ""failed"": 9,
                      ""inProgress"": 0,
                      ""total"": 9,
                      ""entityRecognitionTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ],
                      ""entityRecognitionPiiTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ],
                      ""keyPhraseExtractionTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ],
                      ""entityLinkingTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ],
                      ""sentimentAnalysisTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ],
                      ""extractiveSummarizationTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ],
                     ""customEntityRecognitionTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ],
                     ""customSingleClassificationTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ],
                      ""customMultiClassificationTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ]
                    }
                }"));

            var mockResponse = new MockResponse(200);

            mockResponse.ContentStream = stream;

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

            AnalyzeActionsOperation operation = CreateOperation(client);
            await operation.UpdateStatusAsync();

            Assert.AreEqual(9, operation.ActionsFailed);
            Assert.AreEqual(0, operation.ActionsSucceeded);
            Assert.AreEqual(0, operation.ActionsInProgress);
            Assert.AreEqual(9, operation.ActionsTotal);

            //Take the first page
            AnalyzeActionsResult resultCollection = operation.Value.ToEnumerableAsync().Result.FirstOrDefault();

            RecognizeEntitiesActionResult       entitiesActionsResults               = resultCollection.RecognizeEntitiesResults.FirstOrDefault();
            ExtractKeyPhrasesActionResult       keyPhrasesActionsResults             = resultCollection.ExtractKeyPhrasesResults.FirstOrDefault();
            RecognizePiiEntitiesActionResult    piiActionsResults                    = resultCollection.RecognizePiiEntitiesResults.FirstOrDefault();
            RecognizeLinkedEntitiesActionResult entityLinkingActionsResults          = resultCollection.RecognizeLinkedEntitiesResults.FirstOrDefault();
            AnalyzeSentimentActionResult        analyzeSentimentActionsResults       = resultCollection.AnalyzeSentimentResults.FirstOrDefault();
            ExtractSummaryActionResult          extractSummaryActionsResults         = resultCollection.ExtractSummaryResults.FirstOrDefault();
            RecognizeCustomEntitiesActionResult recognizeCustomEntitiesActionResults = resultCollection.RecognizeCustomEntitiesResults.FirstOrDefault();
            SingleCategoryClassifyActionResult  singleCategoryClassifyActionResult   = resultCollection.SingleCategoryClassifyResults.FirstOrDefault();
            MultiCategoryClassifyActionResult   multiCategoryClassifyActionResult    = resultCollection.MultiCategoryClassifyResults.FirstOrDefault();

            Assert.IsTrue(entitiesActionsResults.HasError);
            Assert.Throws <InvalidOperationException>(() => entitiesActionsResults.DocumentsResults.GetType());

            Assert.IsTrue(keyPhrasesActionsResults.HasError);
            Assert.Throws <InvalidOperationException>(() => keyPhrasesActionsResults.DocumentsResults.GetType());

            Assert.IsTrue(piiActionsResults.HasError);
            Assert.Throws <InvalidOperationException>(() => piiActionsResults.DocumentsResults.GetType());

            Assert.IsTrue(entityLinkingActionsResults.HasError);
            Assert.Throws <InvalidOperationException>(() => entityLinkingActionsResults.DocumentsResults.GetType());

            Assert.IsTrue(analyzeSentimentActionsResults.HasError);
            Assert.Throws <InvalidOperationException>(() => analyzeSentimentActionsResults.DocumentsResults.GetType());

            Assert.IsTrue(extractSummaryActionsResults.HasError);
            Assert.Throws <InvalidOperationException>(() => extractSummaryActionsResults.DocumentsResults.GetType());

            Assert.IsTrue(recognizeCustomEntitiesActionResults.HasError);
            Assert.Throws <InvalidOperationException>(() => recognizeCustomEntitiesActionResults.DocumentsResults.GetType());

            Assert.IsTrue(singleCategoryClassifyActionResult.HasError);
            Assert.Throws <InvalidOperationException>(() => singleCategoryClassifyActionResult.DocumentsResults.GetType());

            Assert.IsTrue(multiCategoryClassifyActionResult.HasError);
            Assert.Throws <InvalidOperationException>(() => multiCategoryClassifyActionResult.DocumentsResults.GetType());
        }
Exemplo n.º 22
0
        public async Task DeploymentTestsValidateCheckPayload()
        {
            var mockResponse = new MockResponse((int)HttpStatusCode.BadRequest);
            var content      = @"{
                      'error': {
                        'code': 'InvalidTemplate',
                        'message': 'Deployment template validation failed.'
                      }
                    }".Replace("'", "\"");

            mockResponse.SetContent(content);

            var dictionary = new Dictionary <string, object> {
                { "param1", "value1" },
                { "param2", true },
                { "param3", new Dictionary <string, object>()
                  {
                      { "param3_1", 123 },
                      { "param3_2", "value3_2" },
                  } }
            };
            var parameters = new Deployment
                             (
                new DeploymentProperties(DeploymentMode.Incremental)
            {
                TemplateLink = new TemplateLink("http://abc/def/template.json")
                {
                    ContentVersion = "1.0.0.0",
                },
                Parameters = JsonSerializer.Serialize(dictionary)
            }
                             );

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

            try
            {
                var raw = await client.Deployments.StartValidateAsync("foo", "bar", parameters);

                var result = (await WaitForCompletionAsync(raw)).Value;
            }
            catch (RequestFailedException)
            {
                var    requestEX = mockTransport.Requests[0];
                Stream stream    = new MemoryStream();
                await requestEX.Content.WriteToAsync(stream, default);

                stream.Position = 0;
                var resquestContent = new StreamReader(stream).ReadToEnd();
                var json            = JsonDocument.Parse(resquestContent).RootElement;
                // Validate payload
                Assert.AreEqual("Incremental", json.GetProperty("properties").GetProperty("mode").GetString());
                Assert.AreEqual("http://abc/def/template.json", json.GetProperty("properties").GetProperty("templateLink").GetProperty("uri").GetString());
                Assert.AreEqual("1.0.0.0", json.GetProperty("properties").GetProperty("templateLink").GetProperty("contentVersion").GetString());
                Assert.AreEqual("value1", json.GetProperty("properties").GetProperty("parameters").GetProperty("param1").GetString());
                Assert.IsTrue(json.GetProperty("properties").GetProperty("parameters").GetProperty("param2").GetBoolean());
                Assert.AreEqual(123, json.GetProperty("properties").GetProperty("parameters").GetProperty("param3").GetProperty("param3_1").GetInt32());
                Assert.AreEqual("value3_2", json.GetProperty("properties").GetProperty("parameters").GetProperty("param3").GetProperty("param3_2").GetString());
            }

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

            Assert.IsTrue(request.Headers.Contains(new HttpHeader("Content-Type", "application/json")));
            Assert.AreEqual(HttpMethod.Post.Method, request.Method.Method);
            Assert.IsTrue(request.Headers.Contains("Authorization"));
        }
        public void CreateIfNotExistsDoesNotThrowWhenClientConstructedWithUriContainingTableName(TableServiceClient tableClient, MockTransport transport)
        {
            var client = InstrumentClient(tableClient);

            var ex = Assert.ThrowsAsync <RequestFailedException>(async() => await client.CreateTableIfNotExistsAsync(TableName));

            Assert.That(ex.Message, Does.Contain("The configured endpoint Uri appears to contain the table name"));

            ex = Assert.ThrowsAsync <RequestFailedException>(async() => await client.DeleteTableAsync(TableName));

            Assert.That(ex.Message, Does.Contain("The configured endpoint Uri appears to contain the table name"));

            ex = Assert.ThrowsAsync <RequestFailedException>(async() => await client.QueryAsync().ToEnumerableAsync());

            Assert.That(ex.Message, Does.Contain("The configured endpoint Uri appears to contain the table name"));

            ex = Assert.ThrowsAsync <RequestFailedException>(async() => await client.CreateTableAsync(TableName));

            Assert.That(ex.Message, Does.Contain("The configured endpoint Uri appears to contain the table name"));
        }
Exemplo n.º 24
0
        public async Task DeploymentTestsListValidateMessage()
        {
            var mockResponse = new MockResponse((int)HttpStatusCode.OK);
            var content      = @"{ 
                    'value' : [
                        {
                        'resourceGroup': 'foo',
                        'name':'myrealease-3.14',
                        'properties':{
                            'provisioningState':'Succeeded',    
                            'timestamp':'2014-01-05T12:30:43.00Z',
                            'mode':'Incremental',
		                    'templateLink': {
                               'uri': 'http://wa/template.json',
                               'contentVersion': '1.0.0.0',
                               'contentHash': {
                                  'algorithm': 'sha256',
                                  'value': 'yyz7xhhshfasf'
                               }
                            },
                            'parametersLink': {
                               'uri': 'http://wa/parameters.json',
                               'contentVersion': '1.0.0.0',
                               'contentHash': {
                                  'algorithm': 'sha256',
                                  'value': 'yyz7xhhshfasf'
                               }
                            },
                            'parameters': {
                                'key' : {
                                    'type':'string',           
                                    'value':'user'
                                }
		                    },
                            'outputs': {
                                'key' : {
                                    'type':'string',           
                                    'value':'user'
                                }
                            }     
                          }   
                        },
                        {
                        'resourceGroup': 'bar',
                        'name':'myrealease-3.14',
                        'properties':{
                            'provisioningState':'Succeeded',    
                            'timestamp':'2014-01-05T12:30:43.00Z',
                            'mode':'Incremental',
		                    'templateLink': {
                               'uri': 'http://wa/template.json',
                               'contentVersion': '1.0.0.0',
                               'contentHash': {
                                  'algorithm': 'sha256',
                                  'value': 'yyz7xhhshfasf'
                               }
                            },
                            'parametersLink': {
                               'uri': 'http://wa/parameters.json',
                               'contentVersion': '1.0.0.0',
                               'contentHash': {
                                  'algorithm': 'sha256',
                                  'value': 'yyz7xhhshfasf'
                               }
                            },
                            'parameters': {
                                'key' : {
                                    'type':'string',           
                                    'value':'user'
                                }
		                    },
                            'outputs': {
                                'key' : {
                                    'type':'string',           
                                    'value':'user'
                                }
                            }        
                        }
                      }
                    ]
                }".Replace("'", "\"");

            mockResponse.SetContent(content);

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

            var result = await client.Deployments.ListByResourceGroupAsync("foo", "provisioningState eq 'Succeeded'", 10).ToEnumerableAsync();

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

            Assert.AreEqual(HttpMethod.Get.Method, request.Method.Method);
            Assert.IsTrue(request.Headers.Contains("Authorization"));
            Assert.IsTrue(request.Uri.ToString().Contains("$top=10"));
            Assert.IsTrue(request.Uri.ToString().Contains("$filter=provisioningState%20eq%20%27Succeeded%27"));

            // Validate result
            Assert.AreEqual("myrealease-3.14", result.First().Name);
            Assert.AreEqual("Succeeded", result.First().Properties.ProvisioningState);
            Assert.AreEqual(new DateTimeOffset(2014, 1, 5, 12, 30, 43, new TimeSpan()), result.First().Properties.Timestamp);
            Assert.AreEqual(DeploymentMode.Incremental, result.First().Properties.Mode);
            Assert.AreEqual("http://wa/template.json", result.First().Properties.TemplateLink.Uri.ToString());
            Assert.AreEqual("1.0.0.0", result.First().Properties.TemplateLink.ContentVersion);
            Assert.IsTrue(JsonSerializer.Serialize(result.First().Properties.Parameters).Contains("\"type\":\"string\""));
            Assert.IsTrue(JsonSerializer.Serialize(result.First().Properties.Outputs).Contains("\"type\":\"string\""));
        }
        public async Task GetBatch()
        {
            var response1 = new MockResponse(200);

            response1.SetContent(SerializationHelpers.Serialize(new []
            {
                CreateSetting(0),
                CreateSetting(1),
            }, SerializeBatch));
            response1.AddHeader(new HttpHeader("Link", $"</kv?after=5>;rel=\"next\""));

            var response2 = new MockResponse(200);

            response2.SetContent(SerializationHelpers.Serialize(new []
            {
                CreateSetting(2),
                CreateSetting(3),
                CreateSetting(4),
            }, SerializeBatch));

            var mockTransport           = new MockTransport(response1, response2);
            ConfigurationClient service = CreateTestService(mockTransport);

            var query    = new SettingSelector();
            int keyIndex = 0;

            while (true)
            {
                using (Response <SettingBatch> response = await service.GetBatchAsync(query, CancellationToken.None))
                {
                    SettingBatch batch = response.Value;
                    for (int i = 0; i < batch.Count; i++)
                    {
                        ConfigurationSetting value = batch[i];
                        Assert.AreEqual("key" + keyIndex, value.Key);
                        keyIndex++;
                    }

                    var nextBatch = batch.NextBatch;

                    if (nextBatch == null)
                    {
                        break;
                    }

                    query = nextBatch;
                }
            }

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

            MockRequest request1 = mockTransport.Requests[0];

            Assert.AreEqual(HttpPipelineMethod.Get, request1.Method);
            Assert.AreEqual("https://contoso.azconfig.io/kv/?key=*&label=*", request1.UriBuilder.ToString());
            AssertRequestCommon(request1);

            MockRequest request2 = mockTransport.Requests[1];

            Assert.AreEqual(HttpPipelineMethod.Get, request2.Method);
            Assert.AreEqual("https://contoso.azconfig.io/kv/?key=*&label=*&after=5", request2.UriBuilder.ToString());
            AssertRequestCommon(request1);
        }
        public void TestFailoverTransportConnectionControlHandling()
        {
            Uri    uri              = new Uri("failover:(mock://localhost:61613)?transport.randomize=false");
            string reconnectTo      = "mock://localhost:61616?transport.name=Reconnected";
            string connectedBrokers = "mock://localhost:61617?transport.name=Broker1," +
                                      "mock://localhost:61618?transport.name=Broker2";
            FailoverTransportFactory factory = new FailoverTransportFactory();

            using (ITransport transport = factory.CreateTransport(uri))
            {
                Assert.IsNotNull(transport);
                transport.Command   = OnCommand;
                transport.Exception = OnException;

                FailoverTransport failover = transport.Narrow(typeof(FailoverTransport)) as FailoverTransport;
                Assert.IsNotNull(failover);
                Assert.IsFalse(failover.Randomize);

                failover.Resumed = OnResumed;

                const int MAX_ATTEMPTS = 50;

                transport.Start();

                for (int i = 0; i < MAX_ATTEMPTS; ++i)
                {
                    if (failover.IsConnected)
                    {
                        break;
                    }

                    Thread.Sleep(100);
                }

                Assert.IsTrue(failover.IsConnected);

                // Ensure the current mock transport has the correct outgoing command handler
                MockTransport mock = transport.Narrow(typeof(MockTransport)) as MockTransport;
                Assert.IsNotNull(mock);
                Assert.AreEqual(61613, mock.RemoteAddress.Port);
                VerifyCommandHandlerSetting(transport, mock);
                mock.OutgoingCommand = OnOutgoingCommand;

                mock.InjectCommand(new ConnectionControl()
                {
                    FaultTolerant    = true,
                    ReconnectTo      = reconnectTo,
                    ConnectedBrokers = connectedBrokers
                });

                // Give a bit of time for the Command to actually be processed.
                Thread.Sleep(2000);

                failover.Remove(true, "mock://localhost:61613");

                mock = null;

                for (int i = 0; i < MAX_ATTEMPTS; ++i)
                {
                    mock = transport.Narrow(typeof(MockTransport)) as MockTransport;
                    if (mock != null)
                    {
                        break;
                    }

                    Thread.Sleep(100);
                }

                Assert.IsNotNull(mock, "Error reconnecting to failover broker.");
                Assert.AreEqual(61616, mock.RemoteAddress.Port);
                Assert.AreEqual("Reconnected", mock.Name);
            }
        }
        public async Task RecognizeEntitiesResultsSorted_WithErrors()
        {
            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(@"
                {
                    ""kind"": ""EntityRecognitionResults"",
                    ""results"": {
                        ""documents"": [
                            {
                                ""id"": ""2"",
                                ""entities"": [
                                    {
                                        ""name"": ""Microsoft"",
                                        ""matches"": [
                                            {
                                                ""text"": ""Microsoft"",
                                                ""offset"": 0,
                                                ""length"": 9,
                                                ""confidenceScore"": 0.26
                                                }
                                        ],
                                        ""language"": ""en"",
                                        ""id"": ""Microsoft"",
                                        ""url"": ""https://en.wikipedia.org/wiki/Microsoft"",
                                        ""dataSource"": ""Wikipedia""
                                    }
                                ],
                                ""warnings"": []
                            },
                            {
                                ""id"": ""3"",
                                ""entities"": [
                                    {
                                        ""name"": ""Microsoft"",
                                        ""matches"": [
                                            {
                                                ""text"": ""Microsoft"",
                                                ""offset"": 0,
                                                ""length"": 9,
                                                ""confidenceScore"": 0.26
                                            }
                                        ],
                                        ""language"": ""en"",
                                        ""id"": ""Microsoft"",
                                        ""url"": ""https://en.wikipedia.org/wiki/Microsoft"",
                                        ""dataSource"": ""Wikipedia""
                                    }
                                ],
                                ""warnings"": []
                            }
                        ],
                        ""errors"": [
                            {
                                ""id"": ""4"",
                                ""error"": {
                                    ""code"": ""InvalidArgument"",
                                    ""message"": ""Invalid document in request."",
                                    ""innererror"": {
                                        ""code"": ""InvalidDocument"",
                                        ""message"": ""Document text is empty.""
                                    }
                                }
                            },
                            {
                                ""id"": ""5"",
                                ""error"": {
                                    ""code"": ""InvalidArgument"",
                                    ""message"": ""Invalid document in request."",
                                    ""innererror"": {
                                        ""code"": ""InvalidDocument"",
                                        ""message"": ""Document text is empty.""
                                    }
                                }
                            }
                        ],
                        ""modelVersion"": ""2020-02-01""
                    }
                }"));

            var mockResponse = new MockResponse(200);

            mockResponse.ContentStream = stream;

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

            var documents = new List <TextDocumentInput>()
            {
                new TextDocumentInput("4", "TextDocument1"),
                new TextDocumentInput("5", "TextDocument2"),
                new TextDocumentInput("2", "TextDocument3"),
                new TextDocumentInput("3", "TextDocument4"),
            };

            var response = await client.RecognizeEntitiesBatchAsync(documents, new TextAnalyticsRequestOptions());

            var resultCollection = response.Value;

            Assert.AreEqual("4", resultCollection[0].Id);
            Assert.AreEqual("5", resultCollection[1].Id);
            Assert.AreEqual("2", resultCollection[2].Id);
            Assert.AreEqual("3", resultCollection[3].Id);
        }
Exemplo n.º 28
0
        public async Task SendingRequestProducesEvents()
        {
            var response = new MockResponse(500);

            response.SetContent(new byte[] { 6, 7, 8, 9, 0 });
            response.AddHeader(new HttpHeader("Custom-Response-Header", "Improved value"));

            var mockTransport = new MockTransport(response);

            var    pipeline = new HttpPipeline(mockTransport, new [] { LoggingPolicy.Shared });
            string requestId;

            using (HttpPipelineRequest request = pipeline.CreateRequest())
            {
                request.SetRequestLine(HttpPipelineMethod.Get, new Uri("https://contoso.a.io"));
                request.AddHeader("Date", "3/26/2019");
                request.AddHeader("Custom-Header", "Value");
                request.Content = HttpPipelineRequestContent.Create(new byte[] { 1, 2, 3, 4, 5 });
                requestId       = request.RequestId;

                await pipeline.SendRequestAsync(request, CancellationToken.None);
            }

            var e = _listener.SingleEventById(RequestEvent);

            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("Request", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            Assert.AreEqual("https://contoso.a.io/", e.GetProperty <string>("uri"));
            Assert.AreEqual("GET", e.GetProperty <string>("method"));
            StringAssert.Contains($"Date:3/26/2019{Environment.NewLine}", e.GetProperty <string>("headers"));
            StringAssert.Contains($"Custom-Header:Value{Environment.NewLine}", e.GetProperty <string>("headers"));

            e = _listener.SingleEventById(RequestContentEvent);
            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("RequestContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4, 5 }, e.GetProperty <byte[]>("content"));

            e = _listener.SingleEventById(ResponseEvent);
            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("Response", 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(ResponseContentEvent);
            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("ResponseContent", e.EventName);
            Assert.AreEqual(requestId, e.GetProperty <string>("requestId"));
            CollectionAssert.AreEqual(new byte[] { 6, 7, 8, 9, 0 }, e.GetProperty <byte[]>("content"));

            e = _listener.SingleEventById(ErrorResponseEvent);
            Assert.AreEqual(EventLevel.Error, 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"));
        }
Exemplo n.º 29
0
        public async Task SetsTraceParentExtension(bool inclTraceparent, bool inclTracestate)
        {
            var mockTransport = new MockTransport(new MockResponse(200));
            var options       = new EventGridPublisherClientOptions
            {
                Transport = mockTransport
            };
            EventGridPublisherClient client =
                new EventGridPublisherClient(
                    new Uri("http://localHost"),
                    new AzureKeyCredential("fakeKey"),
                    options);
            var activity = new Activity($"{nameof(EventGridPublisherClient)}.{nameof(EventGridPublisherClient.SendEvents)}");

            activity.SetW3CFormat();
            activity.Start();
            List <CloudEvent> eventsList = new List <CloudEvent>();

            for (int i = 0; i < 10; i++)
            {
                CloudEvent cloudEvent = new CloudEvent(
                    "record",
                    "Microsoft.MockPublisher.TestEvent",
                    JsonDocument.Parse("{\"property1\": \"abc\",  \"property2\": 123}").RootElement)
                {
                    Id      = "id",
                    Subject = $"Subject-{i}",
                    Time    = DateTimeOffset.UtcNow
                };
                if (inclTraceparent && i % 2 == 0)
                {
                    cloudEvent.ExtensionAttributes.Add("traceparent", "traceparentValue");
                }
                if (inclTracestate && i % 2 == 0)
                {
                    cloudEvent.ExtensionAttributes.Add("tracestate", "param:value");
                }
                eventsList.Add(cloudEvent);
            }
            await client.SendEventsAsync(eventsList);

            activity.Stop();
            List <CloudEvent>        cloudEvents = DeserializeRequest(mockTransport.SingleRequest);
            IEnumerator <CloudEvent> cloudEnum   = eventsList.GetEnumerator();

            foreach (CloudEvent cloudEvent in cloudEvents)
            {
                cloudEnum.MoveNext();
                Dictionary <string, object> cloudEventAttr = cloudEnum.Current.ExtensionAttributes;
                if (cloudEventAttr.ContainsKey(TraceParentHeaderName) &&
                    cloudEventAttr.ContainsKey(TraceStateHeaderName))
                {
                    Assert.AreEqual(
                        cloudEventAttr[TraceParentHeaderName],
                        cloudEvent.ExtensionAttributes[TraceParentHeaderName]);

                    Assert.AreEqual(
                        cloudEventAttr[TraceStateHeaderName],
                        cloudEvent.ExtensionAttributes[TraceStateHeaderName]);
                }
                else if (cloudEventAttr.ContainsKey(TraceParentHeaderName))
                {
                    Assert.AreEqual(
                        cloudEventAttr[TraceParentHeaderName],
                        cloudEvent.ExtensionAttributes[TraceParentHeaderName]);
                }
                else if (cloudEventAttr.ContainsKey(TraceStateHeaderName))
                {
                    Assert.AreEqual(
                        cloudEventAttr[TraceStateHeaderName],
                        cloudEvent.ExtensionAttributes[TraceStateHeaderName]);
                }
                else
                {
                    Assert.AreEqual(
                        activity.Id,
                        cloudEvent.ExtensionAttributes[TraceParentHeaderName]);
                }
            }
        }
        public async Task AnalyzeSentimentAssessmentInOtherSentence()
        {
            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(@"
                {
                    ""documents"": [
                        {
                            ""id"": ""1"",
                            ""sentiment"": ""positive"",
                            ""confidenceScores"": {
                                ""positive"": 0.5,
                                ""neutral"": 0.0,
                                ""negative"": 0.5
                            },
                            ""sentences"": [
                                {
                                    ""sentiment"": ""positive"",
                                    ""confidenceScores"": {
                                        ""positive"": 1.0,
                                        ""neutral"": 0.0,
                                        ""negative"": 0.0
                                    },
                                    ""offset"": 0,
                                    ""length"": 30,
                                    ""text"": ""The park was clean."",
                                    ""targets"": [
                                        {
                                            ""sentiment"": ""positive"",
                                            ""confidenceScores"": {
                                                ""positive"": 1.0,
                                                ""negative"": 0.0
                                            },
                                            ""offset"": 4,
                                            ""length"": 4,
                                            ""text"": ""park"",
                                            ""relations"": [
                                                {
                                                    ""relationType"": ""assessment"",
                                                    ""ref"": ""#/documents/0/sentences/0/assessments/0""
                                                }
                                            ]
                                        }
                                    ],
                                    ""assessments"": [
                                        {
                                            ""sentiment"": ""positive"",
                                            ""confidenceScores"": {
                                                ""positive"": 1.0,
                                                ""negative"": 0.0
                                            },
                                            ""offset"": 13,
                                            ""length"": 5,
                                            ""text"": ""clean"",
                                            ""isNegated"": false
                                        }
                                    ]
                                },
                                {
                                    ""sentiment"": ""positive"",
                                    ""confidenceScores"": {
                                        ""positive"": 0.0,
                                        ""neutral"": 0.0,
                                        ""negative"": 1.0
                                    },
                                    ""offset"": 31,
                                    ""length"": 23,
                                    ""text"": ""It was clean."",
                                    ""targets"": [
                                        {
                                            ""sentiment"": ""positive"",
                                            ""confidenceScores"": {
                                                ""positive"": 0.0,
                                                ""negative"": 1.0
                                            },
                                            ""offset"": 35,
                                            ""length"": 4,
                                            ""text"": ""park"",
                                            ""relations"": [
                                                {
                                                    ""relationType"": ""assessment"",
                                                    ""ref"": ""#/documents/0/sentences/0/assessments/0""
                                                }
                                            ]
                                        }
                                    ],
                                    ""assessments"": []
                                }
                            ],
                            ""warnings"": []
                        }
                    ],
                    ""errors"": [],
                    ""modelVersion"": ""2020-04-01""
                }"));

            var mockResponse = new MockResponse(200);

            mockResponse.ContentStream = stream;

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

            DocumentSentiment response = await client.AnalyzeSentimentAsync("The park was clean. It was clean.");

            SentenceOpinion opinionS1 = response.Sentences.ElementAt(0).Opinions.FirstOrDefault();

            Assert.AreEqual("park", opinionS1.Target.Text);
            Assert.AreEqual(TextSentiment.Positive, opinionS1.Target.Sentiment);
            Assert.AreEqual("clean", opinionS1.Assessments.FirstOrDefault().Text);

            SentenceOpinion opinionS2 = response.Sentences.ElementAt(1).Opinions.FirstOrDefault();

            Assert.AreEqual("park", opinionS2.Target.Text);
            Assert.AreEqual(TextSentiment.Positive, opinionS2.Target.Sentiment);
            Assert.AreEqual("clean", opinionS2.Assessments.FirstOrDefault().Text);
        }
Exemplo n.º 31
0
        public async Task ActionGroupsCreateOrUpdateTest()
        {
            var EventDataList = new List <EventData> {
                new EventData(
                    new SenderAuthorization("action", "role", "scope"),
                    new Dictionary <string, string>()
                {
                    { "tag", "tag" }
                },
                    "caller", "description", "Id", "eventDataId", "correlationId",
                    new LocalizableString("value", "localizedValue"),
                    new LocalizableString("categoryvalue"), new HttpRequestInfo("clientRequestId", "clientIpAddress", "method", "url"), EventLevel.Warning, "resourcegroupname",
                    new LocalizableString("resourceProvide"), "resourceId",
                    new LocalizableString("resourceType"), "operationId",
                    new LocalizableString("operationName"),
                    new Dictionary <string, string>(),
                    new LocalizableString("status"),
                    new LocalizableString("substatus"),
                    DateTime.Parse("2014-05-20T13:14:20.7882792Z"), DateTime.Parse("2014-05-20T13:14:20.7882792Z"), "subscriptionId", "tenantId"
                    )
            };
            var mockResponse = new MockResponse((int)HttpStatusCode.OK);
            var content      = @"
                    {
                        'value':[
                            {
                                'authorization': {
                                    'action': 'action',
                                    'role': 'role',
                                    'scope': 'scope'
                                },
                                'claims': {
                                    'tag': 'tag'
                                },
                                'caller': 'caller',
                                'description': 'description',
                                'id': 'Id',
                                'eventDataId': 'eventDataId',
                                'correlationId': 'correlationId',
                                'eventName': {
                                    'value': 'value',
                                    'localizedValue': 'localizedValue'
                                },
                                'category': {
                                    'value': 'categoryvalue',
                                    'localizedValue': null
                                },
                                'httpRequest': {
                                'clientRequestId': 'clientRequestId',
                                'clientIpAddress': 'clientIpAddress',
                                'method': 'method',
                                'uri': 'url'
                                },
                                'level': 'Warning',
                                'resourceGroupName': 'resourcegroupname',
                                'resourceProviderName': {
                                    'value': 'resourceProvide',
                                    'localizedValue': null
                                },
                                'resourceId': 'resourceId',
                                'resourceType': {
                                    'value': 'resourceType',
                                    'localizedValue': null
                                },
                                'operationId': 'operationId',
                                'operationName': {
                                    'value': 'operationName',
                                    'localizedValue': null
                                },
                                'properties': {},
                                'status': {
                                    'value': 'status',
                                    'localizedValue': null
                                },
                                'subStatus': {
                                    'value': 'substatus',
                                    'localizedValue': null
                                },
                                'eventTimestamp': '2014-05-20T13:14:20.7882792+00:00',
                                'submissionTimestamp': '2014-05-20T13:14:20.7882792+00:00',
                                'subscriptionId': 'subscriptionId',
                                'tenantId': 'tenantId'
                            }
                        ]
}".Replace("'", "\"");

            mockResponse.SetContent(content);
            var mockTransport  = new MockTransport(mockResponse);
            var insightsClient = GetInsightsManagementClient(mockTransport);
            var result         = await insightsClient.ActivityLogs.ListAsync("filter").ToEnumerableAsync();

            AreEqual(EventDataList, result);
        }