Exemplo n.º 1
0
        public async Task Post_Stroes_Subscription_200()
        {
            // Arrange
            var logger = new Mock <ILogger <SubscriptionsController> >();

            var bookSubscriptionRepository = new Mock <IBookSubscriptionsRepository>();

            var bookRepository = new Mock <IBookRepository>();

            bookRepository.Setup(s => s.GetUserBookAsync(It.IsAny <string>(), It.IsAny <string>())).Returns(Task.FromResult(new BookServiceModel()
            {
                BookId = "IDDQD", Name = "The Bible", Price = 666.0, Text = "Text text"
            }));

            var context = new ControllerContext
            {
                HttpContext = new DefaultHttpContext {
                    User = new ClaimsPrincipal(new[] { new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "test_name_identifier") }) })
                }
            };

            var bookSubsController = new SubscriptionsController(logger.Object, bookSubscriptionRepository.Object, bookRepository.Object);

            bookSubsController.ControllerContext = context;

            // Act
            var postResponse = await bookSubsController.PostAsync("IDDQD");

            // Assert
            Assert.IsType <OkResult>(postResponse);
            bookSubscriptionRepository.Verify(v => v.SaveAsync(It.IsAny <BookSubscriptionServiceModel>()));
        }
Exemplo n.º 2
0
        public async Task Delete_Deletes_Subscription_200()
        {
            // Arrange
            var logger = new Mock <ILogger <SubscriptionsController> >();

            var bookSubscriptionRepository = new Mock <IBookSubscriptionsRepository>();

            bookSubscriptionRepository.Setup(s => s.DeleteAsync(It.IsAny <BookSubscriptionServiceModel>())).Returns(Task.FromResult(true));

            var bookRepository = new Mock <IBookRepository>();

            var context = new ControllerContext
            {
                HttpContext = new DefaultHttpContext {
                    User = new ClaimsPrincipal(new[] { new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "test_name_identifier") }) })
                }
            };

            var bookSubsController = new SubscriptionsController(logger.Object, bookSubscriptionRepository.Object, bookRepository.Object);

            bookSubsController.ControllerContext = context;

            // Act
            var deleteResponse = await bookSubsController.DeleteAsync("IDDQD");

            // Assert
            Assert.IsType <OkResult>(deleteResponse);
        }
Exemplo n.º 3
0
        private void ListActiveSubscriptionsButton_Click(object sender, EventArgs e)
        {
            var adminController     = new SubscriptionsController(Properties.Settings.Default);
            var activeSubscriptions = adminController.GetActiveSubscriptions();
            Dictionary <string, Dictionary <string, bool> > subscriptionIds = new Dictionary <string, Dictionary <string, bool> >();

            foreach (var subscription in activeSubscriptions)
            {
                Dictionary <string, bool> personRegistrationIds = new Dictionary <string, bool>();
                foreach (var personRegistrationId in subscription.PersonUuids)
                {
                    if (!personRegistrationIds.ContainsKey(personRegistrationId))
                    {
                        personRegistrationIds.Add(personRegistrationId, true);
                    }
                }
                subscriptionIds.Add(subscription.SubscriptionId, personRegistrationIds);
            }

            notificationResultsConsoleTextBox.Text = "";
            foreach (var personRegistrationSet in subscriptionIds)
            {
                notificationResultsConsoleTextBox.Text += "ID: " + personRegistrationSet.Key + "\r\n";
                foreach (var id in personRegistrationSet.Value.Keys)
                {
                    notificationResultsConsoleTextBox.Text += id;
                }
            }
        }
Exemplo n.º 4
0
        public async Task Post_Returns_404()
        {
            // Arrange
            var logger = new Mock <ILogger <SubscriptionsController> >();

            var bookSubscriptionRepository = new Mock <IBookSubscriptionsRepository>();

            var bookRepository = new Mock <IBookRepository>();

            var context = new ControllerContext
            {
                HttpContext = new DefaultHttpContext {
                    User = new ClaimsPrincipal(new[] { new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "test_name_identifier") }) })
                }
            };

            var bookSubsController = new SubscriptionsController(logger.Object, bookSubscriptionRepository.Object, bookRepository.Object);

            bookSubsController.ControllerContext = context;

            // Act
            var postResponse = await bookSubsController.PostAsync("IDDQD");

            // Assert
            Assert.IsType <NotFoundResult>(postResponse);
        }
