protected void AddEvent(Guid accountId, Guid ownerId, DateTime date, EventCategory category, Guid eventTypeId) { using (var storageDbContext = AccountDbContext.CreateFromAccountId(accountId)) { var _event = new Event() { OwnerId = ownerId, Category = category, Id = Guid.NewGuid(), StartDate = date, CreateDate = date, EndDate = date, ActualDate = date, LastUpdateDate = date, EventTypeId = eventTypeId }; _event.Properties.Add(new EventProperty() { Id = Guid.NewGuid(), EventId = _event.Id, Event = _event, DataType = DataType.String, Name = "test name", Value = "test value" }); storageDbContext.Events.Add(_event); storageDbContext.SaveChanges(); } }
public void AddTest() { var account = TestHelper.GetTestAccount(); var user = TestHelper.GetAccountAdminUser(account.Id); ComponentTypeEditModel model; using (var controller = new ComponentTypesController(account.Id, user.Id)) { var result = (ViewResultBase)controller.Add(); model = (ComponentTypeEditModel)result.Model; } model.SystemName = Guid.NewGuid().ToString(); model.DisplayName = Guid.NewGuid().ToString(); using (var controller = new ComponentTypesController(account.Id, user.Id)) { controller.Add(model); } var accountContext = AccountDbContext.CreateFromAccountId(account.Id); var repository = accountContext.GetComponentTypeRepository(); var componentType = repository.GetOneOrNullBySystemName(model.SystemName); Assert.NotNull(componentType); Assert.False(componentType.IsSystem); Assert.Equal(model.SystemName, componentType.SystemName); Assert.Equal(model.DisplayName, componentType.DisplayName); }
//public static List<Notification> _Last; public static List <Notification> SendSubscriptionNotifications( Guid accountId, Core.Api.EventImportance importance, Guid componentId, NotificationType notificationType) { using (var accountDbContext = AccountDbContext.CreateFromAccountId(accountId)) { // получим новые, неотправленные уведомления var notifications = accountDbContext.Notifications .Include("Event") .Include("Subscription") .Include("NotificationHttp") .Where(x => x.Event.OwnerId == componentId && x.Status == NotificationStatus.InQueue && x.Event.Importance == importance && x.Type == notificationType) .ToList(); foreach (var notification in notifications) { // сделаем вид, что уведомления отправлены notification.SendDate = DateTime.Now; notification.Status = NotificationStatus.Sended; } accountDbContext.SaveChanges(); //_Last = notifications; return(notifications); } }
public void AddTest() { var account = TestHelper.GetTestAccount(); var user = TestHelper.GetAccountAdminUser(account.Id); var componentTypeId = TestHelper.CreateRandomComponentTypeId(account.Id); ComponentAddModel model; using (var controller = new ComponentsController(account.Id, user.Id)) { var result = (ViewResultBase)controller.Add(); model = (ComponentAddModel)result.Model; } model.SystemName = Guid.NewGuid().ToString(); model.DisplayName = Guid.NewGuid().ToString(); model.ComponentTypeId = componentTypeId; model.Version = "1.2.3.4"; using (var controller = new ComponentsController(account.Id, user.Id)) { controller.Add(model); } var accountContext = AccountDbContext.CreateFromAccountId(account.Id); var component = accountContext.Components.Single(x => x.SystemName == model.SystemName); Assert.NotNull(component); Assert.Equal(model.SystemName, component.SystemName); Assert.Equal(model.DisplayName, component.DisplayName); Assert.Equal(model.ComponentTypeId, component.ComponentTypeId); Assert.Equal(model.Version, component.Version); }
public void DeleteTest() { var account = TestHelper.GetTestAccount(); var user = TestHelper.GetAccountAdminUser(account.Id); // Создадим тип компонента var componentTypeInfo = TestHelper.CreateRandomComponentType(account.Id); // Удалим его DeleteConfirmationModel model; using (var controller = new ComponentTypesController(account.Id, user.Id)) { var result = (ViewResultBase)controller.Delete(componentTypeInfo.Id); model = (DeleteConfirmationModel)result.Model; } model.ReturnUrl = "/"; using (var controller = new ComponentTypesController(account.Id, user.Id)) { controller.Delete(model); } // Проверим, что компонент удалился var accountContext = AccountDbContext.CreateFromAccountId(account.Id); var repository = accountContext.GetComponentTypeRepository(); var componentType = repository.GetByIdOrNull(componentTypeInfo.Id); Assert.NotNull(componentType); Assert.True(componentType.IsDeleted); }
protected void InitMetricRules(Guid accountId, Guid metricId) { // Получим метрику и заполним ее правила using (var accountContext = AccountDbContext.CreateFromAccountId(accountId)) { // Заполним правила счётчика var metricRepository = accountContext.GetMetricRepository(); var metric = metricRepository.GetById(metricId); var metricType = metric.MetricType; metricType.ConditionAlarm = "value <= 1"; metricType.ConditionWarning = "value <= 2"; metricType.ConditionSuccess = "value <= 3"; metricType.ConditionElseColor = Core.Common.ObjectColor.Red; accountContext.SaveChanges(); // Перекроем их правилами счётчика компонента metric.ConditionAlarm = "value <= 10"; metric.ConditionWarning = "value <= 100"; metric.ConditionSuccess = "value <= 1000"; metric.ConditionElseColor = Core.Common.ObjectColor.Gray; accountContext.SaveChanges(); AllCaches.MetricTypes.Unload(new AccountCacheRequest() { AccountId = accountId, ObjectId = metricType.Id }); AllCaches.Metrics.Unload(new AccountCacheRequest() { AccountId = accountId, ObjectId = metric.Id }); } }
public void SendMeNewsSettingTest() { var account = TestHelper.GetTestAccount(); var user = TestHelper.GetAccountAdminUser(account.Id); using (var accountContext = AccountDbContext.CreateFromAccountId(account.Id)) { var service = accountContext.GetUserSettingService(); service.SendMeNews(user.Id, false); accountContext.SaveChanges(); } using (var accountContext = AccountDbContext.CreateFromAccountId(account.Id)) { var service = accountContext.GetUserSettingService(); var value = service.SendMeNews(user.Id); Assert.False(value); } using (var accountContext = AccountDbContext.CreateFromAccountId(account.Id)) { var service = accountContext.GetUserSettingService(); service.SendMeNews(user.Id, true); accountContext.SaveChanges(); } using (var accountContext = AccountDbContext.CreateFromAccountId(account.Id)) { var service = accountContext.GetUserSettingService(); var value = service.SendMeNews(user.Id); Assert.True(value); } }
public void HttpNotificationTest() { // Создадим компонент var account = TestHelper.GetTestAccount(); var user = TestHelper.CreateTestUser(account.Id); var component = account.CreateTestApplicationComponent(); var componentControl = account.CreateRandomComponentControl(); // Добавим пользователю http-контакт var url = @"http://localhost/url"; using (var context = AccountDbContext.CreateFromAccountId(account.Id)) { var repository = context.GetUserRepository(); repository.AddContactToUser(user.Id, UserContactType.Http, url, componentControl.Client.ToServerTime(DateTime.Now)); } // Подпишемся на красное событие var dispatcher = TestHelper.GetDispatcherClient(); var subscriptionResponse = dispatcher.CreateSubscription(account.Id, new CreateSubscriptionRequestData() { UserId = user.Id, Object = SubscriptionObject.ComponentType, ComponentTypeId = component.Type.Id, Channel = SubscriptionChannel.Http, Importance = EventImportance.Alarm, IsEnabled = true }); Assert.True(subscriptionResponse.Success); // Отправим красное событие var eventType = TestHelper.GetTestEventType(account.Id); var eventResponse = dispatcher.SendEvent(account.Id, new Core.Api.SendEventData() { TypeSystemName = eventType.SystemName, ComponentId = component.Id, Category = Core.Api.EventCategory.ApplicationError, Importance = EventImportance.Alarm }); Assert.True(eventResponse.Success); account.SaveAllCaches(); // Запустим обработку var processor = new CreateNotificationsProcessor(LogManager.GetCurrentClassLogger(), new CancellationToken()); processor.ProcessAccount(account.Id, component.Id, user.Id); // Проверим, что появилось уведомление с типом http var notifications = TestHelper.SendSubscriptionNotifications(account.Id, EventImportance.Alarm, component.Id, NotificationType.Http); var notification = notifications[0]; Assert.NotNull(notification); Assert.Equal(url, notification.Address); // Проверим, что текст json заполнен //Assert.True(!string.IsNullOrEmpty(notification.NotificationHttp.Json)); }
public static void CheckExternalStatus(Guid accountId, IComponentControl componentControl, Core.Api.MonitoringStatus status) { using (var accountDbContext = AccountDbContext.CreateFromAccountId(accountId)) { var component = accountDbContext.Components.First(x => x.Id == componentControl.Info.Id); Assert.Equal(component.ExternalStatus.Status, status); } }
public static User GetAccountAdminUser(Guid accountId) { using (var accountContext = AccountDbContext.CreateFromAccountId(accountId)) { var repository = accountContext.GetUserRepository(); return(repository.GetAccountAdmin()); } }
public static void CheckMetricaStatus(Guid accountId, IComponentControl componentControl, string metricName, Core.Api.MonitoringStatus status) { using (var accountDbContext = AccountDbContext.CreateFromAccountId(accountId)) { var component = accountDbContext.Components.First(x => x.Id == componentControl.Info.Id); var metric = component.Metrics.Single(x => x.MetricType.SystemName == metricName && x.IsDeleted == false); Assert.Equal(metric.Bulb.Status, status); } }
public void ChangeImportanceTest() { var account = TestHelper.GetTestAccount(); var user = TestHelper.GetAccountAdminUser(account.Id); var eventType = TestHelper.GetTestEventType(account.Id); var component = account.CreateRandomComponentControl(); var dispatcher = DispatcherHelper.GetDispatcherService(); var eventRequest = new SendEventRequest() { Token = account.GetCoreToken(), Data = new SendEventData() { ComponentId = component.Info.Id, TypeSystemName = eventType.SystemName, Category = EventCategory.ComponentEvent, Version = "1.2.3.4", JoinInterval = TimeSpan.FromSeconds(0).TotalSeconds } }; var sendEventResponse = dispatcher.SendEvent(eventRequest); Assert.True(sendEventResponse.Success); var eventId = sendEventResponse.Data.EventId; var eventResponse = dispatcher.GetEventById(new GetEventByIdRequest() { Token = account.GetCoreToken(), Data = new GetEventByIdRequestData() { EventId = eventId } }); Assert.True(eventResponse.Success); var event_ = eventResponse.Data; ChangeImportanceModel model; using (var controller = new EventsController(account.Id, user.Id)) { var result = (ViewResultBase)controller.ChangeImportance(eventId); model = (ChangeImportanceModel)result.Model; } model.Importance = EventImportance.Warning; using (var controller = new EventsController(account.Id, user.Id)) { controller.ChangeImportance(model); } using (var accountContext = AccountDbContext.CreateFromAccountId(account.Id)) { var eventTypeRepository = accountContext.GetEventTypeRepository(); eventType = eventTypeRepository.GetById(model.EventTypeId); Assert.Equal(model.EventTypeId, eventType.Id); Assert.Equal(model.Version, event_.Version); Assert.Equal(model.Importance, eventType.ImportanceForOld); } }
public void QuickAddMobilePhoneTest() { var account = TestHelper.GetTestAccount(); var user = TestHelper.CreateTestUser(account.Id); var phone = "+7 (926) 666-77-88"; // Проверим, что у пользователя нет мобильного телефона с заданным номером using (var context = AccountDbContext.CreateFromAccountId(account.Id)) { var userRepository = context.GetUserRepository(); var dbUser = userRepository.GetById(user.Id); var hasMobilePhone = dbUser.UserContacts.Any(t => t.Type == UserContactType.MobilePhone && t.Value == phone); Assert.False(hasMobilePhone); } // Добавим мобильный телефон QuickSetMobilePhoneModel model; using (var controller = new HomeController(account.Id, user.Id)) { var result = (ViewResultBase)controller.QuickSetMobilePhone(); model = (QuickSetMobilePhoneModel)result.Model; } model.Phone = phone; using (var controller = new HomeController(account.Id, user.Id)) { var result = controller.QuickSetMobilePhone(model); Assert.IsAssignableFrom <RedirectResult>(result); } // Проверим, что телефон появился у пользователя using (var context = AccountDbContext.CreateFromAccountId(account.Id)) { var userRepository = context.GetUserRepository(); var dbUser = userRepository.GetById(user.Id); var hasMobilePhone = dbUser.UserContacts.Any(t => t.Type == UserContactType.MobilePhone && t.Value == phone); Assert.True(hasMobilePhone); } // Проверим, что подписки по sms включены var client = TestHelper.GetDispatcherClient(); var subscription = client.CreateSubscription(account.Id, new CreateSubscriptionRequestData() { Channel = SubscriptionChannel.Sms, UserId = user.Id, Object = SubscriptionObject.Default }).Data; Assert.True(subscription.IsEnabled); }
public void EditLevelsTest() { var account = TestHelper.GetTestAccount(); var component = account.CreateRandomComponentControl(); // Получим форму настроек EditLogModel model; var user = TestHelper.GetAccountAdminUser(account.Id); using (var controller = new LogsController(account.Id, user.Id, OutputRecordCount, SearchIterationRecordCount)) { var result = Assert.IsType <PartialViewResult>(controller.Edit(component.Info.Id)); model = Assert.IsType <EditLogModel>(result.Model); } Assert.True(model.IsTraceEnabled); Assert.True(model.IsDebugEnabled); Assert.True(model.IsInfoEnabled); Assert.True(model.IsWarningEnabled); Assert.True(model.IsErrorEnabled); Assert.True(model.IsFatalEnabled); // Заполним модель model.IsTraceEnabled = false; model.IsDebugEnabled = false; // Отправим данные JsonResult jsonResult; using (var controller = new LogsController(account.Id, user.Id, OutputRecordCount, SearchIterationRecordCount)) { jsonResult = Assert.IsType <JsonResult>(controller.Edit(model)); } var success = (bool)jsonResult.Data.GetType().GetProperty("success").GetValue(jsonResult.Data); Assert.True(success); // Проверим, что настройки поменялись using (var context = AccountDbContext.CreateFromAccountId(account.Id)) { var repository = context.GetLogConfigRepository(); var config = repository.GetByComponentId(component.Info.Id); Assert.False(config.IsTraceEnabled); Assert.False(config.IsDebugEnabled); Assert.True(config.IsInfoEnabled); Assert.True(config.IsWarningEnabled); Assert.True(config.IsErrorEnabled); Assert.True(config.IsFatalEnabled); } }
public void DeleteLastAdminTest() { // Удалим всех пользователей, кроме админа var account = TestHelper.GetTestAccount(); var admin = TestHelper.GetAccountAdminUser(account.Id); using (var context = AccountDbContext.CreateFromAccountId(account.Id)) { var userRepository = context.GetUserRepository(); foreach (var existingUser in userRepository.QueryAll().ToArray()) { if (existingUser.Id != admin.Id) { userRepository.Remove(existingUser); } } } // Создадим дополнительного пользователя (не админа) var password = PasswordHelper.GetRandomPassword(10); var user = TestHelper.CreateTestUser(account.Id, password); // Проверим, что в аккаунте 1 админ using (var context = AccountDbContext.CreateFromAccountId(account.Id)) { var userRepository = context.GetUserRepository(); var adminUsers = userRepository.QueryAll().Where(t => t.Roles.Any(x => x.RoleId == RoleId.AccountAdministrators)).ToArray(); Assert.Equal(1, adminUsers.Length); admin = adminUsers[0]; } // Проверим, что нельзя удалить единственного админа using (var contexts = new DatabasesContext()) { var service = new UserService(contexts); Assert.Throws <CantDeleteLastAdminException>(() => { service.DeleteUser(service.GetById(account.Id, admin.Id), account.Id); }); contexts.SaveChanges(); } // Проверим, что админ остался using (var context = AccountDbContext.CreateFromAccountId(account.Id)) { var userRepository = context.GetUserRepository(); var existingUser = userRepository.QueryAll().FirstOrDefault(t => t.Id == admin.Id); Assert.NotNull(existingUser); } }
public void CreateUserTest() { var account = TestHelper.GetTestAccount(); var password = PasswordHelper.GetRandomPassword(10); var user = TestHelper.CreateTestUser(account.Id, password); Assert.NotNull(user); // Проверим, что у нового пользователя по умолчанию включена отправка новостей using (var context = AccountDbContext.CreateFromAccountId(account.Id)) { var userSettingService = context.GetUserSettingService(); var sendMeNews = userSettingService.SendMeNews(user.Id); Assert.True(sendMeNews); } }
public void RemoveAdminRoleFromLastAdminTest() { // Удалим всех пользователей, кроме админа var account = TestHelper.GetTestAccount(); var admin = TestHelper.GetAccountAdminUser(account.Id); using (var context = AccountDbContext.CreateFromAccountId(account.Id)) { var userRepository = context.GetUserRepository(); foreach (var existingUser in userRepository.QueryAll().ToArray()) { if (existingUser.Id != admin.Id) { userRepository.Remove(existingUser); } } } // Проверим, что в аккаунте 1 админ using (var context = AccountDbContext.CreateFromAccountId(account.Id)) { var userRepository = context.GetUserRepository(); var adminUsers = userRepository.QueryAll().Where(t => t.Roles.Any(x => x.RoleId == RoleId.AccountAdministrators)).ToArray(); Assert.Equal(1, adminUsers.Length); admin = adminUsers[0]; } // Проверим, что нельзя удалить права админа у единственного админа using (var contexts = new DatabasesContext()) { var service = new UserService(contexts); Assert.Throws <CantRemoveAdminRoleFromLastAdmin>(() => { var existingAdmin = service.GetById(account.Id, admin.Id); service.RemoveUserRole(existingAdmin, existingAdmin.Roles.First(t => t.RoleId == RoleId.AccountAdministrators), account.Id); }); contexts.SaveChanges(); } // Проверим, что пользователь с правами администратора остался using (var context = AccountDbContext.CreateFromAccountId(account.Id)) { var userRepository = context.GetUserRepository(); var adminUsers = userRepository.QueryAll().Where(t => t.Roles.Any(x => x.RoleId == RoleId.AccountAdministrators)).ToArray(); Assert.Equal(1, adminUsers.Length); } }
public void EventTypeEditTest() { var account = TestHelper.GetTestAccount(); var user = TestHelper.GetAccountAdminUser(account.Id); var eventType = TestHelper.GetTestEventType(account.Id); EventTypeEditModel model; using (var controller = new EventTypesController(account.Id, user.Id)) { var result = (ViewResultBase)controller.Edit(eventType.Id); model = (EventTypeEditModel)result.Model; Assert.Equal(eventType.Id, model.Id); Assert.Equal(eventType.DisplayName, model.DisplayName); Assert.Equal(eventType.SystemName, model.SystemName); Assert.Equal(eventType.Category, model.Category); Assert.Equal(TimeSpanHelper.FromSeconds(eventType.JoinIntervalSeconds), model.JoinInterval); Assert.Equal(eventType.OldVersion, model.OldVersion); Assert.Equal(eventType.ImportanceForOld, model.ImportanceForOld); Assert.Equal(eventType.ImportanceForNew, model.ImportanceForNew); Assert.Equal(eventType.IsSystem, model.IsSystem); } model.DisplayName += "New"; model.SystemName += "New"; model.Category = EventCategory.ComponentEvent; model.JoinInterval = TimeSpanHelper.FromSeconds(10); model.OldVersion = "2.0.0.0"; model.ImportanceForOld = EventImportance.Alarm; model.ImportanceForNew = EventImportance.Warning; using (var controller = new EventTypesController(account.Id, user.Id)) { controller.Edit(model); } var accountContext = AccountDbContext.CreateFromAccountId(account.Id); var eventTypeRepository = accountContext.GetEventTypeRepository(); eventType = eventTypeRepository.GetById(model.Id); Assert.Equal(model.Id, eventType.Id); Assert.Equal(model.DisplayName, eventType.DisplayName); Assert.Equal(model.SystemName, eventType.SystemName); Assert.Equal(model.Category, eventType.Category); Assert.Equal(model.JoinInterval, TimeSpanHelper.FromSeconds(eventType.JoinIntervalSeconds)); Assert.Equal(model.OldVersion, eventType.OldVersion); Assert.Equal(model.ImportanceForOld, eventType.ImportanceForOld); Assert.Equal(model.ImportanceForNew, eventType.ImportanceForNew); Assert.Equal(model.IsSystem, eventType.IsSystem); }
public static EventType GetTestEventType(Guid accountId) { using (var accountContext = AccountDbContext.CreateFromAccountId(accountId)) { IEventTypeRepository eventTypeRepository = new EventTypeRepository(accountContext); var eventType = new EventType() { Category = Core.Api.EventCategory.ComponentEvent, DisplayName = "Тестовый тип события " + DateTime.Now.ToString("yyyy-MM-dd HH"), ImportanceForNew = Core.Api.EventImportance.Success, JoinIntervalSeconds = 5, SystemName = "EventType.Test " + DateTime.Now.ToString("yyyy-MM-dd HH") }; eventType = eventTypeRepository.GetOrCreate(eventType); return(eventType); } }
public static EventType GetOrCreateEventType( Guid accountId, Core.Api.EventCategory category, string systemName) { using (var accountDb = AccountDbContext.CreateFromAccountId(accountId)) { var eventType = new EventType() { SystemName = systemName, DisplayName = "display name for " + systemName, Category = category }; var type = accountDb.GetEventTypeRepository().GetOrCreate(eventType); return(type); } }
public JsonResult CheckExistingLogin(EditUserModel model) { var login = ConfigDbServicesHelper.GetLoginService().GetOneOrNull(CurrentUser.AccountId, model.Login); if (login != null) { using (var accountContext = AccountDbContext.CreateFromAccountId(login.Account.Id)) { var userRepository = accountContext.GetUserRepository(); var user = userRepository.GetOneOrNullByLogin(model.Login); if (user != null && user.Id != model.Id) { return(Json("Пользователь с таким EMail уже существует", JsonRequestBehavior.AllowGet)); } } } return(Json(true, JsonRequestBehavior.AllowGet)); }
public static MetricType CreateHddMetricType(Guid accountId) { using (var accountContext = AccountDbContext.CreateFromAccountId(accountId)) { var metricType = new MetricType() { Id = Guid.NewGuid(), IsDeleted = false, SystemName = "HDD." + Guid.NewGuid(), ConditionAlarm = "value < 1", ConditionWarning = "value < 10", ConditionElseColor = ObjectColor.Green, NoSignalColor = ObjectColor.Red }; accountContext.MetricTypes.Add(metricType); accountContext.SaveChanges(); return(metricType); } }
public void EventTypeDeleteTest() { var account = TestHelper.GetTestAccount(); var user = TestHelper.GetAccountAdminUser(account.Id); DeleteConfirmationModel model; string systemName; using (var accountContext = AccountDbContext.CreateFromAccountId(account.Id)) { var eventTypeRepository = new EventTypeRepository(accountContext); var eventType = new EventType() { Category = EventCategory.ComponentEvent, DisplayName = "Тестовый тип события " + DateTime.Now.Ticks, ImportanceForNew = EventImportance.Success, JoinIntervalSeconds = 0, SystemName = "EventType.Test " + DateTime.Now.Ticks }; eventType = eventTypeRepository.GetOrCreate(eventType); systemName = eventType.SystemName; using (var controller = new EventTypesController(account.Id, user.Id)) { var result = (ViewResultBase)controller.Delete(eventType.Id); model = (DeleteConfirmationModel)result.Model; } using (var controller = new EventTypesController(account.Id, user.Id)) { controller.Delete(model); } } using (var accountContext = AccountDbContext.CreateFromAccountId(account.Id)) { var eventTypeRepository = new EventTypeRepository(accountContext); var eventType = eventTypeRepository.GetById(Guid.Parse(model.Id)); Assert.NotNull(eventType); Assert.True(eventType.IsDeleted); eventType = eventTypeRepository.GetOneOrNullBySystemName(systemName); Assert.Null(eventType); } }
public void DeleteWithChilds() { var account = TestHelper.GetTestAccount(); var dispatcher = TestHelper.GetDispatcherClient(); // Создадим компонент var systemName = "Component." + Guid.NewGuid(); var getOrCreateComponentResponse = dispatcher.GetOrCreateComponent(account.Id, new GetOrCreateComponentRequestData() { TypeId = SystemComponentTypes.WebSite.Id, SystemName = systemName, DisplayName = systemName, ParentComponentId = account.RootId }); var component = getOrCreateComponentResponse.Data; // Создадим дочерний компонент var childSystemName = "Component." + Guid.NewGuid(); var getOrCreateChildComponentResponse = dispatcher.GetOrCreateComponent(account.Id, new GetOrCreateComponentRequestData() { TypeId = SystemComponentTypes.WebSite.Id, SystemName = childSystemName, DisplayName = childSystemName, ParentComponentId = component.Component.Id }); var child = getOrCreateChildComponentResponse.Data; // Удалим основной компонент dispatcher.DeleteComponent(account.Id, component.Component.Id); // Проверим, что оба компонента удалены using (var context = AccountDbContext.CreateFromAccountId(account.Id)) { var componentRepository = context.GetComponentRepository(); var componentFromDb = componentRepository.GetById(component.Component.Id); Assert.True(componentFromDb.IsDeleted); var childFromDb = componentRepository.GetById(child.Component.Id); Assert.True(childFromDb.IsDeleted); } }
public static void CheckActualStatusEventsCount(TestAccountInfo account, Guid ownerId) { account.SaveAllCaches(); var now = GetDispatcherClient().GetServerTime().Data.Date.AddSeconds(1); using (var storageDbContext = AccountDbContext.CreateFromAccountId(account.Id)) { var events = storageDbContext.Events .Where(x => x.OwnerId == ownerId && x.ActualDate > now) .ToList(); var categoryGroups = events.GroupBy(x => x.Category); foreach (var categoryGroup in categoryGroups) { var categoryEvents = categoryGroup.ToArray(); Assert.Equal(1, categoryEvents.Length); } } }
public void RepositorySetAndGetSettingTest() { var account = TestHelper.GetTestAccount(); var user = TestHelper.GetAccountAdminUser(account.Id); var name = "UserSetting " + DateTime.Now.Ticks; var value = "UserSettingValue " + DateTime.Now.Ticks; using (var accountContext = AccountDbContext.CreateFromAccountId(account.Id)) { var repository = accountContext.GetUserSettingRepository(); repository.SetValue(user.Id, name, value); accountContext.SaveChanges(); } using (var accountContext = AccountDbContext.CreateFromAccountId(account.Id)) { var repository = accountContext.GetUserSettingRepository(); var settingValue = repository.GetValue(user.Id, name); Assert.Equal(value, settingValue); } }
protected void InitMetricTypeRules(Guid accountId, Guid metricTypeId) { // Получим тип метрики и заполним ее правила using (var accountContext = AccountDbContext.CreateFromAccountId(accountId)) { var metricTypeRepository = accountContext.GetMetricTypeRepository(); var metricType = metricTypeRepository.GetById(metricTypeId); metricType.ConditionAlarm = "value <= 10"; metricType.ConditionWarning = "value <= 100"; metricType.ConditionSuccess = "value <= 1000"; metricType.ConditionElseColor = Core.Common.ObjectColor.Gray; accountContext.SaveChanges(); AllCaches.MetricTypes.Unload(new AccountCacheRequest() { AccountId = accountId, ObjectId = metricTypeId }); } }
public void DeleteTest() { var account = TestHelper.GetTestAccount(); var user = TestHelper.GetAccountAdminUser(account.Id); // Создадим компонент var componentInfo = account.CreateTestApplicationComponent(); // Удалим его using (var controller = new ComponentsController(account.Id, user.Id)) { controller.Delete(componentInfo.Id, "fake"); } // Проверим, что компонент удалился var accountContext = AccountDbContext.CreateFromAccountId(account.Id); var repository = accountContext.GetComponentRepository(); var component = repository.GetByIdOrNull(componentInfo.Id); Assert.NotNull(component); Assert.True(component.IsDeleted); }
public void EventTypeAddTest() { var account = TestHelper.GetTestAccount(); var user = TestHelper.GetAccountAdminUser(account.Id); EventTypeEditModel model; using (var controller = new EventTypesController(account.Id, user.Id)) { var result = (ViewResultBase)controller.Add(); model = (EventTypeEditModel)result.Model; } model.DisplayName = "New test event type " + Guid.NewGuid(); model.SystemName += model.DisplayName; model.Category = EventCategory.ComponentEvent; model.ImportanceForNew = EventImportance.Success; model.JoinInterval = TimeSpan.FromSeconds(10); model.OldVersion = "1.0.0.0"; model.ImportanceForOld = EventImportance.Alarm; model.ImportanceForNew = EventImportance.Warning; using (var controller = new EventTypesController(account.Id, user.Id)) { controller.Add(model); } var accountContext = AccountDbContext.CreateFromAccountId(account.Id); var eventTypeRepository = accountContext.GetEventTypeRepository(); var eventType = eventTypeRepository.GetOneOrNullBySystemName(model.SystemName); Assert.NotNull(eventType); Assert.Equal(model.DisplayName, eventType.DisplayName); Assert.Equal(model.SystemName, eventType.SystemName); Assert.Equal(model.Category, eventType.Category); Assert.Equal(model.JoinInterval, TimeSpanHelper.FromSeconds(eventType.JoinIntervalSeconds)); Assert.Equal(model.OldVersion, eventType.OldVersion); Assert.Equal(model.ImportanceForOld, eventType.ImportanceForOld); Assert.Equal(model.ImportanceForNew, eventType.ImportanceForNew); Assert.Equal(model.IsSystem, eventType.IsSystem); }
public void HttpProcessorTest() { var account = TestHelper.GetTestAccount(); var client = account.GetClient(); var component = account.CreateRandomComponentControl(); var unitTestType = client.GetOrCreateUnitTestTypeControl(SystemUnitTestTypes.HttpUnitTestType.SystemName); var unitTest = component.GetOrCreateUnitTestControl(unitTestType, "httpCheck"); Guid unitTestId = unitTest.Info.Id; using (var accountDbContext = AccountDbContext.CreateFromAccountId(account.Id)) { var unitTestObj = accountDbContext.UnitTests.Single(x => x.Id == unitTestId); var httpUnitTest = unitTestObj.HttpRequestUnitTest; var code = HttpRequestErrorCode.ErrorHtmlFound; httpUnitTest.Rules.Add(new HttpRequestUnitTestRule() { DisplayName = code.ToString(), Url = "http://fakesite.zidium.net/ok", ErrorHtml = "Все хорошо", TimeoutSeconds = 5 }); foreach (var rule in httpUnitTest.Rules) { rule.HttpRequestUnitTest = httpUnitTest; rule.HttpRequestUnitTestId = httpUnitTest.UnitTestId; rule.Id = Guid.NewGuid(); } accountDbContext.SaveChanges(); var processor = new HttpRequestsProcessor(LogManager.GetCurrentClassLogger(), new CancellationToken()); processor.ProcessAccount(account.Id, unitTestObj.Id); Assert.True(processor.SuccessCount >= 1); Assert.Equal(0, processor.ErrorCount); } }