public void ShouldSendRentalViewModelMessageWithContinueRentalPropertyIfDriverHasActiveRental()
        {
            //assign
            var driverId        = Guid.NewGuid();
            var driverViewModel = new DriverViewModel()
            {
                Id = driverId
            };
            var activeRentalDto = new RentalDTO();

            _rentalServiceMock.GetActiveRentalForDriver(driverId).Returns(activeRentalDto);

            var activeRentalViewModel = new RentalViewModel();

            _rentalViewModelMapperMock.Map(activeRentalDto).Returns(activeRentalViewModel);

            //act
            var sut = new RentCarViewModel(_carServiceMock, _rentalServiceMock, _carViewModelMapperMock, _rentalViewModelMapperMock, _messengerServiceMock);

            sut.AssignLoggedInDriver(driverViewModel);

            //assert
            _messengerServiceMock.Received().Send(Arg.Is <RentalViewModelMessage>(message => message.RentalViewModel == activeRentalViewModel && message.MessageType == RentalViewModelMessageType.ContinueRental));
            _messengerServiceMock.Received().Send(Arg.Is <NotificationMessage>(message => message.Notification == "Start Car Rental"));
        }
        public void ShouldShowSummaryAndStopTimerWhenReturnCar()
        {
            var elapsedTimer     = Substitute.For <ITimer>();
            var elapsedCostTimer = Substitute.For <ITimer>();

            _timerFactoryMock.CreateTimer().Returns(elapsedTimer, elapsedCostTimer);
            var rentalId = Guid.NewGuid();

            _rentalServiceMock.GetRental(rentalId).Returns(new RentalDTO {
                Total = 10
            });
            var sut = new ActiveRentalSessionViewModel(_timerFactoryMock, _rentalServiceMock, _dialogServiceMock,
                                                       _messengerServiceMock)
            {
                CurrentRental = new RentalViewModel
                {
                    RentalId       = rentalId,
                    PricePerMinute = "2.5"
                }
            };

            sut.StopRentalCommand.Execute(null);


            _rentalServiceMock.Received().ReturnCar(rentalId, Arg.Any <DateTime>());
            Assert.Null(sut.ErrorString);
            _messengerServiceMock.Received()
            .Send(Arg.Is <RefreshRentalsMessage>(m => m.Notification == "Rental Stopped!"));
            Assert.True(sut.IsRentalStopped);
            elapsedCostTimer.Received().Stop();
            elapsedTimer.Received().Stop();
            _rentalServiceMock.Received().GetRental(rentalId);
            _dialogServiceMock.Received().ShowMessage(Arg.Any <string>());
        }
Beispiel #3
0
        public void ShouldSendNavigateToAdminViewMessage()
        {
            var sut = new LoginViewModel(_driverServiceMock, _driverViewModelMapperMock, _messengerServiceMock);

            sut.AdminLoginCommand.Execute(null);
            _messengerServiceMock.Received()
            .Send(Arg.Is <NotificationMessage>(m => m.Notification == "GoToAdminMainView"));
        }
        public void ShouldSendLogoutMessage()
        {
            var sut = new MainViewModel(_messengerServiceMock);

            sut.LogoutCommand.Execute(null);
            _messengerServiceMock.Received().Send(Arg.Is <NotificationMessage>(m => m.Notification == "Logout"));
        }
        public async Task SendNotification_WhenAllPropertiesSet_AddsMessageToTopic()
        {
            // Arrange
            IDictionary <string, string> topicMessageProperties = null;

            IMessengerService messengerService = CreateMessengerService();
            await messengerService.SendToTopic(Arg.Any <string>(), Arg.Any <JobNotification>(), Arg.Do <IDictionary <string, string> >(p => topicMessageProperties = p));

            ILogger logger = CreateLogger();

            INotificationService notificationService = CreateNotificationService(messengerService, logger);

            JobNotification jobNotification = CreateJobNotification();

            // Act
            await notificationService.SendNotification(jobNotification);

            // Assert
            await messengerService
            .Received(1)
            .SendToTopic(Arg.Is(ServiceBusConstants.TopicNames.JobNotifications), Arg.Is(jobNotification), Arg.Any <IDictionary <string, string> >());

            topicMessageProperties.Should().NotBeNull();
            topicMessageProperties["jobId"].Should().Be(jobNotification.JobId, "JobId");
            topicMessageProperties["jobType"].Should().Be(jobNotification.JobType, "JobType");
            topicMessageProperties["entityId"].Should().Be(jobNotification.Trigger.EntityId, "EntityId");
            topicMessageProperties["specificationId"].Should().Be(jobNotification.SpecificationId, "SpecficationId");
            topicMessageProperties["parentJobId"].Should().Be(jobNotification.ParentJobId, "ParentJobId");

            logger
            .Received(1)
            .Information(Arg.Is("Sent notification for job with id '{JobId}' of type '{JobType}' for entity '{EntityType}' with id '{EntityId} and status '{CompletionStatus}"), Arg.Is(jobNotification.JobId), Arg.Is(jobNotification.JobType), Arg.Is(jobNotification.Trigger.EntityType), Arg.Is(jobNotification.Trigger.EntityId), Arg.Is(jobNotification.CompletionStatus));
        }