Exemplo n.º 5
0
        public void CallUserServiceSubscribeForTeamsResultsMethod_WhenPassedTeamsNamesIsNotNull()
        {
            // arrange
            var contextMock = new Mock <ControllerContext>();

            contextMock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns("username");
            contextMock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);

            var userService             = new Mock <IUserService>();
            var subscriptionsController = new SubscriptionsController(userService.Object);

            var controller = new SubscriptionsController(userService.Object);

            controller.ControllerContext = contextMock.Object;

            var teams = new List <string>()
            {
                "someName"
            };

            // act
            controller.SubscribeForTeamResults(teams);

            // assert
            userService.Verify(u => u.SubscribeUserForTeamResults("username", teams), Times.Once);
        }
        public void EditTest()
        {
            // Создадим пользователя
            var account    = TestHelper.GetTestAccount();
            var user       = TestHelper.CreateTestUser(account.Id);
            var dispatcher = TestHelper.GetDispatcherClient();

            var channels = new[]
            {
                SubscriptionChannel.Email,
                SubscriptionChannel.Sms,
                SubscriptionChannel.Http
            };

            foreach (var channel in channels)
            {
                // Получим подписку по умолчанию
                var response = dispatcher.CreateSubscription(account.Id, new CreateSubscriptionRequestData()
                {
                    UserId  = user.Id,
                    Object  = SubscriptionObject.Default,
                    Channel = channel
                });
                var defaultSubscription = response.Data;

                // Изменим подписку по умолчанию
                SubscriptionEditModel model;
                using (var controller = new SubscriptionsController(account.Id, user.Id))
                {
                    var result = (ViewResultBase)controller.Edit(defaultSubscription.Id);
                    model = (SubscriptionEditModel)result.Model;
                }

                model.ReturnUrl       = "/";
                model.IsEnabled       = !model.IsEnabled;
                model.Color           = ColorStatusSelectorValue.FromEventImportance(EventImportance.Success);
                model.MinimumDuration = TimeSpan.FromSeconds(10);
                model.ResendTime      = TimeSpan.FromSeconds(20);

                using (var controller = new SubscriptionsController(account.Id, user.Id))
                {
                    controller.Edit(model);
                }

                // Проверим подписку по умолчанию
                var response2 = dispatcher.CreateSubscription(account.Id, new CreateSubscriptionRequestData()
                {
                    UserId  = user.Id,
                    Object  = SubscriptionObject.Default,
                    Channel = channel
                });
                var newDefaultSubscription = response2.Data;

                Assert.Equal(model.IsEnabled, newDefaultSubscription.IsEnabled);
                Assert.Equal(EventImportance.Success, newDefaultSubscription.Importance);
                Assert.Equal(10, newDefaultSubscription.DurationMinimumInSeconds);
                Assert.Equal(20, newDefaultSubscription.ResendTimeInSeconds);
            }
        }
Exemplo n.º 7
0
        public void Initialize()
        {
            this.subscriptionService = Substitute.For <ISubscriptionService>();
            this.mailingService      = Substitute.For <IMailingService>();
            this.topicsService       = Substitute.For <ITopicsService>();
            this.logger = Substitute.For <ILogger <SubscriptionsController> >();

            this.cut = new SubscriptionsController(this.subscriptionService, this.mailingService, this.topicsService, this.logger);
            this.MockControllerContext(requestScheme, requestHost);
        }
