public async Task RequestAccessPost()
        {
            var providerCode = "PROVIDERCODE";
            var viewModel    = new RequestAccessViewModel {
                FirstName = "FirstName", LastName = "LastName"
            };
            var tempKey = "RequestAccess_To_Name";

            var apiMock = new Mock <IManageApi>();

            var tempDataMock = new Mock <ITempDataDictionary>();

            var frontendUrlMock = new Mock <IFrontendUrlService>();

            var controller = new OrganisationController(apiMock.Object, frontendUrlMock.Object);

            controller.TempData = tempDataMock.Object;

            var result = await controller.RequestAccessPost(providerCode, viewModel);

            apiMock.Verify(x => x.GetProviderSummaries(), Times.Never);
            apiMock.Verify(x => x.CreateAccessRequest(It.IsAny <GovUk.Education.ManageCourses.Api.Model.AccessRequest>()), Times.Once);

            tempDataMock.Verify(x => x.Add(tempKey, $"{viewModel.FirstName} {viewModel.LastName}"));

            var actionResult = result as RedirectToActionResult;

            Assert.IsNotNull(actionResult);
            Assert.AreEqual("Show", actionResult.ActionName);
            Assert.AreEqual("Organisation", actionResult.ControllerName);
            Assert.AreEqual(providerCode, actionResult.RouteValues[providerCode]);
        }
        public async Task RequestAccessPost_invalid()
        {
            var providerCode     = "PROVIDERCODE";
            var organisationName = "organisationName";

            var orgs = new List <ProviderSummary>
            {
                new ProviderSummary
                {
                    ProviderCode = providerCode,
                    ProviderName = organisationName
                }
            };

            var apiMock = new Mock <IManageApi>();

            apiMock.Setup(x => x.GetProviderSummaries())
            .ReturnsAsync(orgs);

            var frontendUrlMock = new Mock <IFrontendUrlService>();

            var controller = new OrganisationController(apiMock.Object, frontendUrlMock.Object);

            controller.ModelState.AddModelError("you", "failed");
            var result = await controller.RequestAccessPost(providerCode, new RequestAccessViewModel());

            var viewResult = result as ViewResult;

            Assert.IsNotNull(viewResult);
            var model = viewResult.ViewData.Model as RequestAccessViewModel;

            Assert.AreEqual(providerCode, controller.ViewBag.ProviderCode);
        }
        public void Arrange()
        {
            _orchestrator           = new Mock <OrganisationOrchestrator>();
            _owinWrapper            = new Mock <IOwinWrapper>();
            _featureToggle          = new Mock <IFeatureToggle>();
            _userViewTestingService = new Mock <IMultiVariantTestingService>();
            _mapper       = new Mock <IMapper>();
            _flashMessage = new Mock <ICookieStorageService <FlashMessageViewModel> >();

            _validationResponse = new OrchestratorResponse <OrganisationDetailsViewModel>
            {
                Data   = new OrganisationDetailsViewModel(),
                Status = HttpStatusCode.OK
            };

            _orchestrator.Setup(x => x.ValidateLegalEntityName(It.IsAny <OrganisationDetailsViewModel>()))
            .ReturnsAsync(_validationResponse);

            _mapper.Setup(x => x.Map <FindOrganisationAddressViewModel>(It.IsAny <OrganisationDetailsViewModel>()))
            .Returns(new FindOrganisationAddressViewModel());

            _logger = new Mock <ILogger>();

            _controller = new OrganisationController(
                _owinWrapper.Object,
                _orchestrator.Object,
                _featureToggle.Object,
                _userViewTestingService.Object,
                _mapper.Object,
                _logger.Object,
                _flashMessage.Object);
        }
        public void Arrange()
        {
            _orchestrator           = new Mock <OrganisationOrchestrator>();
            _owinWrapper            = new Mock <IOwinWrapper>();
            _featureToggle          = new Mock <IFeatureToggle>();
            _userViewTestingService = new Mock <IMultiVariantTestingService>();
            _mapper       = new Mock <IMapper>();
            _flashMessage = new Mock <ICookieStorageService <FlashMessageViewModel> >();

            _orchestrator.Setup(x => x.CreateLegalEntity(It.IsAny <CreateNewLegalEntityViewModel>()))
            .ReturnsAsync(new OrchestratorResponse <EmployerAgreementViewModel>
            {
                Status = HttpStatusCode.OK,
                Data   = new EmployerAgreementViewModel
                {
                    EmployerAgreement = new EmployerAgreementView()
                }
            });

            _logger = new Mock <ILogger>();

            _controller = new OrganisationController(
                _owinWrapper.Object,
                _orchestrator.Object,
                _featureToggle.Object,
                _userViewTestingService.Object,
                _mapper.Object,
                _logger.Object,
                _flashMessage.Object);
        }