Beispiel #6
0
        public async Task Run_WhenSmokeTestRunAgainstSmokeMessageInDevelopment_SmokeResponseSentToQueue()
        {
            GivenSmokeTestCreatedInDevelopment();

            string expectedInvocationId = NewRandomString();

            await WhenMessageReceivedBySmokeTest(expectedInvocationId);

            await _messengerService
            .Received(1)
            .SendToQueue(expectedInvocationId,
                         Arg.Is <SmokeResponse>(_ => _.InvocationId == expectedInvocationId &&
                                                _.BuildNumber == _expectedFileVersion),
                         Arg.Is <Dictionary <string, string> >(_ =>
                                                               _["listener"] == SmokeFunction.FunctionName));
        }
        public async Task WaitForJobsToCompleteWithJobsFailed_ReturnsFalse(bool useServiceBus)
        {
            IJobsApiClient jobsApiClient             = Substitute.For <IJobsApiClient>();
            JobManagementResiliencePolicies policies = new JobManagementResiliencePolicies
            {
                JobsApiClient = Policy.NoOpAsync()
            };

            IMessengerService messengerService = null;

            if (useServiceBus)
            {
                messengerService = Substitute.For <IMessengerService, IServiceBusService>();
            }
            else
            {
                messengerService = Substitute.For <IMessengerService, IQueueService>();
            }

            ILogger logger = Substitute.For <ILogger>();

            JobManagement jobManagement = new JobManagement(jobsApiClient, logger, policies, messengerService);

            string jobId = "3456";

            jobsApiClient
            .GetLatestJobsForSpecification("specificationId", Arg.Is <string[]>(_ => _.Single() == "PopulateScopedProviders"))
            .Returns(new ApiResponse <IDictionary <string, JobSummary> >(HttpStatusCode.OK, new Dictionary <string, JobSummary> {
                { string.Empty, new JobSummary {
                      RunningStatus = RunningStatus.Completed, CompletionStatus = CompletionStatus.Failed, JobId = jobId
                  } }
            }));

            messengerService
            .ReceiveMessage("topic/Subscriptions/correlationId", Arg.Any <Predicate <JobSummary> >(), TimeSpan.FromMilliseconds(600000))
            .Returns(new JobSummary
            {
                CompletionStatus = CompletionStatus.Failed
            });

            //Act
            bool jobsComplete = await jobManagement.QueueJobAndWait(async() => await Task.Run(() => { return(true); }), "PopulateScopedProviders", "specificationId", "correlationId", "topic");

            //Assert
            if (useServiceBus)
            {
                await((IServiceBusService)messengerService)
                .Received(1)
                .CreateSubscription("topic", "correlationId", Arg.Is <TimeSpan>(_ => _.Days == 1));

                await messengerService
                .Received(1)
                .ReceiveMessage("topic/Subscriptions/correlationId", Arg.Any <Predicate <JobSummary> >(), TimeSpan.FromMilliseconds(600000));
            }

            jobsComplete
            .Should()
            .BeFalse();
        }
