Esempio n. 1
0
        public void UpdateUnitTest(Guid accountId, UpdateUnitTestRequestData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            if (data.UnitTestId == null)
            {
                throw new ParameterRequiredException("UnitTestId");
            }
            if (data.ComponentId == null)
            {
                throw new ParameterRequiredException("ComponentId");
            }
            if (data.UnitTestId == Guid.Empty)
            {
                throw new ParameterErrorException("UnitTestId не может быть Guid.Empty");
            }
            if (data.DisplayName == null)
            {
                throw new ParameterRequiredException("DisplayName");
            }
            if (string.IsNullOrWhiteSpace(data.DisplayName))
            {
                throw new ParameterErrorException("DisplayName не может быть пустым");
            }
            //if (data.ErrorColor == null)
            //{
            //    throw new ParameterRequiredException("ErrorColor");
            //}

            // SystemName сейчас не настраивается через GUI

            //if (data.SystemName == null)
            //{
            //    throw new ParameterRequiredException("SystemName");
            //}

            //получим компонент, чтобы убедится, что он принадлежит аккаунту
            var req = new AccountCacheRequest()
            {
                AccountId = accountId,
                ObjectId  = data.ComponentId.Value
            };
            var component = AllCaches.Components.Find(req);

            if (component == null)
            {
                throw new UnknownComponentIdException(data.ComponentId.Value, accountId);
            }

            var request = new AccountCacheRequest()
            {
                AccountId = accountId,
                ObjectId  = data.UnitTestId.Value
            };

            // сохраним изменения
            IUnitTestCacheReadObject unitTestCache = null;

            using (var unitTest = AllCaches.UnitTests.Write(request))
            {
                unitTestCache = unitTest;

                // период выполнения проверки
                if (unitTest.IsSystemType)
                {
                    // не для всех системных проверок можно указывать период (для проверки домена нельзя)
                    if (SystemUnitTestTypes.CanEditPeriod(unitTest.TypeId))
                    {
                        if (data.PeriodSeconds == null)
                        {
                            throw new ParameterRequiredException("Period");
                        }
                        if (data.PeriodSeconds.Value < 60)
                        {
                            throw new ParameterErrorException("Период проверки НЕ может быть меньше 1 минуты");
                        }
                        unitTest.PeriodSeconds = (int)data.PeriodSeconds.Value;
                    }

                    // чтобы выполнить проверку прямо сейчас с новыми параметрами и увидеть результат
                    unitTest.NextDate = DateTime.Now;
                }

                unitTest.DisplayName   = data.DisplayName;
                unitTest.ComponentId   = data.ComponentId.Value;
                unitTest.ErrorColor    = data.ErrorColor;
                unitTest.NoSignalColor = data.NoSignalColor;
                unitTest.ActualTime    = TimeSpanHelper.FromSeconds(data.ActualTime);

                if (data.SimpleMode.HasValue)
                {
                    unitTest.SimpleMode = data.SimpleMode.Value;
                }

                unitTest.BeginSave();
            }

            // ждем сохранения в кэше
            unitTestCache.WaitSaveChanges();
        }
Esempio n. 2
0
        protected UnitTest Create(
            Guid accountId,
            Guid componentId,
            Guid unitTestTypeId,
            string systemName,
            string displayName,
            Guid?newId)
        {
            // создаем отдельный контекст, чтобы после обработки объектов кэшем основной контекст загрузил актуальную версию из БД
            using (var accountDbContext = AccountDbContext.CreateFromAccountIdLocalCache(accountId))
            {
                var now       = DateTime.Now;
                var component = accountDbContext.Components.Single(x => x.Id == componentId);

                var unitTestId = newId ?? Guid.NewGuid();

                var statusData = Context.BulbService.CreateBulb(
                    accountId,
                    now,
                    EventCategory.UnitTestStatus,
                    unitTestId);

                var unitTest = new UnitTest()
                {
                    Id           = unitTestId,
                    SystemName   = systemName,
                    DisplayName  = displayName,
                    ComponentId  = componentId,
                    Component    = component,
                    Enable       = true,
                    ParentEnable = component.ParentEnable,
                    TypeId       = unitTestTypeId,
                    CreateDate   = now,
                    StatusDataId = statusData.Id
                };

                // чтобы не получилось так, что период равен нулю и начнется непрерывное выполнение проверки
                if (SystemUnitTestTypes.IsSystem(unitTestTypeId))
                {
                    if (unitTestTypeId == SystemUnitTestTypes.DomainNameTestType.Id)
                    {
                        // для доменной проверки период задается системой, пользователь НЕ может его менять сам
                        unitTest.PeriodSeconds = (int)TimeSpan.FromDays(1).TotalSeconds;
                    }
                    else
                    {
                        unitTest.PeriodSeconds = (int)TimeSpan.FromMinutes(10).TotalSeconds;
                    }
                }

                if (unitTestTypeId == SystemUnitTestTypes.HttpUnitTestType.Id)
                {
                    unitTest.HttpRequestUnitTest = new HttpRequestUnitTest()
                    {
                        UnitTestId = unitTestId
                    };
                }

                statusData.UnitTestId = unitTest.Id;

                accountDbContext.UnitTests.Add(unitTest);
                accountDbContext.SaveChanges();
                Context.GetAccountDbContext(accountId).SaveChanges();
                return(unitTest);
            }
        }