Exemplo n.º 8
0
        private bool TestEventUrl()
        {
            var  subscriptionsController = new SubscriptionsController(Properties.Settings.Default);
            bool testOk = subscriptionsController.TestWSConnection(eventBrokerWebServiceUrlTextBox.Text);

            if (!testOk)
            {
                MessageBox.Show(this, "Connection failed. The Event Broker Web Service URL is incorrect or the service is unavailable", "Connection failure", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(testOk);
        }
Exemplo n.º 9
0
        public void SetUp()
        {
            _id                 = Guid.NewGuid();
            _course             = CreateCourse();
            _studentDto         = CreateStudentDto();
            _mapperMock         = new Mock <IMapper>();
            _queueServiceMock   = new Mock <IPersistenceService <Student> >();
            _readRepositoryMock = new Mock <IReadRepository <Course> >();
            _controller         = new SubscriptionsController(_mapperMock.Object, _readRepositoryMock.Object, _queueServiceMock.Object);

            _readRepositoryMock.Setup(mock => mock.FindSingleBy(It.IsAny <Expression <Func <Course, bool> > >(), It.IsAny <string[]>())).Returns(_course);
            _readRepositoryMock.Setup(mock => mock.FindSingleByAsync(It.IsAny <Expression <Func <Course, bool> > >(), It.IsAny <string[]>())).ReturnsAsync(_course);
        }
Exemplo n.º 10
0
        void Start()
        {
            SubscriptionsController subsController = FindObjectOfType <SubscriptionsController>();

            if (subsController == null)
            {
                Debug.LogWarning("No SubscriptionController and/or TimeSync found. Missing 'DontDestory' on Pupil Connection object?");
                return;
            }

            gazeCtrl.subscriptionsController = subsController;
            gazeCtrl.enabled = true;
        }
Exemplo n.º 11
0
        public void RedirectToIndexAction_WhenPassedTeamsNamesAreNull()
        {
            // arrange
            var userService             = new Mock <IUserService>();
            var subscriptionsController = new SubscriptionsController(userService.Object);

            // act
            subscriptionsController.SubscribeForTeamResults(null);

            // assert
            subscriptionsController.WithCallTo(c => c.SubscribeForTeamResults(null))
            .ShouldRedirectTo(c => c.Index());
        }
        public async Task Then_If_Error_Then_Internal_Server_Error_Response(
            string accountType,
            string accountIdentifier,
            [Frozen] Mock <IMediator> mediator,
            [Greedy] SubscriptionsController controller)
        {
            mediator.Setup(x => x.Send(It.IsAny <GetApiProductSubscriptionsQuery>(),
                                       CancellationToken.None)).ThrowsAsync(new Exception());

            var actual = await controller.GetAvailableProducts(accountIdentifier, accountType) as StatusCodeResult;

            Assert.IsNotNull(actual);
            actual.StatusCode.Should().Be((int)HttpStatusCode.InternalServerError);
        }
        public async Task Then_The_Request_Is_Handled_And_Created_Result_Returned(
            string accountType,
            string accountIdentifier,
            string productId,
            [Frozen] Mock <IMediator> mediator,
            [Greedy] SubscriptionsController controller)
        {
            await controller.CreateProductSubscription(accountIdentifier, productId, accountType);

            mediator.Verify(x => x.Send(It.Is <CreateSubscriptionKeyCommand>(c =>
                                                                             c.AccountIdentifier.Equals(accountIdentifier) &&
                                                                             c.AccountType.Equals(accountType) &&
                                                                             c.ProductId.Equals(productId)), CancellationToken.None), Times.Once);
        }
        public async Task Then_If_Validation_Error_Then_Request_Error_Response_Is_Returned(
            string accountType,
            string accountIdentifier,
            string productId,
            [Frozen] Mock <IMediator> mediator,
            [Greedy] SubscriptionsController controller)
        {
            mediator.Setup(x => x.Send(It.IsAny <CreateSubscriptionKeyCommand>(),
                                       CancellationToken.None)).ThrowsAsync(new HttpRequestContentException("error message", HttpStatusCode.BadRequest, "error"));

            var actual = await controller.CreateProductSubscription(accountIdentifier, productId, accountType) as ObjectResult;

            Assert.IsNotNull(actual);
            actual.StatusCode.Should().Be((int)HttpStatusCode.BadRequest);
        }
Exemplo n.º 15
0
        public async Task Then_If_There_Is_An_Error_A_ServerError_Is_Returned(
            string id,
            string productId,
            [Frozen] Mock <IMediator> mockMediator,
            [Greedy] SubscriptionsController controller)
        {
            mockMediator.Setup(x => x.Send(
                                   It.IsAny <RenewSubscriptionKeyCommand>(),
                                   CancellationToken.None))
            .ThrowsAsync(new ApplicationException());

            var controllerResult = await controller.RenewSubscriptionKey(id, productId) as IStatusCodeActionResult;

            controllerResult !.StatusCode.Should().Be((int)HttpStatusCode.InternalServerError);
        }
Exemplo n.º 16
0
        public async Task Then_If_There_Is_A_HttpException_It_Is_Returned(
            string errorContent,
            string id,
            string productId,
            [Frozen] Mock <IMediator> mockMediator,
            [Greedy] SubscriptionsController controller)
        {
            mockMediator.Setup(x => x.Send(
                                   It.IsAny <RenewSubscriptionKeyCommand>(),
                                   CancellationToken.None))
            .ThrowsAsync(new HttpRequestContentException("Error", HttpStatusCode.BadRequest, errorContent));

            var controllerResult = await controller.RenewSubscriptionKey(id, productId) as ObjectResult;

            controllerResult !.StatusCode.Should().Be((int)HttpStatusCode.BadRequest);
            controllerResult.Value.Should().Be(errorContent);
        }
Exemplo n.º 17
0
        public void AdminTest()
        {
            // Создадим пользователя
            var account = TestHelper.GetTestAccount();
            var user    = TestHelper.CreateTestUser(account.Id);
            var admin   = TestHelper.GetAccountAdminUser(account.Id);

            // Проверим, что админ может видеть чужие подписки
            SubscriptionListModel model;

            using (var controller = new SubscriptionsController(account.Id, admin.Id))
            {
                // прочитаем подписки админа
                var result = (ViewResultBase)controller.Index(user.Id);
                model = (SubscriptionListModel)result.Model;
            }
            Assert.Equal(user.Id, model.UserId);
            Assert.True(model.Subscriptions.Length > 0);
            Assert.True(model.Subscriptions.All(t => t.UserId == user.Id));

            // откроем подписку админа на редактирование
            var userSubscription            = model.Subscriptions.First();
            SubscriptionEditModel editModel = null;

            using (var controller = new SubscriptionsController(account.Id, user.Id))
            {
                var result = (ViewResultBase)controller.Edit(userSubscription.Id);
                editModel = (SubscriptionEditModel)result.Model;
                Assert.Null(editModel.MinimumDuration);
            }

            // сохраним изменения в подписке пользователя
            using (var controller = new SubscriptionsController(account.Id, admin.Id))
            {
                editModel.MinimumDuration = TimeSpan.FromSeconds(10);
                controller.Edit(editModel);
            }

            // проверим, что настройки подписки изменились
            using (var accountDbContext = account.CreateAccountDbContext())
            {
                var subscription = accountDbContext.Subscriptions.Find(userSubscription.Id);
                Assert.Equal(10, subscription.DurationMinimumInSeconds);
            }
        }
Exemplo n.º 18
0
        private void subscribeCprButton_Click(object sender, EventArgs e)
        {
            ConsoleWriteLine("Subscribing.....");
            var t = Properties.Settings.Default.NotificationMode;
            var adminController = new SubscriptionsController(Properties.Settings.Default);

            string result = adminController.Subscribe(notificationPersonsTextBox.Lines);

            if (result.Length > 0)
            {
                ConsoleWriteLine("Suceeded!");
                ConsoleWriteLine("Subscription ID: " + result);
            }
            else
            {
                ConsoleWriteLine("FAILED!!!");
            }
        }
Exemplo n.º 19
0
        public void ReturnJsonArrayResult_WhenInvoked()
        {
            // arrange
            var contextMock = new Mock <ControllerContext>();

            contextMock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns("username");
            contextMock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);

            var userService             = new Mock <IUserService>();
            var subscriptionsController = new SubscriptionsController(userService.Object);

            // act
            subscriptionsController.RemoveSubscription(null);

            // assert
            subscriptionsController.WithCallTo(c => c.RemoveSubscription(null))
            .ShouldReturnJson();
        }
        public async Task Then_The_Request_Is_Handled_And_Data_Returned(
            string accountType,
            string accountIdentifier,
            GetApiProductSubscriptionsQueryResult mediatorResult,
            [Frozen] Mock <IMediator> mediator,
            [Greedy] SubscriptionsController controller)
        {
            mediator.Setup(x => x.Send(It.Is <GetApiProductSubscriptionsQuery>(c =>
                                                                               c.AccountType.Equals(accountType) &&
                                                                               c.AccountIdentifier.Equals(accountIdentifier)
                                                                               ),
                                       CancellationToken.None)).ReturnsAsync(mediatorResult);

            var actual = await controller.GetAvailableProducts(accountIdentifier, accountType) as OkObjectResult;

            Assert.IsNotNull(actual);
            var actualModel = actual.Value as ProductSubscriptionsApiResponse;

            Assert.IsNotNull(actualModel);
        }
Exemplo n.º 21
0
        public async Task Then_The_Command_Sent(
            string id,
            string productId,
            [Frozen] Mock <IMediator> mockMediator,
            [Greedy] SubscriptionsController controller)
        {
            mockMediator.Setup(x => x.Send(It.Is <RenewSubscriptionKeyCommand>(c =>
                                                                               c.AccountIdentifier.Equals(id) &&
                                                                               c.ProductId.Equals(productId)
                                                                               ), CancellationToken.None))
            .ReturnsAsync(Unit.Value);

            var actual = await controller.RenewSubscriptionKey(id, productId) as IStatusCodeActionResult;

            actual !.StatusCode.Should().Be((int)HttpStatusCode.NoContent);
            mockMediator.Verify(x => x.Send(It.Is <RenewSubscriptionKeyCommand>(c =>
                                                                                c.AccountIdentifier.Equals(id) &&
                                                                                c.ProductId.Equals(productId)
                                                                                ), CancellationToken.None),
                                Times.Once);
        }
        public async Task Then_If_Null_Returned_NotFound_Result_Returned(string accountType,
                                                                         string accountIdentifier,
                                                                         string productId,
                                                                         GetApiProductSubscriptionQueryResult mediatorResult,
                                                                         [Frozen] Mock <IMediator> mediator,
                                                                         [Greedy] SubscriptionsController controller)
        {
            mediatorResult.Product      = null;
            mediatorResult.Subscription = null;
            mediator.Setup(x => x.Send(It.Is <GetApiProductSubscriptionQuery>(c =>
                                                                              c.AccountType.Equals(accountType) &&
                                                                              c.AccountIdentifier.Equals(accountIdentifier) &&
                                                                              c.ProductId.Equals(productId)
                                                                              ),
                                       CancellationToken.None)).ReturnsAsync(mediatorResult);

            var actual = await controller.GetProductSubscription(accountIdentifier, productId, accountType) as NotFoundResult;

            Assert.IsNotNull(actual);
            actual.StatusCode.Should().Be((int)HttpStatusCode.NotFound);
        }
Exemplo n.º 23
0
        public void MockControllerSetUp()
        {
            var optionsBuilder = new DbContextOptionsBuilder <NewsfeedContext>();

            optionsBuilder.UseInMemoryDatabase("fakeDb");
            fakeContext = new NewsfeedContext(optionsBuilder.Options);

            fakeContext.Users = DbContextHelper.GetQueryableMockDbSet
                                (
                new User()
            {
                Id            = 1,
                Subscriptions = { new Subscription {
                                      UserId = 1, DigestId = 1
                                  } }
            },
                new User()
            {
                Id = 2
            }
                                );

            fakeContext.Digests = DbContextHelper.GetQueryableMockDbSet
                                  (
                new Digest()
            {
                Id = 1, CreatorId = 1
            },
                new Digest()
            {
                Id = 2, CreatorId = 1
            },
                new Digest()
            {
                Id = 3, CreatorId = 2, IsPublic = false
            }
                                  );

            controller = new SubscriptionsController(fakeContext);
        }
Exemplo n.º 24
0
        private void BirthDaySubscriptionButton_Click(object sender, EventArgs e)
        {
            var adminController = new SubscriptionsController(Properties.Settings.Default);
            int?age             = (int)AgeSpin.Value;

            if (IgnoreAgeCheckBox.Checked)
            {
                age = null;
            }
            var result = adminController.SubscribeBirthdate(age, (int)PriorDaysSpin.Value,
                                                            notificationPersonsTextBox.Lines);

            if (result.Length > 0)
            {
                ConsoleWriteLine("Suceeded!");
                ConsoleWriteLine("Subscription ID: " + result);
            }
            else
            {
                ConsoleWriteLine("FAILED!!!");
            }
        }
Exemplo n.º 25
0
    public void Start()
    {
        subscriptionsController = FindObjectOfType <SubscriptionsController>();

        if (pupilListener == null)
        {
            pupilListener = new PupilListener(subscriptionsController);
        }
        if (gazeListener == null)
        {
            gazeListener = new GazeListener(subscriptionsController);
        }

        pupilListener.Enable();
        gazeListener.Enable();

        pupilListener.OnReceivePupilData += ReceiveData;
        gazeListener.OnReceive3dGaze     += ReceiveGazeData;
        ControllerManager.instance.Grab  += ReceiveControllerData;

        recorder.StartRecording();
        recording = true;
    }
Exemplo n.º 26
0
        public void CallUserServiceRemoveSubscriptionMethodWithValidUsernameAndTeamName_WhenInvokedWithValidModel()
        {
            // arrange
            var contextMock = new Mock <ControllerContext>();

            contextMock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns("username");
            contextMock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);

            var userService = new Mock <IUserService>();

            var subscriptionsController = new SubscriptionsController(userService.Object);

            subscriptionsController.ControllerContext = contextMock.Object;

            // act
            subscriptionsController.RemoveSubscription(new TeamSubscriptionViewModel()
            {
                Name = "TeamName"
            });

            // assert
            userService.Verify(u => u.RemoveSubscription("username", "TeamName"), Times.Once);
        }