Beispiel #8
0
        public async Task QueueCsvGenerationMessages_GivenSpecificationSummariesFoundAndHasNewResults_CreatesNewMessage()
        {
            //Arrange
            IEnumerable <SpecificationSummary> specificationSummaries = new[]
            {
                new SpecificationSummary {
                    Id = "spec-1"
                }
            };

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .GetSpecificationSummaries()
            .Returns(specificationSummaries);

            ICalculationResultsRepository calculationResultsRepository = CreateResultsRepository();

            calculationResultsRepository
            .CheckHasNewResultsForSpecificationIdAndTimePeriod(
                Arg.Is("spec-1"),
                Arg.Any <DateTimeOffset>(),
                Arg.Any <DateTimeOffset>())
            .Returns(true);

            ILogger logger = CreateLogger();

            IMessengerService messengerService = CreateMessengerService();

            ResultsService resultsService = CreateResultsService(
                logger,
                specificationsRepository: specificationsRepository,
                resultsRepository: calculationResultsRepository,
                messengerService: messengerService);

            //Act
            await resultsService.QueueCsvGenerationMessages();

            //Assert
            await
            messengerService
            .Received(1)
            .SendToQueue(
                Arg.Is(ServiceBusConstants.QueueNames.CalculationResultsCsvGeneration),
                Arg.Is(string.Empty),
                Arg.Is <Dictionary <string, string> >(m => m["specification-id"] == "spec-1"), Arg.Is(false));

            logger
            .Received()
            .Information($"Found new calculation results for specification id 'spec-1'");
        }
        public void ShouldExecuteRegisterCommandWhenDriverIsValid()
        {
            var sut = new RegisterDriverViewModel(_driverServiceMock, _driverViewModelMapperMock,
                                                  _messengerServiceMock);

            sut.CurrentDriver.FirstName     = "Valid";
            sut.CurrentDriver.LastName      = "Valid";
            sut.CurrentDriver.LicenseNumber = "Valid";
            sut.RegisterDriverCommand.Execute(null);
            _driverViewModelMapperMock.Received().Map(sut.CurrentDriver);
            _driverServiceMock.Received().CreateDriver(Arg.Any <DriverDTO>());
            _messengerServiceMock.Received()
            .Send(Arg.Is <NotificationMessage>(m => m.Notification == "Close Register Window"));
        }
Beispiel #10
0
        public async Task ReIndexAllocationNotificationFeeds_GivenRequest_AddsServiceBusMessage()
        {
            //Arrange
            string          userId    = "1234";
            string          userName  = "******";
            ClaimsPrincipal principle = new ClaimsPrincipal(new[]
            {
                new ClaimsIdentity(new [] { new Claim(ClaimTypes.Sid, userId), new Claim(ClaimTypes.Name, userName) })
            });

            HttpContext context = Substitute.For <HttpContext>();

            context
            .User
            .Returns(principle);

            HttpRequest request = Substitute.For <HttpRequest>();

            request
            .HttpContext
            .Returns(context);

            IMessengerService messengerService = CreateMessengerService();

            PublishedResultsService resultsService = CreateResultsService(messengerService: messengerService);

            //Act
            IActionResult actionResult = await resultsService.ReIndexAllocationNotificationFeeds(request);

            //Assert
            actionResult
            .Should()
            .BeAssignableTo <NoContentResult>();

            await
            messengerService
            .Received(1)
            .SendToQueue(
                Arg.Is(ServiceBusConstants.QueueNames.ReIndexAllocationNotificationFeedIndex),
                Arg.Is(string.Empty),
                Arg.Is <IDictionary <string, string> >(m => m["user-id"] == userId && m["user-name"] == userName));
        }