Esempio n. 3
0
        public IUnitTestCacheReadObject GetOrCreateUnitTest(Guid accountId, GetOrCreateUnitTestRequestData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            if (string.IsNullOrEmpty(data.SystemName))
            {
                throw new ParameterRequiredException("SystemName");
            }
            if (data.ComponentId == null)
            {
                throw new ParameterRequiredException("ComponentId");
            }
            if (data.UnitTestTypeId == null)
            {
                throw new ParameterRequiredException("UnitTestTypeId");
            }
            var cache       = new AccountCache(accountId);
            var componentId = data.ComponentId.Value;
            var systemName  = data.SystemName;

            // проверим, что тип проверки существует
            var unitTestTypeId = data.UnitTestTypeId.Value;

            if (!SystemUnitTestTypes.IsSystem(unitTestTypeId))
            {
                var unitTestType = AllCaches.UnitTestTypes.Find(new AccountCacheRequest()
                {
                    AccountId = accountId,
                    ObjectId  = unitTestTypeId
                });

                if (unitTestType == null)
                {
                    throw new UnknownUnitTestTypeIdException(unitTestTypeId);
                }
            }

            // получим компонент
            var component = cache.Components.Read(componentId);

            if (component == null)
            {
                throw new UnknownComponentIdException(componentId, accountId);
            }

            // проверим есть ли у него ссылка на проверку
            var unitTestRef = component.UnitTests.FindByName(data.SystemName);

            if (unitTestRef != null)
            {
                // ссылка есть, вернем существующую проверку
                var unitTest = cache.UnitTests.Read(unitTestRef.Id);
                if (unitTest == null)
                {
                    throw new Exception("unitTest == null");
                }
                return(unitTest);
            }

            // ссылки нет
            using (var writeComponent = cache.Components.Write(componentId))
            {
                // проверим ссылку еще раз
                unitTestRef = writeComponent.UnitTests.FindByName(data.SystemName);
                if (unitTestRef != null)
                {
                    var unitTest = cache.UnitTests.Read(unitTestRef.Id);
                    if (unitTest == null)
                    {
                        throw new Exception("unitTest == null");
                    }
                    return(unitTest);
                }

                // создадим проверку
                var accountDbContext = Context.GetAccountDbContext(accountId);

                // Проверим лимиты
                var checker     = AccountLimitsCheckerManager.GetCheckerForAccount(accountId);
                var checkResult = checker.CheckMaxUnitTestsCount(accountDbContext);

                if (!checkResult.Success)
                {
                    throw new OverLimitException(checkResult.Message);
                }

                // проверка лимитов пройдена
                if (string.IsNullOrWhiteSpace(data.DisplayName))
                {
                    data.DisplayName = data.SystemName;
                }

                // создаем юнит-тест
                var unitTestObj = Create(accountId, componentId, unitTestTypeId, systemName, data.DisplayName, data.NewId);
                unitTestRef = new CacheObjectReference(unitTestObj.Id, unitTestObj.SystemName);
                writeComponent.WriteUnitTests.Add(unitTestRef);
                writeComponent.BeginSave();

                checker.RefreshApiChecksCount();

                // обновим свойства
                using (var unitTestCache = cache.UnitTests.Write(unitTestObj.Id))
                {
                    unitTestCache.NoSignalColor = data.NoSignalColor;
                    unitTestCache.ErrorColor    = data.ErrorColor;
                    unitTestCache.ActualTime    = TimeSpanHelper.FromSeconds(data.ActualTimeSecs);
                    if (data.PeriodSeconds.HasValue)
                    {
                        unitTestCache.PeriodSeconds = data.PeriodSeconds;
                    }
                    if (data.SimpleMode.HasValue)
                    {
                        unitTestCache.SimpleMode = data.SimpleMode.Value;
                    }
                    unitTestCache.BeginSave();
                    unitTestCache.WaitSaveChanges();
                    return(unitTestCache);
                }
            }
        }