Exemplo n.º 27
0
        public void ChangeColorTest()
        {
            var channels = new[]
            {
                SubscriptionChannel.Email,
                SubscriptionChannel.Sms,
                SubscriptionChannel.Http
            };

            foreach (var channel in channels)
            {
                // Создадим пользователя
                var account    = TestHelper.GetTestAccount();
                var user       = TestHelper.CreateTestUser(account.Id);
                var dispatcher = TestHelper.GetDispatcherClient();

                // Создадим тип компонента
                var componentType = TestHelper.CreateRandomComponentType(account.Id);

                // Настроим подписку по умолчанию и подписку на тип
                var response1 = dispatcher.CreateSubscription(account.Id, new CreateSubscriptionRequestData()
                {
                    UserId  = user.Id,
                    Object  = SubscriptionObject.Default,
                    Channel = channel
                });
                var data1     = response1.Data;
                var response2 = dispatcher.UpdateSubscription(account.Id, new UpdateSubscriptionRequestData()
                {
                    Id         = data1.Id,
                    IsEnabled  = true,
                    Importance = EventImportance.Warning
                });
                response2.Check();

                var response3 = dispatcher.CreateSubscription(account.Id, new CreateSubscriptionRequestData()
                {
                    UserId          = user.Id,
                    Object          = SubscriptionObject.ComponentType,
                    ComponentTypeId = componentType.Id,
                    Channel         = channel
                });
                var data3     = response3.Data;
                var response4 = dispatcher.UpdateSubscription(account.Id, new UpdateSubscriptionRequestData()
                {
                    Id         = data3.Id,
                    IsEnabled  = true,
                    Importance = EventImportance.Warning
                });
                response4.Check();

                // Поменяем цвет подписок на красный
                using (var controller = new SubscriptionsController(account.Id, user.Id))
                {
                    controller.Color(data1.Id + "," + data3.Id, ObjectColor.Red.ToString(), user.Id, channel);
                }

                // Проверим, что цвет подписок стал красным
                var response5 = dispatcher.CreateSubscription(account.Id, new CreateSubscriptionRequestData()
                {
                    UserId  = user.Id,
                    Object  = SubscriptionObject.Default,
                    Channel = channel
                });
                var data5 = response5.Data;
                Assert.Equal(EventImportance.Alarm, data5.Importance);

                var response6 = dispatcher.CreateSubscription(account.Id, new CreateSubscriptionRequestData()
                {
                    UserId          = user.Id,
                    ComponentTypeId = componentType.Id,
                    Object          = SubscriptionObject.ComponentType,
                    Channel         = channel
                });
                var data6 = response6.Data;
                Assert.Equal(EventImportance.Alarm, data6.Importance);
            }
        }
