/// <summary>
        /// Initialises a new instance of the <see cref="WebTestResource"/> class.
        /// </summary>
        /// <param name="name">Web test name.</param>
        /// <param name="url">Test URL.</param>
        /// <param name="insights"><see cref="ResourceBaseExtended"/> instance representing Application Insights component.</param>
        /// <param name="testType">Type of the web test. Default value is <c>WebTestType.UriPingTest</c>. </param>
        public WebTestResource(string name, string url, ResourceBaseExtended insights, TestType testType = TestType.UrlPingTest)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            this._name = name;

            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentNullException(nameof(url));
            }

            this._url = url;

            if (insights == null)
            {
                throw new ArgumentNullException(nameof(insights));
            }

            this._insights = insights;

            this._testType = testType;

            this.Initialise();
        }
        public void Given_InvalidTestType_CreateOrUpdateWebTestAsync_ShouldThrow_Exception(string name, string url, AuthType authType, string accessToken, TestType testType)
        {
            this._webTest.SetupGet(p => p.TestType).Returns(testType);

            var insightsResource = new ResourceBaseExtended();

            Func <Task> func = async() => { var result = await this._service.CreateOrUpdateWebTestAsync(name, url, authType, accessToken, this._webTest.Object, this._resourceClient.Object, insightsResource).ConfigureAwait(false); };

            func.ShouldThrow <InvalidOperationException>();
        }
        public void Given_NullParameters_CreateOrUpdateAlertsAsync_ShouldThrow_Exception(string name, string location)
        {
            var webTestResource  = new ResourceBaseExtended(location);
            var insightsResource = new ResourceBaseExtended(location);

            Func <Task> func = async() => { var result = await this._service.CreateOrUpdateAlertsAsync(null, this._webTest.Object, this._insightsClient.Object, webTestResource, insightsResource).ConfigureAwait(false); };

            func.ShouldThrow <ArgumentNullException>();

            func = async() => { var result = await this._service.CreateOrUpdateAlertsAsync(name, null, this._insightsClient.Object, webTestResource, insightsResource).ConfigureAwait(false); };
            func.ShouldThrow <ArgumentNullException>();

            func = async() => { var result = await this._service.CreateOrUpdateAlertsAsync(name, this._webTest.Object, null, webTestResource, insightsResource).ConfigureAwait(false); };
            func.ShouldThrow <ArgumentNullException>();

            func = async() => { var result = await this._service.CreateOrUpdateAlertsAsync(name, this._webTest.Object, this._insightsClient.Object, null, insightsResource).ConfigureAwait(false); };
            func.ShouldThrow <ArgumentNullException>();

            func = async() => { var result = await this._service.CreateOrUpdateAlertsAsync(name, this._webTest.Object, this._insightsClient.Object, webTestResource, null).ConfigureAwait(false); };
            func.ShouldThrow <ArgumentNullException>();
        }
        public async void Given_Parameters_CreateOrUpdateAlertsAsync_ShouldReturn_Result(string name, bool sendAlertToAdmin, string recipients, int alertLocationThreshold, TestAlertFailureTimeWindow alertFailureTimeWindow, bool isEnabled, string location)
        {
            var emails = recipients.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();

            var alerts = new Mock <AlertsElement>();

            alerts.SetupGet(p => p.SendAlertToAdmin).Returns(sendAlertToAdmin);
            alerts.SetupGet(p => p.Recipients).Returns(emails);
            alerts.SetupGet(p => p.AlertLocationThreshold).Returns(alertLocationThreshold);
            alerts.SetupGet(p => p.TestAlertFailureTimeWindow).Returns(alertFailureTimeWindow);
            alerts.SetupGet(p => p.IsEnabled).Returns(isEnabled);

            this._webTest.SetupGet(p => p.Alerts).Returns(alerts.Object);

            var response = new AzureOperationResponse()
            {
                StatusCode = HttpStatusCode.OK
            };

            this._alertOperations.Setup(p => p.CreateOrUpdateRuleAsync(It.IsAny <string>(), It.IsAny <RuleCreateOrUpdateParameters>(), It.IsAny <CancellationToken>())).ReturnsAsync(response);

            this._insightsClient.Setup(p => p.AlertOperations).Returns(this._alertOperations.Object);

            var webTestId       = Guid.NewGuid();
            var insightsId      = Guid.NewGuid();
            var webTestResource = new ResourceBaseExtended(location)
            {
                Id = webTestId.ToString(), Name = name
            };
            var insightsResource = new ResourceBaseExtended(location)
            {
                Id = insightsId.ToString(), Name = name
            };

            var result = await this._service.CreateOrUpdateAlertsAsync(name, this._webTest.Object, this._insightsClient.Object, webTestResource, insightsResource).ConfigureAwait(false);

            result.Should().BeTrue();
        }
        public async void Given_Parameters_CreateOrUpdateWebTestAsync_ShouldReturn_Result(string name, string url, TestStatus testStatus, TestFrequency testFrequency, TestTimeout testTimeout, bool parseDependentRequests, RetriesForWebTestFailure retriesForWebTestFailure, AuthType authType, string accessToken, TestLocations testLocations, string resourceGroup, string location)
        {
            var successCriteria = new Mock <SucessCriteriaElement>();

            successCriteria.SetupGet(p => p.Timeout).Returns(testTimeout);

            this._webTest.SetupGet(p => p.TestType).Returns(TestType.UrlPingTest);
            this._webTest.SetupGet(p => p.Status).Returns(testStatus);
            this._webTest.SetupGet(p => p.Frequency).Returns(testFrequency);
            this._webTest.SetupGet(p => p.ParseDependentRequests).Returns(parseDependentRequests);
            this._webTest.SetupGet(p => p.SuccessCriteria).Returns(successCriteria.Object);
            this._webTest.SetupGet(p => p.RetriesForWebTestFailure).Returns(retriesForWebTestFailure);
            this._webTest.SetupGet(p => p.TestLocations).Returns(testLocations);

            this._appInsights.SetupGet(p => p.ResourceGroup).Returns(resourceGroup);

            this._settings.SetupGet(p => p.ApplicationInsight).Returns(this._appInsights.Object);

            var resource       = new GenericResourceExtended(location);
            var resourceResult = new ResourceCreateOrUpdateResult()
            {
                StatusCode = HttpStatusCode.OK, Resource = resource
            };

            this._resourceOperations.Setup(p => p.CreateOrUpdateAsync(It.IsAny <string>(), It.IsAny <ResourceIdentity>(), It.IsAny <GenericResource>(), It.IsAny <CancellationToken>())).ReturnsAsync(resourceResult);

            this._resourceClient.Setup(p => p.Resources).Returns(this._resourceOperations.Object);

            var id = Guid.NewGuid();
            var insightsResource = new ResourceBaseExtended(location)
            {
                Id = id.ToString(), Name = name
            };

            var result = await this._service.CreateOrUpdateWebTestAsync(name, url, authType, accessToken, this._webTest.Object, this._resourceClient.Object, insightsResource).ConfigureAwait(false);

            result.Location.Should().BeEquivalentTo(location);
        }
        public static bool AreEqualPrereq(
            ResourceBaseExtended first,
            ResourceBaseExtended second,
            bool ignoreEtag = false)
        {
            if (first == null && second == null)
            {
                return(true);
            }
            else if (first == null || second == null)
            {
                return(false);
            }

            if (first.Location != second.Location ||
                first.Name != second.Name)
            {
                return(false);
            }

            if (first.Tags != null || second.Tags != null)
            {
                if (first.Tags == null || second.Tags == null || first.Tags.Count != second.Tags.Count)
                {
                    return(false);
                }

                foreach (string key in first.Tags.Keys)
                {
                    if (!second.Tags.ContainsKey(key) || first.Tags[key] != second.Tags[key])
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Adds properties for web test alert.
        /// </summary>
        /// <param name="parameters"><see cref="RuleCreateOrUpdateParameters"/> instance.</param>
        /// <param name="name">Name of web test.</param>
        /// <param name="element"><see cref="WebTestElement"/> instance from App.config/Web.config.</param>
        /// <param name="webTest"><see cref="ResourceBaseExtended"/> instance representing web test resource.</param>
        /// <param name="insights"><see cref="ResourceBaseExtended"/> instance representing Application Insights resource.</param>
        /// <returns>Returns the <see cref="RuleCreateOrUpdateParameters"/> instance with properties added.</returns>
        public static RuleCreateOrUpdateParameters AddProperties(this RuleCreateOrUpdateParameters parameters, string name, WebTestElement element, ResourceBaseExtended webTest, ResourceBaseExtended insights)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (element == null)
            {
                throw new ArgumentNullException(nameof(element));
            }

            if (webTest == null)
            {
                throw new ArgumentNullException(nameof(webTest));
            }

            if (insights == null)
            {
                throw new ArgumentNullException(nameof(insights));
            }

            var alertName = $"{name}-{insights.Name}-alert".ToLowerInvariant();

            var action = new RuleEmailAction()
            {
                SendToServiceOwners = element.Alerts.SendAlertToAdmin
            };

            if (!element.Alerts.Recipients.IsNullOrEmpty())
            {
                action.CustomEmails = element.Alerts.Recipients;
            }

            var source = new RuleMetricDataSource()
            {
                MetricName = AlertMetricName, ResourceUri = webTest.Id
            };
            var condition = new LocationThresholdRuleCondition()
            {
                DataSource          = source,
                FailedLocationCount = element.Alerts.AlertLocationThreshold,
                WindowSize          = TimeSpan.FromMinutes((int)element.Alerts.TestAlertFailureTimeWindow),
            };
            var rule = new Rule()
            {
                Name            = alertName,
                Description     = string.Empty,
                IsEnabled       = element.Alerts.IsEnabled,
                LastUpdatedTime = DateTime.UtcNow,
                Actions         = { action },
                Condition       = condition,
            };

            parameters.Properties = rule;

            return(parameters);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Adds tags for web test alert.
        /// </summary>
        /// <param name="parameters"><see cref="RuleCreateOrUpdateParameters"/> instance.</param>
        /// <param name="webTest"><see cref="ResourceBaseExtended"/> instance representing web test resource.</param>
        /// <param name="insights"><see cref="ResourceBaseExtended"/> instance representing Application Insights resource.</param>
        /// <returns>Returns the <see cref="RuleCreateOrUpdateParameters"/> instance with tags added.</returns>
        public static RuleCreateOrUpdateParameters AddTags(this RuleCreateOrUpdateParameters parameters, ResourceBaseExtended webTest, ResourceBaseExtended insights)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (webTest == null)
            {
                throw new ArgumentNullException(nameof(webTest));
            }

            if (insights == null)
            {
                throw new ArgumentNullException(nameof(insights));
            }

            parameters.Tags.Add($"hidden-link:{insights.Id}", "Resource");
            parameters.Tags.Add($"hidden-link:{webTest.Id}", "Resource");

            return(parameters);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates or updates alert resource.
        /// </summary>
        /// <param name="name">Name of the web test.</param>
        /// <param name="webTest"><see cref="WebTestElement"/> instance from configuration.</param>
        /// <param name="client"><see cref="IInsightsManagementClient"/> instance.</param>
        /// <param name="webTestResource"><see cref="ResourceBaseExtended"/> instance as a Web Test resource.</param>
        /// <param name="insightsResource"><see cref="ResourceBaseExtended"/> instance as an Application Insights resource.</param>
        /// <returns>Returns <c>True</c>, if the web test resource creted/updated successfully; otherwise returns <c>False</c>.</returns>
        public async Task <bool> CreateOrUpdateAlertsAsync(string name, WebTestElement webTest, IInsightsManagementClient client, ResourceBaseExtended webTestResource, ResourceBaseExtended insightsResource)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (webTest == null)
            {
                throw new ArgumentNullException(nameof(webTest));
            }

            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (webTestResource == null)
            {
                throw new ArgumentNullException(nameof(webTestResource));
            }

            if (insightsResource == null)
            {
                throw new ArgumentNullException(nameof(insightsResource));
            }

#if !TEST
            Console.WriteLine($"Processing alert for {name} started ...");
#endif
            var parameters = (new RuleCreateOrUpdateParameters()
            {
                Location = InsightsAlertResourceLocation
            })
                             .AddTags(webTestResource, insightsResource)
                             .AddProperties(name, webTest, webTestResource, insightsResource);

            var result = await client.AlertOperations.CreateOrUpdateRuleAsync(this._appInsights.ResourceGroup, parameters).ConfigureAwait(false);

            if (!IsAcceptableHttpStatusCode(result.StatusCode, new[] { HttpStatusCode.OK, HttpStatusCode.Created }))
            {
                throw new HttpResponseException(result.StatusCode);
            }

#if !TEST
            Console.WriteLine($"Processing alert for {name} completed");
#endif
            return(true);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates or updates web test resource.
        /// </summary>
        /// <param name="name">Name of the web test.</param>
        /// <param name="url">URL of the web test.</param>
        /// <param name="authType"><see cref="AuthType"/> value.</param>
        /// <param name="accessToken">Access token value.</param>
        /// <param name="webTest"><see cref="WebTestElement"/> instance from configuration.</param>
        /// <param name="client"><see cref="IResourceManagementClient"/> instance.</param>
        /// <param name="insightsResource"><see cref="ResourceBaseExtended"/> instance as an Application Insights resource.</param>
        /// <returns>Returns <c>True</c>, if the web test resource creted/updated successfully; otherwise returns <c>False</c>.</returns>
        public async Task <GenericResourceExtended> CreateOrUpdateWebTestAsync(string name, string url, AuthType authType, string accessToken, WebTestElement webTest, IResourceManagementClient client, ResourceBaseExtended insightsResource)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentNullException(nameof(url));
            }

            if (webTest == null)
            {
                throw new ArgumentNullException(nameof(webTest));
            }

            // TODO: for now it only supports PING test.
            if (webTest.TestType != TestType.UrlPingTest)
            {
                throw new InvalidOperationException("Invalid web test type");
            }

            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (insightsResource == null)
            {
                throw new ArgumentNullException(nameof(insightsResource));
            }

#if !TEST
            Console.WriteLine($"Processing web test for {name} started ...");
#endif
            var resource = new WebTestResource(name, url, insightsResource, webTest.TestType);
            resource.CreateWebTestProperties(webTest.TestLocations, webTest.Status, webTest.Frequency, webTest.SuccessCriteria.Timeout, webTest.ParseDependentRequests, webTest.RetriesForWebTestFailure, authType: authType, accessToken: accessToken);

            var result = await client.Resources.CreateOrUpdateAsync(this._appInsights.ResourceGroup, resource.ResourceIdentity, resource).ConfigureAwait(false);

            if (!IsAcceptableHttpStatusCode(result.StatusCode, new[] { HttpStatusCode.OK, HttpStatusCode.Created }))
            {
                throw new HttpResponseException(result.StatusCode);
            }

#if !TEST
            Console.WriteLine($"Processing web test for {name} completed");
#endif
            return(result.Resource);
        }