Beispiel #11
0
        async public Task SaveDefinition_GivenValidYamlAndDoesContainsExistingItemWithModelUpdates_ThenAddsMessageToTopicAndReturnsOK()
        {
            //Arrange
            string yaml         = CreateRawDefinition();
            string definitionId = "9183";

            byte[]       byteArray = Encoding.UTF8.GetBytes(yaml);
            MemoryStream stream    = new MemoryStream(byteArray);

            IHeaderDictionary headerDictionary = new HeaderDictionary();

            headerDictionary
            .Add("yaml-file", new StringValues(yamlFile));

            HttpRequest request = Substitute.For <HttpRequest>();

            request
            .Headers
            .Returns(headerDictionary);

            request
            .Body
            .Returns(stream);

            ILogger logger = CreateLogger();

            HttpStatusCode statusCode = HttpStatusCode.Created;

            DatasetDefinition existingDatasetDefinition = new DatasetDefinition
            {
                Id = definitionId
            };

            IDatasetRepository datasetsRepository = CreateDataSetsRepository();

            datasetsRepository
            .SaveDefinition(Arg.Any <DatasetDefinition>())
            .Returns(statusCode);

            datasetsRepository
            .GetDatasetDefinition(Arg.Is(definitionId))
            .Returns(existingDatasetDefinition);

            byte[] excelAsBytes = new byte[100];

            IExcelWriter <DatasetDefinition> excelWriter = CreateExcelWriter();

            excelWriter
            .Write(Arg.Any <DatasetDefinition>())
            .Returns(excelAsBytes);

            ICloudBlob blob = Substitute.For <ICloudBlob>();

            IBlobClient blobClient = CreateBlobClient();

            blobClient
            .GetBlockBlobReference(Arg.Any <string>())
            .Returns(blob);

            DatasetDefinitionChanges datasetDefinitionChanges = new DatasetDefinitionChanges();

            datasetDefinitionChanges.DefinitionChanges.Add(DefinitionChangeType.DefinitionName);

            IDefinitionChangesDetectionService definitionChangesDetectionService = CreateChangesDetectionService();

            definitionChangesDetectionService
            .DetectChanges(Arg.Any <DatasetDefinition>(), Arg.Is(existingDatasetDefinition))
            .Returns(datasetDefinitionChanges);

            IMessengerService messengerService = CreateMessengerService();

            DefinitionsService service = CreateDefinitionsService(
                logger,
                datasetsRepository,
                excelWriter: excelWriter,
                blobClient: blobClient,
                definitionChangesDetectionService: definitionChangesDetectionService,
                messengerService: messengerService);

            //Act
            IActionResult result = await service.SaveDefinition(request);

            //Assert
            result
            .Should()
            .BeOfType <OkResult>();

            await
            messengerService
            .Received(1)
            .SendToTopic(
                Arg.Is(ServiceBusConstants.TopicNames.DataDefinitionChanges),
                Arg.Is(datasetDefinitionChanges),
                Arg.Any <IDictionary <string, string> >());
        }