Exemplo n.º 28
0
        public void ChangeEnableTest()
        {
            // Создадим пользователя
            var account    = TestHelper.GetTestAccount();
            var user       = TestHelper.CreateTestUser(account.Id);
            var dispatcher = TestHelper.GetDispatcherClient();

            // Создадим тип компонента
            var componentType = TestHelper.CreateRandomComponentType(account.Id);

            var channels = new[]
            {
                SubscriptionChannel.Email,
                SubscriptionChannel.Sms,
                SubscriptionChannel.Http
            };

            foreach (var channel in channels)
            {
                // Настроим подписку по умолчанию и подписку на тип
                var response1 = dispatcher.CreateSubscription(account.Id, new CreateSubscriptionRequestData()
                {
                    UserId  = user.Id,
                    Object  = SubscriptionObject.Default,
                    Channel = channel
                });
                var data1     = response1.Data;
                var response2 = dispatcher.UpdateSubscription(account.Id, new UpdateSubscriptionRequestData()
                {
                    Id         = data1.Id,
                    IsEnabled  = true,
                    Importance = EventImportance.Warning
                });
                response2.Check();

                var response3 = dispatcher.CreateSubscription(account.Id, new CreateSubscriptionRequestData()
                {
                    UserId          = user.Id,
                    Object          = SubscriptionObject.ComponentType,
                    Channel         = channel,
                    ComponentTypeId = componentType.Id
                });
                var data3     = response3.Data;
                var response4 = dispatcher.UpdateSubscription(account.Id, new UpdateSubscriptionRequestData()
                {
                    Id         = data3.Id,
                    IsEnabled  = true,
                    Importance = EventImportance.Warning
                });
                response4.Check();

                // Выключим обе подписки
                using (var controller = new SubscriptionsController(account.Id, user.Id))
                {
                    controller.Enable(data1.Id + "," + data3.Id, false, user.Id, channel);
                }

                // Проверим, что подписки выключены
                var response5 = dispatcher.CreateSubscription(account.Id, new CreateSubscriptionRequestData()
                {
                    UserId  = user.Id,
                    Object  = SubscriptionObject.Default,
                    Channel = channel
                });
                var data5 = response5.Data;
                Assert.False(data5.IsEnabled);

                var response6 = dispatcher.CreateSubscription(account.Id, new CreateSubscriptionRequestData()
                {
                    UserId          = user.Id,
                    Object          = SubscriptionObject.ComponentType,
                    ComponentTypeId = componentType.Id,
                    Channel         = channel
                });
                var data6 = response6.Data;
                Assert.False(data6.IsEnabled);

                // Включим обе подписки
                using (var controller = new SubscriptionsController(account.Id, user.Id))
                {
                    controller.Enable(data1.Id + "," + data3.Id, true, user.Id, channel);
                }

                // Проверим, что подписки включены
                var response7 = dispatcher.CreateSubscription(account.Id, new CreateSubscriptionRequestData()
                {
                    UserId  = user.Id,
                    Object  = SubscriptionObject.Default,
                    Channel = channel
                });
                var data7 = response7.Data;
                Assert.True(data7.IsEnabled);

                var response8 = dispatcher.CreateSubscription(account.Id, new CreateSubscriptionRequestData()
                {
                    UserId          = user.Id,
                    Object          = SubscriptionObject.ComponentType,
                    Channel         = channel,
                    ComponentTypeId = componentType.Id
                });
                var data8 = response8.Data;
                Assert.True(data8.IsEnabled);
            }
        }
Exemplo n.º 29
0
 private async void TenantGetSubMappingsTest()
 {
     string [] subId = { "c438fe96-7cc3-43a1-ac87-c2795a6eea79" };
     var       tc    = new SubscriptionsController();
     var       resp  = tc.GetSubscriptionList(subId);
 }