Exemplo n.º 1
0
        public void LoadRule()
        {
            HttpRequestUnitTestRule rule = null;

            if (UnitTest != null)
            {
                rule = UnitTest.HttpRequestUnitTest.Rules.FirstOrDefault();
            }
            else
            {
                Period = TimeSpan.FromMinutes(10);
            }

            if (rule != null)
            {
                Method         = rule.Method;
                TimeOutSeconds = rule.TimeoutSeconds ?? 10;
                Url            = rule.Url;
                SuccessHtml    = rule.SuccessHtml;
                ErrorHtml      = rule.ErrorHtml;
                ResponseCode   = rule.ResponseCode ?? 200;
                RequestHeaders = GetRuleDatas(rule, HttpRequestUnitTestRuleDataType.RequestHeader);
                WebFormDatas   = GetRuleDatas(rule, HttpRequestUnitTestRuleDataType.WebFormData);
                RequestCookies = GetRuleDatas(rule, HttpRequestUnitTestRuleDataType.RequestCookie);
            }
            else
            {
                ResponseCode   = 200;
                TimeOutSeconds = 5;
                Method         = HttpRequestMethod.Get;
            }
        }
Exemplo n.º 2
0
 protected void CheckRuleDeletingPermissions(HttpRequestUnitTestRule rule)
 {
     if (rule.IsDeleted)
     {
         throw new AlreadyDeletedException(rule.Id, Naming.HttpRequestUnitTestRule);
     }
 }
Exemplo n.º 3
0
        protected override void SetUnitTestParams(UnitTest unitTest, EditSimpleModel model)
        {
            if (unitTest.HttpRequestUnitTest == null)
            {
                unitTest.HttpRequestUnitTest = new HttpRequestUnitTest()
                {
                    UnitTest = unitTest
                }
            }
            ;
            var rule = unitTest.HttpRequestUnitTest.Rules.FirstOrDefault(FindRulePredicate());

            if (rule == null)
            {
                rule = new HttpRequestUnitTestRule()
                {
                    Id             = Guid.NewGuid(),
                    Method         = HttpRequestMethod.Get,
                    ResponseCode   = 200,
                    TimeoutSeconds = 5,
                    SortNumber     = 0
                };
                unitTest.HttpRequestUnitTest.Rules.Add(rule);
            }
            rule.DisplayName = "Правило http-проверки сайта " + model.Url;
            rule.Url         = model.Url;
        }
Exemplo n.º 4
0
        public void SaveRule()
        {
            if (UnitTest.HttpRequestUnitTest == null)
            {
                var newHttpRequestUnitTest = new HttpRequestUnitTest
                {
                    UnitTestId = UnitTest.Id,
                    UnitTest   = UnitTest
                };
                UnitTest.HttpRequestUnitTest = newHttpRequestUnitTest;
            }

            var rule = UnitTest.HttpRequestUnitTest.Rules.FirstOrDefault();

            if (rule == null)
            {
                rule = new HttpRequestUnitTestRule()
                {
                    Id = Guid.NewGuid(),
                    HttpRequestUnitTest = UnitTest.HttpRequestUnitTest
                };
                UnitTest.HttpRequestUnitTest.Rules.Add(rule);
            }

            rule.DisplayName    = UnitTest.DisplayName;
            rule.SortNumber     = 0;
            rule.TimeoutSeconds = TimeOutSeconds;
            rule.Method         = Method;
            rule.Url            = new Uri(Url).AbsoluteUri;
            rule.ResponseCode   = ResponseCode;
            rule.SuccessHtml    = SuccessHtml;
            rule.ErrorHtml      = ErrorHtml;

            foreach (var data in rule.Datas.ToArray())
            {
                rule.Datas.Remove(data);
                AccountDbContext.Entry(data).State = System.Data.Entity.EntityState.Deleted;
            }

            if (RequestHeaders != null)
            {
                RequestHeaders.ForEach(x => AddRuleData(rule, x, HttpRequestUnitTestRuleDataType.RequestHeader));
            }

            if (RequestCookies != null)
            {
                RequestCookies.ForEach(x => AddRuleData(rule, x, HttpRequestUnitTestRuleDataType.RequestCookie));
            }

            if (WebFormDatas != null)
            {
                WebFormDatas.ForEach(x => AddRuleData(rule, x, HttpRequestUnitTestRuleDataType.WebFormData));
            }
        }