Beispiel #12
0
        public async Task EditPolicy_WhenValidModelAndUpdateCosmosAndIsASubPolicy_SendsMessageAndReturnsOK()
        {
            // Arrange
            PolicyEditModel policyEditModel = new PolicyEditModel
            {
                SpecificationId = SpecificationId,
                Name            = "new policy name",
                Description     = "new policy description",
                ParentPolicyId  = "parent-policy-id"
            };

            string json = JsonConvert.SerializeObject(policyEditModel);

            byte[]       byteArray = Encoding.UTF8.GetBytes(json);
            MemoryStream stream    = new MemoryStream(byteArray);

            HttpContext context = Substitute.For <HttpContext>();

            HttpRequest request = Substitute.For <HttpRequest>();

            IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "specificationId", new StringValues(SpecificationId) },
                { "policyId", new StringValues(PolicyId) },
            });

            request
            .Query
            .Returns(queryStringValues);
            request
            .Body
            .Returns(stream);

            request
            .HttpContext
            .Returns(context);

            Specification specification = CreateSpecification();

            specification
            .Current
            .Policies = new[]
            {
                new Policy
                {
                    Id          = "parent-policy-id",
                    Name        = "policy name",
                    SubPolicies = new[] { new Policy {
                                              Id = PolicyId, Name = PolicyName
                                          } }
                }
            };

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .GetSpecificationById(Arg.Is(SpecificationId))
            .Returns(specification);

            specificationsRepository
            .UpdateSpecification(Arg.Is(specification))
            .Returns(HttpStatusCode.OK);

            IMessengerService messengerService = CreateMessengerService();

            ISearchRepository <SpecificationIndex> mockSearchRepository = CreateSearchRepository();

            mockSearchRepository
            .Index(Arg.Any <IEnumerable <SpecificationIndex> >())
            .Returns(new List <IndexError>());

            SpecificationVersion newSpecVersion = specification.Current.Clone() as SpecificationVersion;
            Policy editedNewSubpolicy           = newSpecVersion.Policies.First().SubPolicies.First();

            editedNewSubpolicy.Name      = policyEditModel.Name;
            newSpecVersion.PublishStatus = PublishStatus.Updated;

            IVersionRepository <SpecificationVersion> mockVersionRepository = CreateVersionRepository();

            mockVersionRepository
            .CreateVersion(Arg.Any <SpecificationVersion>(), Arg.Any <SpecificationVersion>())
            .Returns(newSpecVersion);

            SpecificationsService specificationsService = CreateService(specificationsRepository: specificationsRepository,
                                                                        messengerService: messengerService, searchRepository: mockSearchRepository, specificationVersionRepository: mockVersionRepository);

            // Act
            IActionResult result = await specificationsService.EditPolicy(request);

            // Assert
            result
            .Should()
            .BeOfType <OkObjectResult>()
            .Which
            .Value
            .Should()
            .BeOfType <Policy>()
            .Which
            .Description
            .Should()
            .Be("new policy description");

            await
            messengerService
            .Received(1)
            .SendToTopic(Arg.Is(ServiceBusConstants.TopicNames.EditSpecification),
                         Arg.Is <SpecificationVersionComparisonModel>(
                             m => m.Id == SpecificationId
                             ), Arg.Any <IDictionary <string, string> >(), Arg.Is(true));

            await
            mockSearchRepository
            .Received(1)
            .Index(Arg.Is <IEnumerable <SpecificationIndex> >(
                       m => m.First().Id == SpecificationId &&
                       m.First().Status == newSpecVersion.PublishStatus.ToString()
                       ));
        }