예제 #5
0
        public void Arrange()
        {
            _orchestrator           = new Mock <OrganisationOrchestrator>();
            _owinWrapper            = new Mock <IOwinWrapper>();
            _featureToggle          = new Mock <IFeatureToggle>();
            _userViewTestingService = new Mock <IMultiVariantTestingService>();
            _mapper       = new Mock <IMapper>();
            _flashMessage = new Mock <ICookieStorageService <FlashMessageViewModel> >();

            _orchestrator.Setup(x => x.GetCharityByRegistrationNumber(It.Is <string>(c => c == "12345"), It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(new OrchestratorResponse <OrganisationDetailsViewModel>
            {
                Data   = new OrganisationDetailsViewModel(),
                Status = HttpStatusCode.OK
            });

            _orchestrator.Setup(x => x.GetCharityByRegistrationNumber(It.Is <string>(c => c == "666"), It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(new OrchestratorResponse <OrganisationDetailsViewModel>
            {
                Data   = new OrganisationDetailsViewModel(),
                Status = HttpStatusCode.NotFound
            });

            _logger = new Mock <ILogger>();

            _controller = new OrganisationController(
                _owinWrapper.Object,
                _orchestrator.Object,
                _featureToggle.Object,
                _userViewTestingService.Object,
                _mapper.Object,
                _logger.Object,
                _flashMessage.Object);
        }
예제 #6
0
        public void Arrange()
        {
            _orchestrator           = new Mock <OrganisationOrchestrator>();
            _owinWrapper            = new Mock <IOwinWrapper>();
            _featureToggle          = new Mock <IFeatureToggle>();
            _userViewTestingService = new Mock <IMultiVariantTestingService>();
            _mapper       = new Mock <IMapper>();
            _flashMessage = new Mock <ICookieStorageService <FlashMessageViewModel> >();

            _viewModel = new SelectOrganisationAddressViewModel();

            _orchestrator.Setup(x => x.GetAddressesFromPostcode(It.IsAny <FindOrganisationAddressViewModel>()))
            .ReturnsAsync(new OrchestratorResponse <SelectOrganisationAddressViewModel>()
            {
                Data   = _viewModel,
                Status = HttpStatusCode.OK
            });

            _mapper.Setup(x => x.Map <AddOrganisationAddressViewModel>(It.IsAny <FindOrganisationAddressViewModel>()))
            .Returns(new AddOrganisationAddressViewModel()
            {
                Address = new AddressViewModel()
            });

            _logger = new Mock <ILogger>();

            _controller = new OrganisationController(
                _owinWrapper.Object,
                _orchestrator.Object,
                _featureToggle.Object,
                _userViewTestingService.Object,
                _mapper.Object,
                _logger.Object,
                _flashMessage.Object);
        }
예제 #7
0
        protected void Setup()
        {
            SetupOrchestratorMocks();
            SetupControllerMocks();

            OrganisationController = new OrganisationController(ControllerLoggerMock.Object, Mediator.Object);
        }
예제 #8
0
        public void ThenAResultShouldBeReturned()
        {
            var request = new WithdrawOrganisationRequest();

            var result = OrganisationController.WithdrawalOrganisation(request).Result as NoContentResult;

            result.Should().NotBeNull();

            Mediator.Verify(q => q.Send(request, Moq.It.IsAny <CancellationToken>()));
        }
        public void Arrange()
        {
            Setup();

            _organisation = Builder <Organisation> .CreateNew().Build();

            Mediator.Setup(q => q.Send(Moq.It.IsAny <CreateOrganisationRequest>(), Moq.It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult((_organisation)));

            _result = OrganisationController.CreateOrganisation(default(CreateOrganisationRequest)).Result;
        }
        public async Task Index_Redirects_To_FrontEnd()
        {
            var frontendUrlMock = new Mock <IFrontendUrlService>();

            frontendUrlMock.Setup(x => x.ShouldRedirectOrganisationShow()).Returns(true);
            frontendUrlMock.Setup(x => x.RedirectToFrontend("/organisations")).Returns(new RedirectResult("frontend"));
            var controller = new OrganisationController(null, frontendUrlMock.Object);

            var result = await controller.Index();

            Assert.IsTrue(result is RedirectResult);
        }
        public async Task Show_Redirects_To_FrontEnd()
        {
            var providerCode = "PROVIDERCODE";

            var frontendUrlMock = new Mock <IFrontendUrlService>();

            frontendUrlMock.Setup(x => x.ShouldRedirectOrganisationShow()).Returns(true);
            frontendUrlMock.Setup(x => x.RedirectToFrontend("/organisations/" + providerCode)).Returns(new RedirectResult("frontend"));
            var controller = new OrganisationController(null, frontendUrlMock.Object);

            var result = await controller.Show(providerCode);

            Assert.IsTrue(result is RedirectResult);
        }
        public void RequestAccess()
        {
            var providerCode = "PROVIDERCODE";

            var frontendUrlMock = new Mock <IFrontendUrlService>();

            frontendUrlMock.Setup(x => x.ShouldRedirectOrganisationShow()).Returns(true);
            frontendUrlMock.Setup(x => x.RedirectToFrontend("/organisations/" + $"{providerCode}/request-access")).Returns(new RedirectResult("frontend"));
            var controller = new OrganisationController(null, frontendUrlMock.Object);

            var result = controller.RequestAccess(providerCode);

            Assert.IsTrue(result is RedirectResult);
        }
예제 #13
0
        public async Task ThenRoEpaoApprovedFlagIsSet()
        {
            var mediator = new Mock <IMediator>();

            mediator.Setup(m => m.Send(It.IsAny <UpdateRoEpaoApprovedFlagRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(new Organisation
            {
                Id = Guid.NewGuid(),
            });

            var organisationController = new OrganisationController(mediator.Object, new Mock <ILogger <OrganisationController> >().Object);

            await organisationController.UpdateRoEpaoApprovedFlag(Guid.NewGuid(), Guid.NewGuid(), It.IsAny <string>(), true);

            mediator.VerifyAll();
        }
        public async Task Show()
        {
            var providerCode     = "PROVIDERCODE";
            var organisationName = "organisationName";
            // Todo: fix this ObservableCollection.
            var providerCourses = new List <Course>
            {
                new Course
                {
                    Provider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode, ProviderName = organisationName
                    }
                }
            };

            var orgs = new List <ProviderSummary>
            {
                new ProviderSummary(),
                new ProviderSummary
                {
                    ProviderCode = providerCode,
                    ProviderName = organisationName
                }
            };

            var apiMock = new Mock <IManageApi>();

            apiMock.Setup(x => x.GetCoursesOfProvider(providerCode)).ReturnsAsync(providerCourses);

            apiMock.Setup(x => x.GetProviderSummaries()).ReturnsAsync(orgs);

            apiMock.Setup(x => x.GetProviderSummary(It.IsAny <string>())).ReturnsAsync(orgs[1]);

            var frontendUrlMock = new Mock <IFrontendUrlService>();

            var controller = new OrganisationController(apiMock.Object, frontendUrlMock.Object);

            var result = await controller.Show(providerCode);

            var viewResult = result as ViewResult;

            Assert.IsNotNull(viewResult);
            var model = viewResult.ViewData.Model as CourseListViewModel;

            Assert.NotNull(model);

            Assert.IsTrue(model.MultipleOrganisations);
        }
예제 #15
0
        public async void GetIndex_WithInactiveAndRejectedAssociation_ShowsOnlyInactiveAssociation()
        {
            // Arrange
            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <GetUserOrganisationsByStatus> ._))
            .Returns(new List <OrganisationUserData>
            {
                new OrganisationUserData
                {
                    OrganisationId = new Guid("EF4B78BA-3D73-4B99-A996-714677590A78"),
                    UserStatus     = UserStatus.Inactive,
                    Organisation   = new OrganisationData
                    {
                        OrganisationName   = "Organisation Name 1",
                        OrganisationStatus = OrganisationStatus.Complete,
                    }
                },
                new OrganisationUserData
                {
                    OrganisationId = new Guid("EF4B78BA-3D73-4B99-A996-714677590A78"),
                    UserStatus     = UserStatus.Rejected,
                    Organisation   = new OrganisationData
                    {
                        OrganisationName   = "Organisation Name 1",
                        OrganisationStatus = OrganisationStatus.Complete,
                    }
                }
            });

            OrganisationController controller = new OrganisationController(() => weeeClient);

            // Act
            ActionResult result = await controller.Index();

            // Assert
            Assert.IsAssignableFrom <ViewResultBase>(result);
            ViewResultBase viewResult = result as ViewResultBase;

            Assert.IsAssignableFrom <PendingOrganisationsViewModel>(viewResult.Model);
            PendingOrganisationsViewModel model = viewResult.Model as PendingOrganisationsViewModel;

            Assert.Equal(1, model.InaccessibleOrganisations.Count());
            OrganisationUserData result1 = model.InaccessibleOrganisations.First();

            Assert.Equal(UserStatus.Inactive, result1.UserStatus);
        }
        public void Arrange()
        {
            _orchestrator           = new Mock <OrganisationOrchestrator>();
            _owinWrapper            = new Mock <IAuthenticationService>();
            _userViewTestingService = new Mock <IMultiVariantTestingService>();
            _mapper       = new Mock <IMapper>();
            _flashMessage = new Mock <ICookieStorageService <FlashMessageViewModel> >();

            _logger = new Mock <ILog>();

            _controller = new OrganisationController(
                _owinWrapper.Object,
                _orchestrator.Object,
                _userViewTestingService.Object,
                _mapper.Object,
                _logger.Object,
                _flashMessage.Object);
        }
예제 #17
0
        public async void GetIndex_OneInactiveOrg_ShowsPendingView()
        {
            // Arrange
            Guid organisationId = new Guid("433DB128-12A1-44FB-B26A-8128F8E36598");

            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <GetUserOrganisationsByStatus> ._))
            .Returns(new List <OrganisationUserData>
            {
                new OrganisationUserData
                {
                    OrganisationId = organisationId,
                    UserStatus     = UserStatus.Pending,
                    Organisation   = new OrganisationData
                    {
                        OrganisationName   = "Organisation Name 1",
                        OrganisationStatus = OrganisationStatus.Complete,
                    }
                }
            });

            OrganisationController controller = new OrganisationController(() => weeeClient);

            // Act
            ActionResult result = await controller.Index();

            // Assert
            Assert.IsAssignableFrom <ViewResult>(result);

            ViewResult viewResult = result as ViewResult;

            Assert.Equal("PendingOrganisations", viewResult.ViewName);

            Assert.IsAssignableFrom <PendingOrganisationsViewModel>(viewResult.Model);

            PendingOrganisationsViewModel model = viewResult.Model as PendingOrganisationsViewModel;

            Assert.Equal(1, model.InaccessibleOrganisations.Count());

            Assert.Equal(organisationId, model.InaccessibleOrganisations.First().OrganisationId);
            Assert.Equal("Organisation Name 1", model.InaccessibleOrganisations.First().Organisation.OrganisationName);
        }
        public void Arrange()
        {
            _orchestrator           = new Mock <OrganisationOrchestrator>();
            _owinWrapper            = new Mock <IAuthenticationService>();
            _userViewTestingService = new Mock <IMultiVariantTestingService>();
            _mapper       = new Mock <IMapper>();
            _flashMessage = new Mock <ICookieStorageService <FlashMessageViewModel> >();

            _orchestrator.Setup(x => x.CreateLegalEntity(It.IsAny <CreateNewLegalEntityViewModel>()))
            .Throws <UnauthorizedAccessException>();

            _logger = new Mock <ILog>();

            _controller = new OrganisationController(
                _owinWrapper.Object,
                _orchestrator.Object,
                _userViewTestingService.Object,
                _mapper.Object,
                _logger.Object,
                _flashMessage.Object);
        }
예제 #19
0
        public void Arrange()
        {
            _response = new FindEducationalOrganisationsResponse
            {
                Organisations = new PagedApiResponse <EducationOrganisation>
                {
                    Data = new List <EducationOrganisation> {
                        new EducationOrganisation {
                            Name = "Test Organisation"
                        }
                    }
                }
            };

            _mediator = new Mock <IMediator>();

            _mediator.Setup(x => x.SendAsync(It.IsAny <FindEducationalOrganisationsQuery>()))
            .ReturnsAsync(_response);

            _controller = new OrganisationController(_mediator.Object, Mock.Of <ILog>());
        }
예제 #20
0
        public async void GetIndex_NoOrganisations_RedirectsToCreateJoinOrganisation()
        {
            // Arrange
            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <GetUserOrganisationsByStatus> ._))
            .Returns(new List <OrganisationUserData>());

            OrganisationController controller = new OrganisationController(() => weeeClient);

            // Act
            ActionResult result = await controller.Index();

            // Assert
            Assert.IsAssignableFrom <RedirectToRouteResult>(result);

            RedirectToRouteResult redirectResult = result as RedirectToRouteResult;

            Assert.Equal(null, redirectResult.RouteValues["area"] as string, ignoreCase: true);
            Assert.Equal("organisationregistration", redirectResult.RouteValues["controller"] as string, ignoreCase: true);
            Assert.Equal("Search", redirectResult.RouteValues["action"] as string, ignoreCase: true);
        }
        public void Arrange()
        {
            _orchestrator           = new Mock <OrganisationOrchestrator>();
            _owinWrapper            = new Mock <IOwinWrapper>();
            _featureToggle          = new Mock <IFeatureToggle>();
            _userViewTestingService = new Mock <IMultiVariantTestingService>();
            _mapper       = new Mock <IMapper>();
            _flashMessage = new Mock <ICookieStorageService <FlashMessageViewModel> >();

            _orchestrator.Setup(x => x.GetAddOtherOrganisationViewModel(It.IsAny <string>()))
            .Returns(new OrchestratorResponse <OrganisationDetailsViewModel>());

            _logger = new Mock <ILogger>();

            _controller = new OrganisationController(
                _owinWrapper.Object,
                _orchestrator.Object,
                _featureToggle.Object,
                _userViewTestingService.Object,
                _mapper.Object,
                _logger.Object,
                _flashMessage.Object);
        }