Exemplo n.º 5
0
        protected List <KeyValueRowModel> GetRuleDatas(HttpRequestUnitTestRule rule, HttpRequestUnitTestRuleDataType type)
        {
            var datas = rule.Datas.Where(x => x.Type == type).ToList();
            var rows  = new List <KeyValueRowModel>();

            foreach (var data in datas)
            {
                var row = ConvertToKeyValueRow(data);
                rows.Add(row);
            }
            return(rows);
        }
Exemplo n.º 6
0
        protected void AddRuleData(HttpRequestUnitTestRule rule, KeyValueRowModel row, HttpRequestUnitTestRuleDataType type)
        {
            var data = new HttpRequestUnitTestRuleData();

            data.Id     = row.HasId ? new Guid(row.Id) : Guid.NewGuid();
            data.Key    = row.Key;
            data.Value  = row.Value;
            data.Type   = type;
            data.Rule   = rule;
            data.RuleId = rule.Id;
            rule.Datas.Add(data);
        }
Exemplo n.º 7
0
        protected void AddRuleData(HttpRequestUnitTestRule rule, KeyValueRowModel row, HttpRequestUnitTestRuleDataType type)
        {
            var data = new HttpRequestUnitTestRuleData
            {
                Id     = Guid.NewGuid(),
                Key    = row.Key,
                Value  = row.Value,
                Type   = type,
                Rule   = rule,
                RuleId = rule.Id
            };

            rule.Datas.Add(data);
        }
        protected HttpRequestResultInfo ProcessRule(HttpRequestUnitTestRule rule, ILogger logger)
        {
            var result = ProcessRuleRaw(rule, logger);

            if (result.ErrorCode == HttpRequestErrorCode.Success)
            {
                return(result);
            }

            if (IsInternetWork() == false)
            {
                result.ErrorCode    = HttpRequestErrorCode.InternetNotWork;
                result.ErrorMessage = "Неполадки в сети";
                return(result);
            }

            return(result);
        }
        protected HttpRequestResultInfo ProcessRuleRaw(HttpRequestUnitTestRule rule, ILogger logger)
        {
            var result = new HttpRequestResultInfo
            {
                ErrorCode = HttpRequestErrorCode.Success,
                Rule      = rule,
                StartDate = DateTime.Now
            };

            try
            {
                if (rule == null)
                {
                    throw new ArgumentNullException("rule");
                }

                logger.Debug("Правило: " + rule.DisplayName);
                if (string.IsNullOrWhiteSpace(rule.Url))
                {
                    result.ErrorCode    = HttpRequestErrorCode.UrlFormatError;
                    result.ErrorMessage = "Укажите URL";
                    return(result);
                }
                Uri uri = null;
                try
                {
                    uri = new Uri(rule.Url);
                }
                catch (UriFormatException)
                {
                    result.ErrorCode    = HttpRequestErrorCode.UrlFormatError;
                    result.ErrorMessage = "Неверный формат URL";
                    return(result);
                }
                if (new[] { "http", "https" }.Contains(uri.Scheme.ToLowerInvariant()) == false)
                {
                    result.ErrorCode    = HttpRequestErrorCode.UrlFormatError;
                    result.ErrorMessage = "Неверная схема URI. Используйте http или https";
                    return(result);
                }
                if (NetworkHelper.IsDomainHasIp(uri.Host) == false)
                {
                    result.ErrorCode    = HttpRequestErrorCode.UnknownDomain;
                    result.ErrorMessage = "Не удалось получить IP-адрес";
                    return(result);
                }

                var formDatas      = rule.GetWebFormsDatas();
                var requestHeaders = rule.GetRequestHeaders();
                var requestCookies = rule.GetRequestCookies();

                // установим таймаут
                var timeOutSeconds = rule.TimeoutSeconds ?? 60;
                if (timeOutSeconds > 60)
                {
                    timeOutSeconds = 60;
                }

                // обновим URL
                if (rule.Method == HttpRequestMethod.Get && formDatas.Count > 0)
                {
                    var uriBuilder          = new UriBuilder(uri);
                    var httpValueCollection = HttpUtility.ParseQueryString(uriBuilder.Uri.Query);
                    foreach (var webFormData in formDatas)
                    {
                        httpValueCollection.Add(webFormData.Key, webFormData.Value);
                    }
                    uriBuilder.Query = httpValueCollection.ToString();
                    uri = uriBuilder.Uri;
                }

                // создадим запрос
                var request = (HttpWebRequest)WebRequest.Create(uri);
                logger.Debug("Uri: " + request.RequestUri.AbsoluteUri);
                request.MaximumAutomaticRedirections = 4;
                request.MaximumResponseHeadersLength = 20;
                request.Timeout          = timeOutSeconds * 1000;
                request.ReadWriteTimeout = timeOutSeconds * 1000;
                result.Request           = request;

                // добавим заголовки HTTP
                foreach (var header in requestHeaders)
                {
                    if (string.Equals("User-Agent", header.Key, StringComparison.OrdinalIgnoreCase))
                    {
                        request.UserAgent = header.Value;
                    }
                    else
                    {
                        request.Headers.Add(header.Key, header.Value);
                    }
                }

                // Обязательно заполним UserAgent
                // Пустого UserAgent быть не должно
                // Многие сервера выдают ошибку из-за этого
                if (string.IsNullOrEmpty(request.UserAgent))
                {
                    request.UserAgent = "Zidium";
                }

                // добавим куки
                foreach (var cookie in requestCookies)
                {
                    request.CookieContainer.Add(new Cookie(cookie.Key, cookie.Value));
                }

                // добавим данные веб-формы
                var postData = "";
                if (rule.Method == HttpRequestMethod.Post)
                {
                    request.Method      = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    var httpValueCollection = HttpUtility.ParseQueryString(string.Empty);
                    foreach (var formData in formDatas)
                    {
                        httpValueCollection.Add(formData.Key, formData.Value);
                    }
                    postData = httpValueCollection.ToString(); // данный метод внутри кодирует спец символы
                    var data = Encoding.UTF8.GetBytes(postData);
                    request.ContentLength = postData.Length;
                    using (var dataStream = request.GetRequestStream())
                    {
                        dataStream.Write(data, 0, data.Length);
                        dataStream.Close();
                    }
                }

                // получаем ответ
                try
                {
                    var response = (HttpWebResponse)request.GetResponse();
                    result.ErrorCode = CheckResponse(result, timeOutSeconds, response, logger);
                }
                catch (SocketException exception)
                {
                    result.ErrorMessage = exception.Message;
                    result.ErrorCode    = HttpRequestErrorCode.TcpError;
                    logger.Error(exception);
                }
                catch (IOException exception)
                {
                    result.ErrorMessage = exception.Message;
                    result.ErrorCode    = HttpRequestErrorCode.TcpError;
                    logger.Error(exception);
                }
                catch (WebException exception)
                {
                    result.ErrorMessage = exception.Message;
                    if (exception.Response != null)
                    {
                        var httpResponse = (HttpWebResponse)exception.Response;
                        if (result.ResponseHeaders == null)
                        {
                            result.ResponseHeaders = GetResponseHeaders(httpResponse);
                        }
                        if (result.ResponseHtml == null)
                        {
                            result.ResponseHtml = GetResponseHtml(httpResponse);
                        }
                        if (result.HttpStatusCode == null)
                        {
                            result.HttpStatusCode = httpResponse.StatusCode;
                        }
                    }
                    if (exception.Status == WebExceptionStatus.Timeout)
                    {
                        result.ErrorCode = HttpRequestErrorCode.Timeout;
                    }
                    else if (exception.Status == WebExceptionStatus.ProtocolError)
                    {
                        result.ErrorCode = HttpRequestErrorCode.InvalidResponseCode;
                    }
                    else
                    {
                        result.ErrorCode = HttpRequestErrorCode.TcpError;
                        logger.Error(exception);
                    }
                }
            }
            catch (WebException exception)
            {
                result.ErrorCode    = HttpRequestErrorCode.TcpError;
                result.ErrorMessage = exception.Message;
                logger.Error(exception);
            }
            catch (Exception exception)
            {
                exception.Data.Add("UnitTestId", rule.HttpRequestUnitTest.UnitTestId);
                exception.Data.Add("RuleId", rule.Id);
                exception.Data.Add("RuleName", rule.DisplayName);
                exception.Data.Add("UnitTestName", rule.HttpRequestUnitTest.UnitTest.DisplayName);
                logger.Error(exception);

                result.ErrorCode    = HttpRequestErrorCode.UnknownError;
                result.ErrorMessage = exception.Message;
            }
            finally
            {
                result.EndDate = DateTime.Now;
                logger.Info(result.Rule.Url + " => " + result.ErrorCode);
            }
            return(result);
        }