Beispiel #13
0
        public async Task EditSpecification_GivenChangesAndSpecContainsPoliciesAndCalculations_UpdatesSearchAndSendsMessage()
        {
            //Arrange
            SpecificationEditModel specificationEditModel = new SpecificationEditModel
            {
                FundingPeriodId  = "fp10",
                Name             = "new spec name",
                FundingStreamIds = new[] { "fs11" }
            };

            Period fundingPeriod = new Period
            {
                Id   = "fp10",
                Name = "fp 10"
            };

            IEnumerable <FundingStream> fundingStreams = new[]
            {
                new FundingStream {
                    AllocationLines = new List <AllocationLine>
                    {
                        new AllocationLine {
                            Id = "al1", Name = "al2"
                        }
                    }
                }
            };

            string json = JsonConvert.SerializeObject(specificationEditModel);

            byte[]       byteArray = Encoding.UTF8.GetBytes(json);
            MemoryStream stream    = new MemoryStream(byteArray);

            HttpContext context = Substitute.For <HttpContext>();

            HttpRequest request = Substitute.For <HttpRequest>();

            IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "specificationId", new StringValues(SpecificationId) },
            });

            request
            .Query
            .Returns(queryStringValues);
            request
            .Body
            .Returns(stream);

            request
            .HttpContext
            .Returns(context);

            ILogger logger = CreateLogger();

            Specification specification = CreateSpecification();

            specification
            .Current
            .Policies = new[]
            {
                new Policy
                {
                    Calculations = new[]
                    {
                        new Calculation {
                            AllocationLine = new AllocationLine {
                                Id = "oldallocationlineid"
                            }
                        }
                    }
                }
            };

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .GetSpecificationById(Arg.Is(SpecificationId))
            .Returns(specification);

            specificationsRepository
            .GetPeriodById(Arg.Is(fundingPeriod.Id))
            .Returns(fundingPeriod);

            specificationsRepository
            .GetFundingStreams(Arg.Any <Expression <Func <FundingStream, bool> > >())
            .Returns(fundingStreams);

            specificationsRepository
            .UpdateSpecification(Arg.Any <Specification>())
            .Returns(HttpStatusCode.OK);

            ISearchRepository <SpecificationIndex> searchRepository = CreateSearchRepository();

            ICacheProvider cacheProvider = CreateCacheProvider();

            IMessengerService messengerService = CreateMessengerService();

            SpecificationVersion newSpecVersion = specification.Current.Clone() as SpecificationVersion;

            newSpecVersion.Name             = specificationEditModel.Name;
            newSpecVersion.FundingPeriod.Id = specificationEditModel.FundingPeriodId;
            newSpecVersion.FundingStreams   = new[] { new FundingStream {
                                                          Id = "fs11"
                                                      } };

            IVersionRepository <SpecificationVersion> versionRepository = CreateVersionRepository();

            versionRepository
            .CreateVersion(Arg.Any <SpecificationVersion>(), Arg.Any <SpecificationVersion>())
            .Returns(newSpecVersion);

            SpecificationsService service = CreateService(
                logs: logger, specificationsRepository: specificationsRepository, searchRepository: searchRepository,
                cacheProvider: cacheProvider, messengerService: messengerService, specificationVersionRepository: versionRepository);

            //Act
            IActionResult result = await service.EditSpecification(request);

            //Arrange
            await
            searchRepository
            .Received(1)
            .Index(Arg.Is <IEnumerable <SpecificationIndex> >(
                       m => m.First().Id == SpecificationId &&
                       m.First().Name == "new spec name" &&
                       m.First().FundingPeriodId == "fp10" &&
                       m.First().FundingStreamIds.Count() == 1
                       ));

            await
            cacheProvider
            .Received(1)
            .RemoveAsync <SpecificationSummary>(Arg.Is($"{CacheKeys.SpecificationSummaryById}{specification.Id}"));

            await
            messengerService
            .Received(1)
            .SendToTopic(Arg.Is(ServiceBusConstants.TopicNames.EditSpecification),
                         Arg.Is <SpecificationVersionComparisonModel>(
                             m => m.Id == SpecificationId &&
                             m.Current.Name == "new spec name" &&
                             m.Previous.Name == "Spec name"
                             ), Arg.Any <IDictionary <string, string> >(), Arg.Is(true));

            await
            versionRepository
            .Received(1)
            .SaveVersion(Arg.Is(newSpecVersion));
        }
        public async Task EditCalculation_WhenCalcInSubPolicyButNotTopLevelPolicyUpdatesCosmos_SendsMessageReturnsOk()
        {
            // Arrange
            CalculationEditModel policyEditModel = new CalculationEditModel
            {
                Name            = "new calc name",
                CalculationType = CalculationType.Funding,
                Description     = "test description",
                PolicyId        = "policy-id-2"
            };

            string json = JsonConvert.SerializeObject(policyEditModel);

            byte[]       byteArray = Encoding.UTF8.GetBytes(json);
            MemoryStream stream    = new MemoryStream(byteArray);

            HttpContext context = Substitute.For <HttpContext>();

            HttpRequest request = Substitute.For <HttpRequest>();

            IQueryCollection queryStringValues = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "specificationId", new StringValues(SpecificationId) },
                { "calculationId", new StringValues(CalculationId) },
            });

            request
            .Query
            .Returns(queryStringValues);
            request
            .Body
            .Returns(stream);

            request
            .HttpContext
            .Returns(context);

            Specification specification = CreateSpecification();

            specification
            .Current
            .Policies = new[] {
                new Policy {
                    Id = PolicyId, Name = PolicyName, SubPolicies = new[] { new Policy {
                                                                                Id = "policy-id-2", Name = "sub-policy", Calculations = new[] { new Calculation {
                                                                                                                                                    Id = CalculationId, Name = "Old name"
                                                                                                                                                } }
                                                                            } }
                }
            };

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .GetSpecificationById(Arg.Is(SpecificationId))
            .Returns(specification);

            specificationsRepository
            .UpdateSpecification(Arg.Is(specification))
            .Returns(HttpStatusCode.OK);

            ICacheProvider cacheProvider = CreateCacheProvider();

            IMessengerService messengerService = CreateMessengerService();

            SpecificationVersion newSpecVersion = specification.Current.Clone() as SpecificationVersion;

            newSpecVersion.Policies.First().SubPolicies.First().Calculations = new[] { new Calculation {
                                                                                           Id = CalculationId, Name = "new calc name"
                                                                                       } };

            IVersionRepository <SpecificationVersion> versionRepository = CreateVersionRepository();

            versionRepository
            .CreateVersion(Arg.Any <SpecificationVersion>(), Arg.Any <SpecificationVersion>())
            .Returns(newSpecVersion);

            SpecificationsService specificationsService = CreateService(specificationsRepository: specificationsRepository,
                                                                        cacheProvider: cacheProvider, messengerService: messengerService, specificationVersionRepository: versionRepository);

            // Act
            IActionResult result = await specificationsService.EditCalculation(request);

            // Assert
            result
            .Should()
            .BeOfType <OkObjectResult>();

            specification
            .Current
            .Policies
            .First()
            .SubPolicies
            .First()
            .Calculations
            .First()
            .Name
            .Should()
            .Be("new calc name");

            await
            messengerService
            .Received(1)
            .SendToTopic(Arg.Is(ServiceBusConstants.TopicNames.EditCalculation),
                         Arg.Is <CalculationVersionComparisonModel>(
                             m => m.CalculationId == CalculationId &&
                             m.SpecificationId == SpecificationId
                             ), Arg.Any <IDictionary <string, string> >());

            await
            versionRepository
            .Received(1)
            .SaveVersion(Arg.Is(newSpecVersion));
        }
        public async Task CreateCalculation_GivenValidModelForSubPolicyAndSubPolicyFoundAndUpdated_ReturnsOK()
        {
            //Arrange
            AllocationLine allocationLine = new AllocationLine
            {
                Id   = "02a6eeaf-e1a0-476e-9cf9-8aa5d9129345",
                Name = "test alloctaion"
            };

            List <FundingStream> fundingStreams = new List <FundingStream>();

            FundingStream fundingStream = new FundingStream
            {
                AllocationLines = new List <AllocationLine>
                {
                    allocationLine
                },
                Id = FundingStreamId
            };

            fundingStreams.Add(fundingStream);

            Policy policy = new Policy
            {
                Id   = PolicyId,
                Name = PolicyName,
            };

            Specification specification = CreateSpecification();

            specification.Current.Policies       = new[] { policy };
            specification.Current.FundingStreams = new List <Reference>()
            {
                new Reference {
                    Id = FundingStreamId
                }
            };

            CalculationCreateModel model = new CalculationCreateModel
            {
                SpecificationId  = SpecificationId,
                PolicyId         = PolicyId,
                AllocationLineId = AllocationLineId
            };

            string json = JsonConvert.SerializeObject(model);

            byte[]       byteArray = Encoding.UTF8.GetBytes(json);
            MemoryStream stream    = new MemoryStream(byteArray);

            ClaimsPrincipal principle = new ClaimsPrincipal(new[]
            {
                new ClaimsIdentity(new [] { new Claim(ClaimTypes.Sid, UserId), new Claim(ClaimTypes.Name, Username) })
            });

            HttpContext context = Substitute.For <HttpContext>();

            context
            .User
            .Returns(principle);

            HttpRequest request = Substitute.For <HttpRequest>();

            request
            .Body
            .Returns(stream);

            request
            .HttpContext
            .Returns(context);

            IHeaderDictionary headerDictionary = new HeaderDictionary();

            headerDictionary
            .Add("sfa-correlationId", new StringValues(SfaCorrelationId));

            request
            .Headers
            .Returns(headerDictionary);

            ILogger logger = CreateLogger();

            ISpecificationsRepository specificationsRepository = CreateSpecificationsRepository();

            specificationsRepository
            .GetSpecificationById(Arg.Is(SpecificationId))
            .Returns(specification);

            specificationsRepository
            .GetFundingStreams(Arg.Any <Expression <Func <FundingStream, bool> > >())
            .Returns(fundingStreams);

            specificationsRepository
            .UpdateSpecification(Arg.Is(specification))
            .Returns(HttpStatusCode.OK);

            Calculation calculation = new Calculation
            {
                AllocationLine = new Reference()
            };

            IMapper mapper = CreateMapper();

            mapper
            .Map <Calculation>(Arg.Any <CalculationCreateModel>())
            .Returns(calculation);

            IMessengerService messengerService = CreateMessengerService();

            SpecificationVersion newSpecVersion = specification.Current.Clone() as SpecificationVersion;

            newSpecVersion.PublishStatus = PublishStatus.Updated;
            newSpecVersion.Version       = 2;

            IVersionRepository <SpecificationVersion> mockVersionRepository = CreateVersionRepository();

            mockVersionRepository
            .CreateVersion(Arg.Any <SpecificationVersion>(), Arg.Any <SpecificationVersion>())
            .Returns(newSpecVersion);

            SpecificationsService service = CreateService(logs: logger, specificationsRepository: specificationsRepository,
                                                          mapper: mapper, messengerService: messengerService, specificationVersionRepository: mockVersionRepository);

            //Act
            IActionResult result = await service.CreateCalculation(request);

            //Assert
            result
            .Should()
            .BeOfType <OkObjectResult>();

            await
            messengerService
            .Received(1)
            .SendToQueue(Arg.Is("calc-events-create-draft"),
                         Arg.Is <Models.Calcs.Calculation>(m =>
                                                           m.CalculationSpecification.Id == calculation.Id &&
                                                           m.CalculationSpecification.Name == calculation.Name &&
                                                           m.Name == calculation.Name &&
                                                           !string.IsNullOrEmpty(m.Id) &&
                                                           m.AllocationLine.Id == allocationLine.Id &&
                                                           m.AllocationLine.Name == allocationLine.Name),
                         Arg.Is <IDictionary <string, string> >(m =>
                                                                m["user-id"] == UserId &&
                                                                m["user-name"] == Username &&
                                                                m["sfa-correlationId"] == SfaCorrelationId));
        }