예제 #22
0
        public async void GetIndex_OneActiveOrg_RedirectsToSchemeChooseActivity()
        {
            // Arrange
            Guid organisationId = new Guid("433DB128-12A1-44FB-B26A-8128F8E36598");

            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <GetUserOrganisationsByStatus> ._))
            .Returns(new List <OrganisationUserData>
            {
                new OrganisationUserData
                {
                    OrganisationId = organisationId,
                    UserStatus     = UserStatus.Active,
                    Organisation   = new OrganisationData
                    {
                        OrganisationName   = "Organisation Name 1",
                        OrganisationStatus = OrganisationStatus.Complete,
                    }
                }
            });

            OrganisationController controller = new OrganisationController(() => weeeClient);

            // Act
            ActionResult result = await controller.Index();

            // Assert
            Assert.IsAssignableFrom <RedirectToRouteResult>(result);

            RedirectToRouteResult redirectResult = result as RedirectToRouteResult;

            Assert.Equal("scheme", redirectResult.RouteValues["area"] as string, ignoreCase: true);
            Assert.Equal("home", redirectResult.RouteValues["controller"] as string, ignoreCase: true);
            Assert.Equal("chooseactivity", redirectResult.RouteValues["action"] as string, ignoreCase: true);
            Assert.Equal(organisationId, redirectResult.RouteValues["pcsId"]);
        }
        public void Arrange()
        {
            _response = new GetCharityByRegistrationNumberResponse
            {
                Charity = new Charity
                {
                    RegistrationNumber = 123,
                    Name = "Test Charity"
                }
            };

            _mediator = new Mock <IMediator>();

            _mediator.Setup(x => x.SendAsync(It.Is <GetCharityByRegistrationNumberQuery>(query => query.RegistrationNumber == 123)))
            .ReturnsAsync(_response);

            _mediator.Setup(x => x.SendAsync(It.Is <GetCharityByRegistrationNumberQuery>(query => query.RegistrationNumber == 456)))
            .ReturnsAsync(new GetCharityByRegistrationNumberResponse
            {
                Charity = null
            });

            _controller = new OrganisationController(_mediator.Object, Mock.Of <ILog>());
        }