Exemplo n.º 10
0
        protected override SendUnitTestResultRequestData GetResult(
            Guid accountId,
            AccountDbContext accountDbContext,
            UnitTest unitTest,
            ILogger logger,
            CancellationToken token)
        {
            var rules = unitTest.HttpRequestUnitTest.Rules
                        .Where(x => x.IsDeleted == false)
                        .OrderBy(x => x.SortNumber)
                        .ToList();

            logger.Debug("Найдено правил " + rules.Count);
            if (rules.Count > 0)
            {
                // Проверим наличие баннера, если это нужно
                if (unitTest.HttpRequestUnitTest.LastBannerCheck == null ||
                    unitTest.HttpRequestUnitTest.LastBannerCheck.Value <= DateTime.Now.AddHours(-24))
                {
                    var bannerResultData = CheckForBanner(accountId, accountDbContext, unitTest, logger);

                    if (bannerResultData != null)
                    {
                        return(bannerResultData);
                    }
                }

                var resultData = new SendUnitTestResultRequestData();
                resultData.Properties = new List <ExtentionPropertyDto>();

                HttpRequestUnitTestRule errorRule = null;
                foreach (var rule in rules)
                {
                    token.ThrowIfCancellationRequested();

                    var ruleResult = ProcessRule(rule, logger);

                    if (ruleResult.ErrorCode == HttpRequestErrorCode.UnknownError)
                    {
                        // если произошла неизвестная ошибка, то не обновляем статус проверки
                        logger.Debug("Выход из-за неизвестной ошибки");
                        return(null);
                    }
                    if (ruleResult.ErrorCode == HttpRequestErrorCode.InternetNotWork)
                    {
                        // Если интернет не работает, то не обновляем статус проверки
                        logger.Debug("Выход из-за InternetNotWork");
                        return(null);
                    }

                    // обновим правило
                    rule.LastRunErrorCode    = ruleResult.ErrorCode;
                    rule.LastRunTime         = ruleResult.StartDate;
                    rule.LastRunDurationMs   = (int)(ruleResult.EndDate - ruleResult.StartDate).TotalMilliseconds;
                    rule.LastRunErrorMessage = ruleResult.ErrorMessage;

                    // сохраним информацию об ошибке
                    if (errorRule == null && ruleResult.ErrorCode != HttpRequestErrorCode.Success)
                    {
                        errorRule = rule;
                        resultData.Properties.AddValue("Rule", rule.DisplayName);
                        resultData.Properties.AddValue("ErrorMessage", rule.LastRunErrorMessage);
                        resultData.Properties.AddValue("ErrorCode", rule.LastRunErrorCode.ToString());
                        resultData.Properties.AddValue("RequestMethod", rule.Method.ToString());
                        resultData.Properties.AddValue("TimeoutMs", (rule.TimeoutSeconds ?? 0) * 1000);

                        var duration = (int)((ruleResult.EndDate - ruleResult.StartDate).TotalMilliseconds);
                        resultData.Properties.AddValue("ExecutionTimeMs", duration);

                        if (ruleResult.Request != null)
                        {
                            resultData.Properties.AddValue("RequestUrl", ruleResult.Request.RequestUri.AbsoluteUri);
                        }

                        if (ruleResult.ResponseHeaders != null)
                        {
                            resultData.Properties.AddValue("ResponseHeaders", ruleResult.ResponseHeaders);
                        }
                        if (ruleResult.ResponseHtml != null)
                        {
                            resultData.Properties.AddValue("ResponseHtml", ruleResult.ResponseHtml);
                        }
                        if (unitTest.HttpRequestUnitTest.ProcessAllRulesOnError == false)
                        {
                            break; // прекращаем выполнять правила, если хотя бы в одном ошибка
                        }
                    }
                }
                if (errorRule != null)
                {
                    resultData.Result = UnitTestResult.Alarm;
                    var errorMessage = errorRule.DisplayName + ". " + errorRule.LastRunErrorMessage;
                    resultData.Message = errorMessage;
                }
                else
                {
                    resultData.Result  = UnitTestResult.Success;
                    resultData.Message = "Успешно";
                }

                // сохраним изменения статусов правил
                accountDbContext.SaveChanges();

                return(resultData);
            }

            return(new SendUnitTestResultRequestData()
            {
                Result = UnitTestResult.Unknown,
                Message = "Укажите хотя бы один запрос (правило) для проверки"
            });
        }