Beispiel #16
0
        private static void CheckServiceBusCalls(IMessengerService messengerService, string uniqueId, string queueName, string topicName, string entityPathBase, bool useSession)
        {
            if (!IsDevelopment && topicName != null)
            {
                if (useSession)
                {
                    messengerService
                    .Received(1)
                    .SendToTopic(topicName,
                                 uniqueId,
                                 Arg.Any <Dictionary <string, string> >(),
                                 sessionId: uniqueId);
                }
                else
                {
                    messengerService
                    .Received(1)
                    .SendToTopic(topicName,
                                 uniqueId,
                                 Arg.Any <Dictionary <string, string> >());
                }
            }
            else
            {
                if (useSession)
                {
                    messengerService
                    .Received(1)
                    .SendToQueue(queueName,
                                 uniqueId,
                                 Arg.Any <Dictionary <string, string> >(),
                                 sessionId: uniqueId);
                }
                else
                {
                    messengerService
                    .Received(1)
                    .SendToQueue(queueName,
                                 uniqueId,
                                 Arg.Any <Dictionary <string, string> >());
                }
            }

            if (!IsDevelopment)
            {
                ((IServiceBusService)messengerService)
                .Received(1)
                .CreateSubscription("smoketest", uniqueId, Arg.Is <TimeSpan>(_ => _.Days == 1));

                ((IServiceBusService)messengerService)
                .Received(1)
                .DeleteSubscription("smoketest", uniqueId);
            }
            else
            {
                ((IQueueService)messengerService)
                .Received(1)
                .DeleteQueue(uniqueId);
            }

            messengerService
            .Received(1)
            .ReceiveMessage <SmokeResponse>(entityPathBase,
                                            Arg.Any <Predicate <SmokeResponse> >(),
                                            _timeout);
        }