예제 #24
0
 public void TestSetup()
 {
     _mediator   = new Mock <IMediator>();
     _logger     = new Mock <ILogger <OrganisationController> >();
     _controller = new OrganisationController(_mediator.Object, _logger.Object);
 }
        public void AboutPost_ModelState_WordCount()
        {
            var providerCode   = "PROVIDERCODE";
            var exceed100Words = "";

            for (int i = 0; i < 101; i++)
            {
                exceed100Words += i + " ";
            }
            var providerName = "ProviderName";

            var viewModel = new OrganisationViewModelForAbout
            {
                AboutTrainingProviders = new List <TrainingProviderViewModel>()
                {
                    new TrainingProviderViewModel {
                        Description  = exceed100Words,
                        ProviderName = providerName,
                        ProviderCode = providerCode + 1
                    }
                }
            };

            var providerCourses = new List <Course>
            {
                new Course {
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToUpperInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToLowerInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 1, ProviderName = providerName
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 2
                    }
                },
            };

            var apiMock = new Mock <IManageApi>();

            apiMock.Setup(x => x.GetCoursesOfProvider(providerCode))
            .ReturnsAsync(providerCourses);


            var enrichmentModel = new ProviderEnrichmentModel {
                AccreditingProviderEnrichments = new List <AccreditingProviderEnrichment> {
                }
            };

            var ucasProviderEnrichmentGetModel = new UcasProviderEnrichmentGetModel()
            {
                EnrichmentModel = enrichmentModel
            };

            apiMock.Setup(x => x.GetProviderSummaries())
            .ReturnsAsync(new List <ProviderSummary> {
                new ProviderSummary()
            });

            apiMock.Setup(x => x.GetProviderEnrichment(providerCode))
            .ReturnsAsync(ucasProviderEnrichmentGetModel);

            var objectValidator = new Mock <IObjectModelValidator>();

            objectValidator.Setup(o => o.Validate(It.IsAny <ActionContext>(),
                                                  It.IsAny <ValidationStateDictionary>(),
                                                  It.IsAny <string>(),
                                                  It.IsAny <Object>()));

            var frontendUrlMock = new Mock <IFrontendUrlService>();

            var controller = new OrganisationController(apiMock.Object, frontendUrlMock.Object);

            controller.ObjectValidator = objectValidator.Object;

            controller.TempData = new Mock <ITempDataDictionary>().Object;

            Assert.IsFalse(controller.ModelState.Any());
            Assert.IsTrue(controller.ModelState.IsValid);
            var result = controller.AboutPost(providerCode, viewModel).Result;


            Assert.IsTrue(controller.ModelState.Any());
            Assert.AreEqual($"Reduce word count for {providerName}", controller.ModelState["AboutTrainingProviders_0__Description"].Errors.First().ErrorMessage);
            Assert.IsFalse(controller.ModelState.IsValid);

            var viewResult = result as ViewResult;

            var organisationViewModel = viewResult.ViewData.Model as OrganisationViewModelForAbout;

            Assert.IsNotNull(viewResult);
            Assert.AreEqual(exceed100Words, organisationViewModel.AboutTrainingProviders.First(x => x.ProviderCode == providerCode + 1).Description);
            Assert.AreEqual(providerName, organisationViewModel.AboutTrainingProviders.First(x => x.ProviderCode == providerCode + 1).ProviderName);
        }
        public async Task AboutPost_SetAccreditingProviderToEmpty()
        {
            var existingEnrichment = new UcasProviderEnrichmentGetModel()
            {
                EnrichmentModel = new ProviderEnrichmentModel()
                {
                    AccreditingProviderEnrichments = new List <AccreditingProviderEnrichment>
                    {
                        new AccreditingProviderEnrichment
                        {
                            UcasProviderCode = "ACC",
                            Description      = "foo"
                        }
                    }
                }
            };

            var apiMock = new Mock <IManageApi>();

            apiMock.Setup(x => x.GetProviderEnrichment("ABC")).ReturnsAsync(existingEnrichment);

            UcasProviderEnrichmentPostModel result = null;

            apiMock.Setup(x => x.SaveProviderEnrichment("ABC", It.IsAny <UcasProviderEnrichmentPostModel>()))
            .Callback((string a, UcasProviderEnrichmentPostModel b) => result = b)
            .Returns(Task.CompletedTask);

            apiMock.Setup(x => x.GetCoursesOfProvider("ABC")).ReturnsAsync(new List <Course> {
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = "ACC"
                    }
                }
            });

            var objectValidator = new Mock <IObjectModelValidator>();

            objectValidator.Setup(o => o.Validate(It.IsAny <ActionContext>(),
                                                  It.IsAny <ValidationStateDictionary>(),
                                                  It.IsAny <string>(),
                                                  It.IsAny <Object>()));

            var frontendUrlMock = new Mock <IFrontendUrlService>();

            var controller = new OrganisationController(apiMock.Object, frontendUrlMock.Object);

            controller.ObjectValidator = objectValidator.Object;
            controller.TempData        = new Mock <ITempDataDictionary>().Object;

            var res = await controller.AboutPost("ABC", new OrganisationViewModelForAbout {
                AboutTrainingProviders = new List <TrainingProviderViewModel>
                {
                    new TrainingProviderViewModel
                    {
                        ProviderCode = "ACC",
                        Description  = null // not an empty string... this is how MVC model binding behaves
                    }
                }
            });


            result.Should().NotBeNull();
            result.EnrichmentModel.AccreditingProviderEnrichments[0].UcasProviderCode.Should().Be("ACC");
            result.EnrichmentModel.AccreditingProviderEnrichments[0].Description.Should().BeNullOrEmpty();
        }
        public async Task DetailsPost_PublishOrganisation_WhenApiReturnsTrue()
        {
            var providerCode = "PROVIDERCODE";
            var viewModel    = new OrganisationViewModel
            {
                AboutTrainingProviders = new List <TrainingProviderViewModel>()
            };

            var providerName = "ProviderName";

            var providerCourses = new List <Course>
            {
                new Course {
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToUpperInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToLowerInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 1, ProviderName = providerName
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 2
                    }
                },
            };
            var apiMock = new Mock <IManageApi>();

            apiMock.Setup(x => x.GetProviderSummary(providerCode))
            .ReturnsAsync(new ProviderSummary {
                ProviderCode = providerCode, ProviderName = providerName
            });

            apiMock.Setup(x => x.GetCoursesOfProvider(providerCode))
            .ReturnsAsync(providerCourses);

            var enrichmentModel = new ProviderEnrichmentModel {
                AccreditingProviderEnrichments = new List <AccreditingProviderEnrichment>()
            };

            var ucasProviderEnrichmentGetModel = new UcasProviderEnrichmentGetModel()
            {
                EnrichmentModel = enrichmentModel
            };

            apiMock.Setup(x => x.GetProviderEnrichment(providerCode))
            .ReturnsAsync(ucasProviderEnrichmentGetModel);

            var objectValidator = new Mock <IObjectModelValidator>();

            objectValidator.Setup(o => o.Validate(It.IsAny <ActionContext>(),
                                                  It.IsAny <ValidationStateDictionary>(),
                                                  It.IsAny <string>(),
                                                  It.IsAny <Object>()));

            apiMock.Setup(x => x.PublishAllCoursesOfProviderToSearchAndCompare(providerCode))
            .ReturnsAsync(true);
            var frontendUrlMock = new Mock <IFrontendUrlService>();
            var controller      = new OrganisationController(apiMock.Object, frontendUrlMock.Object);

            controller.ObjectValidator = objectValidator.Object;

            controller.TempData = new Mock <ITempDataDictionary>().Object;

            var result = await controller.DetailsPost(providerCode, viewModel);

            var actionResult = result as RedirectToActionResult;

            Assert.IsNotNull(actionResult);
            Assert.AreEqual("Details", actionResult.ActionName);
            Assert.AreEqual(providerCode, actionResult.RouteValues[providerCode]);
        }
        public void DetailsPost_PublishOrganisation_WhenApiReturnsFalse()
        {
            var providerCode = "PROVIDERCODE";
            var providerName = "ProviderName";

            var viewModel = new OrganisationViewModel
            {
                AboutTrainingProviders = new List <TrainingProviderViewModel>()
            };

            var providerCourses = new List <Course>
            {
                new Course {
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToUpperInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode.ToLowerInvariant()
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 1, ProviderName = providerName
                    }
                },
                new Course {
                    AccreditingProvider = new GovUk.Education.ManageCourses.Domain.Models.Provider {
                        ProviderCode = providerCode + 2
                    }
                },
            };

            var apiMock = new Mock <IManageApi>();

            apiMock.Setup(x => x.GetProviderSummary(providerCode))
            .ReturnsAsync(new ProviderSummary {
                ProviderCode = providerCode, ProviderName = providerName
            });

            apiMock.Setup(x => x.GetCoursesOfProvider(providerCode))
            .ReturnsAsync(providerCourses);

            var enrichmentModel = new ProviderEnrichmentModel {
                AccreditingProviderEnrichments = new List <AccreditingProviderEnrichment> {
                }
            };

            var ucasProviderEnrichmentGetModel = new UcasProviderEnrichmentGetModel()
            {
                EnrichmentModel = enrichmentModel
            };

            apiMock.Setup(x => x.GetProviderEnrichment(providerCode))
            .ReturnsAsync(ucasProviderEnrichmentGetModel);

            var objectValidator = new Mock <IObjectModelValidator>();

            objectValidator.Setup(o => o.Validate(It.IsAny <ActionContext>(),
                                                  It.IsAny <ValidationStateDictionary>(),
                                                  It.IsAny <string>(),
                                                  It.IsAny <Object>()));

            var frontendUrlMock = new Mock <IFrontendUrlService>();

            var controller = new OrganisationController(apiMock.Object, frontendUrlMock.Object);

            controller.ObjectValidator = objectValidator.Object;

            controller.TempData = new Mock <ITempDataDictionary>().Object;

            Assert.ThrowsAsync <InvalidOperationException>(async() => await controller.DetailsPost(providerCode, viewModel));
        }
 public OrganisationControllerTests()
 {
     _controller = new OrganisationController(_mockLogger.Object, _mockOrganisationServiceService.Object);
 }
        public void Arrange(bool addEpaoClaim, bool addUkprnClaim, List <ContactsPrivilege> contactsPrivileges = null)
        {
            HttpContextAssessor = new Mock <IHttpContextAccessor>();

            Logger         = new Mock <ILogger <OrganisationController> >();
            SessionService = new Mock <ISessionService>();
            TokenService   = new Mock <ITokenService>();
            TokenService.Setup(s => s.GetToken()).Returns("jwt");

            OrganisationApiClient = new Mock <IOrganisationsApiClient>();
            OrganisationApiClient.Setup(c => c.Get("12345")).ReturnsAsync(new OrganisationResponse()
            {
            });

            EpaOrganisation = new EpaOrganisation
            {
                Id               = OrganisationOneId,
                OrganisationId   = EpaoId,
                OrganisationData = new OrganisationData
                {
                    Address1    = ValidAddress1,
                    Address2    = ValidAddress2,
                    Address3    = ValidAddress3,
                    Address4    = ValidAddress4,
                    Postcode    = ValidPostcode,
                    PhoneNumber = ValidPhoneNumber,
                    Email       = ValidEmailAddress,
                    WebsiteLink = ValidWebsiteLink
                },
                PrimaryContact = ValidPrimaryContact
            };

            OrganisationApiClient.Setup(c => c.GetEpaOrganisation(EpaoId)).ReturnsAsync(EpaOrganisation);

            WebConfiguration = new Mock <IWebConfiguration>();
            WebConfiguration.Setup(c => c.AzureApiAuthentication).Returns(new AzureApiAuthentication
            {
                ProductId = "1234567"
            });

            ExternalApiClient = new Mock <IAzureApiClient>();
            ExternalApiClient.Setup(c => c.GetUserDetailsByUkprn(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>())).ReturnsAsync(
                new List <AzureUser>
            {
                new AzureUser
                {
                    Subscriptions = new List <AzureSubscription>
                    {
                        new AzureSubscription()
                    }
                }
            });

            ContactsApiClient = new Mock <IContactsApiClient>();
            ContactsApiClient.Setup(c => c.GetPrivileges()).ReturnsAsync(
                new List <Privilege>()
            {
                new Privilege
                {
                    Id  = ChangeOrganisationPrivilegeId,
                    Key = Privileges.ChangeOrganisationDetails
                },
                new Privilege
                {
                    Id  = ManageUsersPrivilegeId,
                    Key = Privileges.ManageUsers
                }
            });

            ContactsApiClient.Setup(c => c.GetContactPrivileges(UserId)).ReturnsAsync(
                contactsPrivileges);

            EmailApiClient    = new Mock <IEmailApiClient>();
            ValidateApiClient = new Mock <IValidationApiClient>();

            var claims = new List <Claim>();

            if (addEpaoClaim)
            {
                claims.Add(new Claim("http://schemas.portal.com/epaoid", EpaoId.ToString()));
            }

            if (addUkprnClaim)
            {
                claims.Add(new Claim("http://schemas.portal.com/ukprn", "12345"));
            }

            claims.Add(new Claim("UserId", UserId.ToString()));

            HttpContextAssessor
            .Setup(c => c.HttpContext)
            .Returns(new DefaultHttpContext()
            {
                User = new ClaimsPrincipal(new ClaimsIdentity(claims.ToArray()))
            });

            sut = new OrganisationController(HttpContextAssessor.Object, OrganisationApiClient.Object, ExternalApiClient.Object,
                                             ContactsApiClient.Object, EmailApiClient.Object, ValidateApiClient.Object,
                                             Logger.Object, WebConfiguration.Object);
        }