Beispiel #1
0
        public async Task <BaseResultType <PrepareItemResult <TEntity> > > Execute(TParam paramOfCRUDOperation)
        {
            BaseResultType <PrepareItemResult <TEntity> > prepareItemResult = new BaseResultType <PrepareItemResult <TEntity> >()
            {
                Data = new PrepareItemResult <TEntity>()
                {
                    Item = paramOfCRUDOperation.Item, Question = paramOfCRUDOperation.Questions
                }, Question = paramOfCRUDOperation.Questions
            };

            paramOfCRUDOperation.Item      = prepareItemResult.Data.Item;
            paramOfCRUDOperation.Questions = paramOfCRUDOperation.Questions;

            if (prepareItemResult.Status == ResultStatus.Fail)
            {
                throw new ArgumentException(prepareItemResult.Message);
            }
            prepareItemResult.Data.Question = prepareItemResult.Question;

            if (!IsOnlyAddInContext)
            {
                await _repository.Save(paramOfCRUDOperation);
            }


            return(prepareItemResult);
        }
Beispiel #2
0
        public void AddLogTest(long?id)
        {
            RepositoryAddItem <ObjectMappingForTest, AddParamOfCRUDOperation <ObjectMappingForTest> > repositoryItem = new RepositoryAddItem <ObjectMappingForTest, AddParamOfCRUDOperation <ObjectMappingForTest> >(_uow, context);

            CreateContext();
            //ARRANGE
            LogTest logTestClass = new LogTest();

            Assert.AreEqual(0, logTestClass.LogItemsCollection.Count);//Пустые логи
            HandlerCRUD <ObjectMappingForTest, AddParamOfCRUDOperation <ObjectMappingForTest> > processingObjectTestCalss = new HandlerCRUD <ObjectMappingForTest, AddParamOfCRUDOperation <ObjectMappingForTest> >(repositoryItem);
            ObjectMappingForTest item = new ObjectMappingForTest()
            {
                IntValue = 22, IntValue2 = 33
            };

            if (id != null)
            {
                item.Id = (long)id;
            }
            //ACT

            LogerCRUDBLLDecoratorDecorator <ObjectMappingForTest, AddParamOfCRUDOperation <ObjectMappingForTest> > processingObjectLogDecorator = new LogerCRUDBLLDecoratorDecorator <ObjectMappingForTest, AddParamOfCRUDOperation <ObjectMappingForTest> >(processingObjectTestCalss, logTestClass);
            BaseResultType <PrepareItemResult <ObjectMappingForTest> > resultSave = processingObjectLogDecorator.Execute(new AddParamOfCRUDOperation <ObjectMappingForTest>()
            {
                Item = item
            }).Result;

            //ASSERT
            Assert.AreEqual(ResultStatus.Success, resultSave.Status);
            Assert.AreEqual(1, logTestClass.GetCount());//Лог добавился
        }
 public Task <BaseResultType <User> > LoginAllowCheckAsync(DefaultParamOfCRUDOperation <User> param)
 {
     return(Task.Run(() =>
     {
         BaseResultType <User> resultType = new BaseResultType <User>();
         if (param is null || param.Item is null)
         {
             resultType.AddError("Отсутствует параметр проверки пользователя.");
         }
        public async override Task <BaseResultType <PrepareItemResult <TEntity> > > Execute(DeleteParamOfCRUDOperation <TEntity> paramOfCRUDOperation)
        {
            BaseResultType <PrepareItemResult <TEntity> > result = await _handlerCRUD.Execute(paramOfCRUDOperation);

            if (result.Status == ResultStatus.Success)
            {
                await _cache.DeleteAsync(result.Data.Item);
            }

            return(result);
        }
        //   [ValidateAntiForgeryToken]
        public async Task <IActionResult> Registration(AddParamOfCRUDOperation <UserDTO> param)
        {
            BaseResultType result = await _accountService.RegisterAsync(param);

            if (result.Status == ResultStatus.Success)
            {
                await Authenticate(param.Item); // аутентификация
            }

            return(Json(result));
        }
        public void LoginAsyncTest_EmptyParam()
        {
            // ARRANGE
            RepositoryAddItem <User, AddParamOfCRUDOperation <User> > repositoryAddItem = new RepositoryAddItem <User, AddParamOfCRUDOperation <User> >(_uow, context);
            AccountService accountService = new AccountService(_uow, repositoryAddItem);

            // ACT
            BaseResultType result = accountService.LoginAllowCheckAsync(new DefaultParamOfCRUDOperation <UserDTO>()).Result;

            //ASSERT
            Assert.IsTrue(result.Status == ResultStatus.Fail);
        }
        // [ValidateAntiForgeryToken]
        public async Task <IActionResult> Login(DefaultParamOfCRUDOperation <UserDTO> param)
        {
            BaseResultType <User> result = await _accountService.LoginAllowCheckAsync(param);

            if (result.Status == ResultStatus.Success)
            {
                param.Item.Id = result.Data.Id;
                await Authenticate(param.Item); // аутентификация
            }

            return(Json(result));
        }
        public void AddErrorTest()
        {
            BaseResultType baseResultType = new BaseResultType();

            baseResultType.Status = ResultStatus.Fail;
            baseResultType.AddError("Error1");
            Assert.AreEqual("Error1", baseResultType.Message);
            Assert.AreEqual(ResultStatus.Fail, baseResultType.Status, "При добавлении ошибки,IsSuccess  должен меняться на false.");

            baseResultType.Status = ResultStatus.Success;
            baseResultType.AddError("Error2");
            Assert.AreEqual("Error1" + Environment.NewLine + "Error2", baseResultType.Message);
            Assert.AreEqual(ResultStatus.Fail, baseResultType.Status, "При добавлении ошибки,IsSuccess  должен меняться на false.");
        }
        public void AddMessageTest()
        {
            BaseResultType baseResultType = new BaseResultType();

            baseResultType.Status = ResultStatus.Fail;
            baseResultType.AddMessage("Message1");
            Assert.AreEqual("Message1", baseResultType.Message);
            Assert.AreEqual(ResultStatus.Fail, baseResultType.Status, "При добавлении сообщения,IsSuccess не должен меняться. Добавялется только сообщение.");

            baseResultType.Status = ResultStatus.Success;
            baseResultType.AddMessage("Message2");
            Assert.AreEqual("Message1" + Environment.NewLine + "Message2", baseResultType.Message);
            Assert.AreEqual(ResultStatus.Success, baseResultType.Status, "При добавлении сообщения,IsSuccess не должен меняться. Добавялется только сообщение.");
        }
        public async Task <IActionResult> Logout()
        {
            BaseResultType result = new BaseResultType()
            {
                Status = ResultStatus.Success
            };

            try
            {
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
            catch (Exception e)
            {
                result.AddError(e.Message);
            }
            return(Json(result));
        }
        // [DataRow("123l.ru", "pass", ResultStatus.Fail)] //TODO: Добавить проверку корректности почты
        public void LoginAsyncTest_CheckUser(string email, string password, ResultStatus resultCheck)
        {
            // ARRANGE
            RepositoryAddItem <User, AddParamOfCRUDOperation <User> > repositoryAddItem = new RepositoryAddItem <User, AddParamOfCRUDOperation <User> >(_uow, context);

            AccountService accountService = new AccountService(_uow, repositoryAddItem);
            DefaultParamOfCRUDOperation <UserDTO> userParam = new DefaultParamOfCRUDOperation <UserDTO>();

            userParam.Item          = new UserDTO();
            userParam.Item.Email    = email;
            userParam.Item.Password = password;

            // ACT
            BaseResultType result = accountService.LoginAllowCheckAsync(userParam).Result;

            //ASSERT
            Assert.IsTrue(result.Status == resultCheck);
        }
        public void RegisterAsyncTest()
        {
            // ARRANGE
            RepositoryAddItem <User, AddParamOfCRUDOperation <User> > repositoryAddItem = new RepositoryAddItem <User, AddParamOfCRUDOperation <User> >(_uow, context);
            AccountService accountService = new AccountService(_uow, repositoryAddItem);
            AddParamOfCRUDOperation <UserDTO> userParam = new AddParamOfCRUDOperation <UserDTO>();

            userParam.Item          = new UserDTO();
            userParam.Item.Email    = "*****@*****.**";
            userParam.Item.Password = "******";
            int countUsersInDB = context.Users.CountAsync().Result;

            // ACT
            BaseResultType result = accountService.RegisterAsync(userParam).Result;

            //ASSERT
            Assert.IsTrue(result.Status == ResultStatus.Success);
            Assert.IsTrue(context.Users.CountAsync().Result == countUsersInDB + 1);
        }
            public BaseResultType Validate(DefaultParamOfCRUDOperation <ObjectMappingForTest> item)
            {
                BaseResultType baseResultType = new BaseResultType()
                {
                    Status = ResultStatus.Success
                };

                if (String.IsNullOrWhiteSpace(item.Item.StrValue))
                {
                    WarningQuestion question = new WarningQuestion()
                    {
                        Id      = "1",
                        Message = "Отсутствует строка"
                    };
                    baseResultType.AddWarring(question);
                }

                return(baseResultType);
            }
        public void GetByIdTest()
        {
            CreateContext();
            DefaultController <ObjectMappingForTest> defaultController = new DefaultController <ObjectMappingForTest>(new FakeLogger(), new FetchDomainData <ObjectMappingForTest>(_uow), null, null, null);

            var exArgumentException = Assert.ThrowsExceptionAsync <ArgumentException>(() => defaultController.GetByIdAsync(10));

            Assert.AreEqual("Запись не найдена.", exArgumentException.Result.Message);

            //Проверка успешного получения записи

            JsonResult resultGetById = defaultController.GetByIdAsync(3).Result;
            BaseResultType <ObjectMappingForTest> resultSuccessQuery = (BaseResultType <ObjectMappingForTest>)resultGetById.Value;

            Assert.AreEqual(ResultStatus.Success, resultSuccessQuery.Status);
            Assert.IsNotNull(resultSuccessQuery.Data);
            Assert.AreEqual(3, resultSuccessQuery.Data.Id);
            Assert.AreEqual(23, resultSuccessQuery.Data.IntValue);
            Assert.AreEqual("23", resultSuccessQuery.Data.StrValue);
        }
        public void MergeTest()
        {
            //TODO: дописать тесты для вопросов
            BaseResultType error = new BaseResultType();

            error.Status = ResultStatus.Fail;
            error.AddError("Error");

            BaseResultType message = new BaseResultType();

            message.Status = ResultStatus.Success;
            message.AddMessage("Message");

            //При merge, IsSuccess не должен изменяться из fail в success, но должен меняться из success в fail. Если была ошибка, то ошибка должна остаться
            error.Merge(message);
            Assert.AreEqual(ResultStatus.Fail, error.Status);
            Assert.AreEqual("Error" + Environment.NewLine + "Message", error.Message);

            error.Message = "Error";//Сьрасываем сообщение на исходное
            message.Merge(error);
            Assert.AreEqual(ResultStatus.Fail, error.Status);
            Assert.AreEqual("Message" + Environment.NewLine + "Error", message.Message);
        }
        public void AddTest()
        {
            CreateContext();
            DefaultController <ObjectMappingForTest> defaultController = new DefaultController <ObjectMappingForTest>(new FakeLogger(),
                                                                                                                      new FetchDomainData <ObjectMappingForTest>(_uow),
                                                                                                                      new HandlerCRUD <ObjectMappingForTest, AddParamOfCRUDOperation <ObjectMappingForTest> >(new RepositoryAddItem <ObjectMappingForTest, AddParamOfCRUDOperation <ObjectMappingForTest> >(_uow, context)),
                                                                                                                      new HandlerCRUD <ObjectMappingForTest, EditParamOfCRUDOperation <ObjectMappingForTest> >(new RepositoryEditItem <ObjectMappingForTest, EditParamOfCRUDOperation <ObjectMappingForTest> >(_uow, context)),
                                                                                                                      new HandlerCRUD <ObjectMappingForTest, DeleteParamOfCRUDOperation <ObjectMappingForTest> >(new RepositoryDeleteItem <ObjectMappingForTest, DeleteParamOfCRUDOperation <ObjectMappingForTest> >(_uow, context)));

            AddParamOfCRUDOperation <ObjectMappingForTest> paramQueryAdd = new AddParamOfCRUDOperation <ObjectMappingForTest>();

            paramQueryAdd.Item = new ObjectMappingForTest()
            {
                IntValue = 1, IntValue2 = 1, StrValue = "1"
            };
            JsonResult resultAdd = defaultController.Add(paramQueryAdd).Result;
            BaseResultType <PrepareItemResult <ObjectMappingForTest> > resultSuccessQuery = ((BaseResultType <PrepareItemResult <ObjectMappingForTest> >)resultAdd.Value);

            Assert.AreEqual(ResultStatus.Success, resultSuccessQuery.Status);
            Assert.IsNotNull(resultSuccessQuery.Data);

            Assert.IsInstanceOfType(resultSuccessQuery.Data, typeof(PrepareItemResult <ObjectMappingForTest>), "Вернулся тип объекта не ObjectMappingForTest после сохранения этого объекта.");
            Assert.AreEqual(1, ((ObjectMappingForTest)resultSuccessQuery.Data.Item).IntValue);
            Assert.AreEqual(1, ((ObjectMappingForTest)resultSuccessQuery.Data.Item).IntValue2);
            Assert.AreEqual("1", ((ObjectMappingForTest)resultSuccessQuery.Data.Item).StrValue);
            Assert.AreEqual(4, ((ObjectMappingForTest)resultSuccessQuery.Data.Item).Id);

            //Проверка запроса из БД, что запись добавилась
            JsonResult result = defaultController.GetAsync(new FetchDataParameters()
            {
                CountOnPage = 10, PageNumber = 1
            }).Result;
            BaseResultType <ResultFetchData <ObjectMappingForTest> > fetchDataResultQuery = (BaseResultType <ResultFetchData <ObjectMappingForTest> >)result.Value;

            Assert.AreEqual(ResultStatus.Success, fetchDataResultQuery.Status);
            Assert.AreEqual(4, fetchDataResultQuery.Data.TotalCountRows);
        }
            public BaseResultType Validate(DefaultParamOfCRUDOperation <ObjectMappingForTest> item)
            {
                BaseResultType baseResultType = new BaseResultType()
                {
                    Status = ResultStatus.Success
                };

                if (String.IsNullOrWhiteSpace(item.Item.StrValue))
                {
                    if (!item.IsSendAndAnswerQuestion("Продолжить?", ResultQuestionType.NO, baseResultType))
                    {
                        baseResultType.AddError("Ошибка");
                    }
                }

                if (item.Item.IntValue2 == 22)
                {
                    baseResultType.AddWarring(new WarningQuestion()
                    {
                        Message = "Уведомления"
                    });
                }
                return(baseResultType);
            }
        public void GetAsyncTest()
        {
            CreateContext();
            DefaultController <ObjectMappingForTest> defaultController = new DefaultController <ObjectMappingForTest>(new FakeLogger(), new FetchDomainData <ObjectMappingForTest>(_uow), null, null, null);

            //Выборка первой страницы с дефолтным размером стриницы
            JsonResult result = defaultController.GetAsync(null).Result;
            BaseResultType <ResultFetchData <ObjectMappingForTest> > fetchDataResultQuery = (BaseResultType <ResultFetchData <ObjectMappingForTest> >)result.Value;

            Assert.AreEqual(ResultStatus.Success, fetchDataResultQuery.Status);
            Assert.AreEqual(3, fetchDataResultQuery.Data.TotalCountRows);
            Assert.AreEqual(3, fetchDataResultQuery.Data.Items.Count);

            //Проверка выборки первой страницы
            result = defaultController.GetAsync(new FetchDataParameters()
            {
                CountOnPage = 1
            }).Result;
            fetchDataResultQuery = (BaseResultType <ResultFetchData <ObjectMappingForTest> >)result.Value;
            Assert.AreEqual(ResultStatus.Success, fetchDataResultQuery.Status);
            Assert.AreEqual(3, fetchDataResultQuery.Data.TotalCountRows, "Общий подсчет записей при запросе не работает.");
            Assert.AreEqual(1, fetchDataResultQuery.Data.Items.Count);
            Assert.AreEqual(1, fetchDataResultQuery.Data.Items[0].Id);
            Assert.AreEqual(1, fetchDataResultQuery.Data.PageNumber);
            //Проверка выборки второй страницы
            result = defaultController.GetAsync(new FetchDataParameters()
            {
                CountOnPage = 1, PageNumber = 2
            }).Result;
            fetchDataResultQuery = (BaseResultType <ResultFetchData <ObjectMappingForTest> >)result.Value;
            Assert.AreEqual(ResultStatus.Success, fetchDataResultQuery.Status);
            Assert.AreEqual(3, fetchDataResultQuery.Data.TotalCountRows);
            Assert.AreEqual(1, fetchDataResultQuery.Data.Items.Count);
            Assert.AreEqual(2, fetchDataResultQuery.Data.Items[0].Id);
            Assert.AreEqual(2, fetchDataResultQuery.Data.PageNumber);
        }
        public void MergeQuestionTest()
        {
            BaseResultType withQuestion = new BaseResultType();

            withQuestion.AddWarring(new WarningQuestion());

            BaseResultType withoutQuestion = new BaseResultType();

            withQuestion.Merge(withoutQuestion);
            Assert.IsNotNull(withQuestion.Question);
            Assert.AreEqual(1, withQuestion.Question.Count);

            withoutQuestion.Merge(withoutQuestion);
            Assert.IsNotNull(withQuestion.Question);
            Assert.AreEqual(1, withQuestion.Question.Count);

            //Мерж с пустыми списками вопросов
            withQuestion    = new BaseResultType();
            withoutQuestion = new BaseResultType();

            withoutQuestion.Merge(withoutQuestion);
            Assert.IsNotNull(withoutQuestion.Question);
            Assert.AreEqual(0, withoutQuestion.Question.Count);
        }
Beispiel #20
0
 public EKAERException(BaseResultType result) : base(result.Msg)
 {
     Result     = result;
     ReasonCode = result.ReasonCode;
 }