Beispiel #1
0
        public TestEngineService(
            ICacheProvider cacheProvider,
            ISpecificationRepository specificationRepository,
            ILogger logger,
            ITestEngine testEngine,
            IScenariosRepository scenariosRepository,
            IProviderSourceDatasetsRepository providerSourceDatasetsRepository,
            ITestResultsService testResultsService,
            ITestResultsRepository testResultsRepository,
            IBuildProjectRepository buildProjectRepository,
            ITelemetry telemetry,
            ITestRunnerResiliencePolicies resiliencePolicies,
            ICalculationsRepository calculationsRepository)
        {
            _cacheProvider           = cacheProvider;
            _specificationRepository = specificationRepository;
            _logger              = logger;
            _testEngine          = testEngine;
            _scenariosRepository = scenariosRepository;
            _providerSourceDatasetsRepository = providerSourceDatasetsRepository;
            _testResultsService    = testResultsService;
            _testResultsRepository = testResultsRepository;
            _telemetry             = telemetry;

            _cacheProviderPolicy                    = resiliencePolicies.CacheProviderRepository;
            _specificationRepositoryPolicy          = resiliencePolicies.SpecificationRepository;
            _scenariosRepositoryPolicy              = resiliencePolicies.ScenariosRepository;
            _providerSourceDatasetsRepositoryPolicy = resiliencePolicies.ProviderSourceDatasetsRepository;
            _testResultsRepositoryPolicy            = resiliencePolicies.TestResultsRepository;
            _builProjectsRepositoryPolicy           = resiliencePolicies.BuildProjectRepository;
            _buildProjectRepository                 = buildProjectRepository;
            _calculationsRepository                 = calculationsRepository;
        }
Beispiel #2
0
        public async Task IsCalculationNameValid_WhenCalculationDoesNotExist_ThenReturnsOkResult()
        {
            // Arrange
            string specificationId = "spec1";

            ISpecificationRepository specificationRepository = CreateSpecificationRepository();

            specificationRepository
            .GetSpecificationSummaryById(Arg.Is(specificationId))
            .Returns(new SpecificationSummary {
                Id = specificationId
            });

            ICalculationsRepository calculationsRepository = CreateCalculationsRepository();

            calculationsRepository
            .GetCalculationsBySpecificationId(Arg.Is(specificationId))
            .Returns(new List <Models.Calcs.Calculation>());

            CalculationService service = CreateCalculationService(specificationRepository: specificationRepository, calculationsRepository: calculationsRepository);

            // Act
            IActionResult result = await service.IsCalculationNameValid(specificationId, "calc1", null);

            // Assert
            result
            .Should()
            .BeOfType <OkResult>();
        }
Beispiel #3
0
 public DeprecateDataEntryHandler(IVmsLogger <DeprecateDataEntryHandler> logger, IServiceBusMessagePublisher publisher, ISpecificationRepository repository, ISpecificationAggregate specificationAggregate)
 {
     _logger                 = logger;
     _publisher              = publisher;
     _repository             = repository;
     _specificationAggregate = specificationAggregate;
 }
        public FundingStreamPermissionService(
            IUserRepository userRepository,
            ISpecificationRepository specificationRepository,
            IVersionRepository <FundingStreamPermissionVersion> fundingStreamPermissionVersionRepository,
            ICacheProvider cacheProvider,
            IMapper mapper,
            ILogger logger,
            IUsersResiliencePolicies policies)
        {
            Guard.ArgumentNotNull(userRepository, nameof(userRepository));
            Guard.ArgumentNotNull(specificationRepository, nameof(specificationRepository));
            Guard.ArgumentNotNull(fundingStreamPermissionVersionRepository, nameof(fundingStreamPermissionVersionRepository));
            Guard.ArgumentNotNull(cacheProvider, nameof(cacheProvider));
            Guard.ArgumentNotNull(mapper, nameof(mapper));
            Guard.ArgumentNotNull(logger, nameof(logger));
            Guard.ArgumentNotNull(policies, nameof(policies));

            _userRepository           = userRepository;
            _specificationsRepository = specificationRepository;
            _fundingStreamPermissionVersionRepository = fundingStreamPermissionVersionRepository;
            _cacheProvider = cacheProvider;
            _mapper        = mapper;
            _logger        = logger;

            _userRepositoryPolicy           = policies.UserRepositoryPolicy;
            _specificationsRepositoryPolicy = policies.SpecificationRepositoryPolicy;
            _fundingStreamPermissionVersionRepositoryPolicy = policies.FundingStreamPermissionVersionRepositoryPolicy;
            _cacheProviderPolicy = policies.CacheProviderPolicy;
        }
Beispiel #5
0
 private static CalculationService CreateCalculationService(
     ICalculationsRepository calculationsRepository = null,
     ILogger logger = null,
     ISearchRepository <CalculationIndex> searchRepository = null,
     IValidator <Calculation> calcValidator           = null,
     IBuildProjectsService buildProjectsService       = null,
     ISpecificationRepository specificationRepository = null,
     ICacheProvider cacheProvider = null,
     ICalcsResiliencePolicies resiliencePolicies = null,
     IVersionRepository <CalculationVersion> calculationVersionRepository = null,
     IJobsApiClient jobsApiClient                     = null,
     ISourceCodeService sourceCodeService             = null,
     IFeatureToggle featureToggle                     = null,
     IBuildProjectsRepository buildProjectsRepository = null,
     ICalculationCodeReferenceUpdate calculationCodeReferenceUpdate = null)
 {
     return(new CalculationService
                (calculationsRepository ?? CreateCalculationsRepository(),
                logger ?? CreateLogger(),
                searchRepository ?? CreateSearchRepository(),
                calcValidator ?? CreateCalculationValidator(),
                buildProjectsService ?? CreateBuildProjectsService(),
                specificationRepository ?? CreateSpecificationRepository(),
                cacheProvider ?? CreateCacheProvider(),
                resiliencePolicies ?? CalcsResilienceTestHelper.GenerateTestPolicies(),
                calculationVersionRepository ?? CreateCalculationVersionRepository(),
                jobsApiClient ?? CreateJobsApiClient(),
                sourceCodeService ?? CreateSourceCodeService(),
                featureToggle ?? CreateFeatureToggle(),
                buildProjectsRepository ?? CreateBuildProjectsRepository(),
                calculationCodeReferenceUpdate ?? CreateCalculationCodeReferenceUpdate()));
 }
Beispiel #6
0
 public UpdateEntryOrderHandler(IVmsLogger <UpdateEntryOrderHandler> logger, IServiceBusMessagePublisher publisher, ISpecificationRepository repository, ISpecificationAggregate specificationAggregate)
 {
     _logger                 = logger;
     _publisher              = publisher;
     _repository             = repository;
     _specificationAggregate = specificationAggregate;
 }
Beispiel #7
0
 public CreateDataEntryHandler(IVmsLogger <CreateDataEntryHandler> logger, IServiceBusMessagePublisher publisher, ISpecificationAggregate aggregate, ISpecificationRepository repository)
 {
     _logger     = logger;
     _publisher  = publisher;
     _aggregate  = aggregate;
     _repository = repository;
 }
        /// <summary>
        /// Loads the data
        /// </summary>
        /// <returns></returns>
        public override async Task LoadDataGridData()
        {
            _specRepo = new SpecificationRepository();

            // Gets all the specifications, and maps it to objects fit to display in the datagrid
            SpecList = new ObservableCollection <SpecificationOverviewItem>
                           (EntitiesMapping.MapToSpecificationOverviewItem(await _specRepo.GetAllAsync(), _preferredLanguage.ID)
                           .OrderBy(x => x.SpecName).ToList());

            BindData();
        }
        public void CreateCalculation_CreatingCalculationButAssociatedCalculationSpecificationNotFound_ThrowsException()
        {
            //Arrange
            Calculation calculation = CreateCalculation();

            IEnumerable <Calculation> calculations = new[]
            {
                calculation
            };
            string json = JsonConvert.SerializeObject(calculation);

            IEnumerable <Models.Specs.Calculation> calculationSpecifications = new[]
            {
                new Models.Specs.Calculation
                {
                    Id = "any-id"
                }
            };

            Message message = new Message(Encoding.UTF8.GetBytes(json));

            message.UserProperties.Add("user-id", UserId);
            message.UserProperties.Add("user-name", Username);

            ILogger logger = CreateLogger();

            ISearchRepository <CalculationIndex> searchRepository = CreateSearchRepository();

            Models.Specs.SpecificationSummary specificationSummary = new Models.Specs.SpecificationSummary()
            {
                Id   = calculation.SpecificationId,
                Name = "Test Spec Name",
            };

            ISpecificationRepository specificationRepository = CreateSpecificationRepository();

            specificationRepository
            .GetSpecificationSummaryById(Arg.Is(calculation.SpecificationId))
            .Returns(specificationSummary);

            specificationRepository
            .GetCalculationSpecificationsForSpecification(Arg.Is(calculation.SpecificationId))
            .Returns(calculationSpecifications);

            CalculationService service = CreateCalculationService(logger: logger, searchRepository: searchRepository, specificationRepository: specificationRepository);

            //Act
            Func <Task> test = async() => await service.CreateCalculation(message);

            //Assert
            test
            .Should().ThrowExactly <RetriableException>()
            .WithMessage($"A calculation specification was not found for calculation specification id '{calculation.CalculationSpecification.Id}'");
        }
        public static IQueryable <TEntity> GetQuery(IQueryable <TEntity> inputQuery
                                                    , ISpecificationRepository <TEntity> specification)
        {
            var query = inputQuery;

            if (specification.criteria != null)
            {
                query = query.Where(specification.criteria);
            }
            query = specification.Includes.Aggregate(query, (current, include) => current.Include(include));
            return(query);
        }
Beispiel #11
0
        public void SetupTest()
        {
            _logger = Substitute.For <ILogger>();
            _calculationRepository   = Substitute.For <ICalculationRepository>();
            _specificationRepository = Substitute.For <ISpecificationRepository>();
            _datasetRepository       = Substitute.For <IDatasetRepository>();
            _fundingLineRepository   = Substitute.For <IFundingLineRepository>();

            _graphService = new GraphService(_logger,
                                             _calculationRepository,
                                             _specificationRepository,
                                             _datasetRepository,
                                             _fundingLineRepository);
        }
Beispiel #12
0
        public async Task GetEffectivePermissionsForUser_WhenNotFoundInCacheButSpecificationNotFound_ThenPreconditionFailedResultReturned()
        {
            // Arrange
            ICacheProvider cacheProvider = CreateCacheProvider();
            EffectiveSpecificationPermission cachedPermission = null;

            cacheProvider
            .GetHashValue <EffectiveSpecificationPermission>(Arg.Is($"{CacheKeys.EffectivePermissions}:{UserId}"), Arg.Is(SpecificationId))
            .Returns(cachedPermission);

            ISpecificationRepository specificationRepository = CreateSpecificationRepository();

            SpecificationSummary specificationSummary = null;

            specificationRepository
            .GetSpecificationSummaryById(Arg.Is(SpecificationId))
            .Returns(specificationSummary);

            FundingStreamPermissionService service = CreateService(
                specificationRepository: specificationRepository,
                cacheProvider: cacheProvider);


            // Act
            IActionResult result = await service.GetEffectivePermissionsForUser(UserId, SpecificationId, null);

            // Assert
            result
            .Should()
            .BeOfType <PreconditionFailedResult>()
            .Which
            .Value
            .Should()
            .Be("Specification not found");

            await cacheProvider
            .Received(1)
            .GetHashValue <EffectiveSpecificationPermission>(Arg.Is($"{CacheKeys.EffectivePermissions}:{UserId}"), Arg.Is(SpecificationId));

            await cacheProvider
            .Received(0)
            .SetHashValue(
                Arg.Is($"{CacheKeys.EffectivePermissions}:{UserId}"),
                Arg.Is(SpecificationId),
                Arg.Any <EffectiveSpecificationPermission>());
        }
        public BuildProjectsService(
            ILogger logger,
            ITelemetry telemetry,
            IProviderResultsRepository providerResultsRepository,
            ISpecificationRepository specificationsRepository,
            ICacheProvider cacheProvider,
            ICalculationsRepository calculationsRepository,
            IFeatureToggle featureToggle,
            IJobsApiClient jobsApiClient,
            ICalcsResiliencePolicies resiliencePolicies,
            EngineSettings engineSettings,
            ISourceCodeService sourceCodeService,
            IDatasetRepository datasetRepository,
            IBuildProjectsRepository buildProjectsRepository)
        {
            Guard.ArgumentNotNull(logger, nameof(logger));
            Guard.ArgumentNotNull(telemetry, nameof(telemetry));
            Guard.ArgumentNotNull(providerResultsRepository, nameof(providerResultsRepository));
            Guard.ArgumentNotNull(specificationsRepository, nameof(specificationsRepository));
            Guard.ArgumentNotNull(cacheProvider, nameof(cacheProvider));
            Guard.ArgumentNotNull(calculationsRepository, nameof(calculationsRepository));
            Guard.ArgumentNotNull(featureToggle, nameof(featureToggle));
            Guard.ArgumentNotNull(jobsApiClient, nameof(jobsApiClient));
            Guard.ArgumentNotNull(resiliencePolicies, nameof(resiliencePolicies));
            Guard.ArgumentNotNull(engineSettings, nameof(engineSettings));
            Guard.ArgumentNotNull(sourceCodeService, nameof(sourceCodeService));
            Guard.ArgumentNotNull(datasetRepository, nameof(datasetRepository));
            Guard.ArgumentNotNull(buildProjectsRepository, nameof(buildProjectsRepository));

            _logger    = logger;
            _telemetry = telemetry;
            _providerResultsRepository     = providerResultsRepository;
            _specificationsRepository      = specificationsRepository;
            _cacheProvider                 = cacheProvider;
            _calculationsRepository        = calculationsRepository;
            _featureToggle                 = featureToggle;
            _jobsApiClient                 = jobsApiClient;
            _jobsApiClientPolicy           = resiliencePolicies.JobsApiClient;
            _engineSettings                = engineSettings;
            _sourceCodeService             = sourceCodeService;
            _datasetRepository             = datasetRepository;
            _datasetRepositoryPolicy       = resiliencePolicies.DatasetsRepository;
            _buildProjectsRepository       = buildProjectsRepository;
            _buildProjectsRepositoryPolicy = resiliencePolicies.BuildProjectRepositoryPolicy;
        }
Beispiel #14
0
        public SpecificationForm(int ID)
        {
            InitializeComponent();

            // Defines the progressbar and submit button to allow the progressbar methods to work in the FormUserControl(base)
            progressBar  = prog;
            submitButton = btnSubmit;

            _specRepo = new SpecificationRepository();

            SpecModel = _specRepo.Get(ID);

            _updatingPage = !SpecModel.IsNew();

            PrepareUpdate();

            DataContext = this;
        }
        public GraphService(ILogger logger,
                            ICalculationRepository calcRepository,
                            ISpecificationRepository specRepository,
                            IDatasetRepository datasetRepository,
                            IFundingLineRepository fundingLineRepository)
        {
            Guard.ArgumentNotNull(logger, nameof(logger));
            Guard.ArgumentNotNull(calcRepository, nameof(calcRepository));
            Guard.ArgumentNotNull(specRepository, nameof(specRepository));
            Guard.ArgumentNotNull(datasetRepository, nameof(datasetRepository));
            Guard.ArgumentNotNull(fundingLineRepository, nameof(fundingLineRepository));

            _logger                = logger;
            _calcRepository        = calcRepository;
            _specRepository        = specRepository;
            _datasetRepository     = datasetRepository;
            _fundingLineRepository = fundingLineRepository;
        }
Beispiel #16
0
        public async Task IsCalculationNameValid_WhenSameCalculation_ThenReturnsOkResult()
        {
            // Arrange
            string specificationId = "spec1";
            string calcName        = "calc1";
            string calcSpecId      = "calc-spec-id-1";

            ISpecificationRepository specificationRepository = CreateSpecificationRepository();

            specificationRepository
            .GetSpecificationSummaryById(Arg.Is(specificationId))
            .Returns(new SpecificationSummary {
                Id = specificationId
            });

            List <Models.Calcs.Calculation> existingCalcs = new List <Models.Calcs.Calculation>
            {
                new Models.Calcs.Calculation
                {
                    Name                     = calcName,
                    SourceCodeName           = calcName,
                    Id                       = "calc-1",
                    CalculationSpecification = new Common.Models.Reference {
                        Id = calcSpecId
                    }
                }
            };

            ICalculationsRepository calculationsRepository = CreateCalculationsRepository();

            calculationsRepository
            .GetCalculationsBySpecificationId(Arg.Is(specificationId))
            .Returns(existingCalcs);

            CalculationService service = CreateCalculationService(specificationRepository: specificationRepository, calculationsRepository: calculationsRepository);

            // Act
            IActionResult result = await service.IsCalculationNameValid(specificationId, calcName, calcSpecId);

            // Assert
            result
            .Should()
            .BeOfType <OkResult>();
        }
Beispiel #17
0
        /// <summary>
        /// Functionality that has to happen in both the create and update form
        /// </summary>
        private void InitializeWindow()
        {
            // Defines the progressBar and SubmitButton to allow the ProgressBar methods to work (see FormUserControl)
            progressBar  = prog;
            submitButton = btnSubmit;

            _langRepo = new LanguageRepository();
            _specRepo = new SpecificationRepository();

            // Sets display language
            _preferredLanguage = Properties.Settings.Default.CurrentUser.PreferredLanguage;
            SetLanguageDictionary();

            DataContext = this;

            _updatingPage = !CategoryModel.IsNew();

            SetTitle();
        }
Beispiel #18
0
 public FundingStreamPermissionService CreateService(
     IUserRepository userRepository = null,
     ISpecificationRepository specificationRepository = null,
     IVersionRepository <FundingStreamPermissionVersion> fundingStreamPermissionVersionRepository = null,
     ICacheProvider cacheProvider = null,
     IMapper mapper = null,
     ILogger logger = null,
     IUsersResiliencePolicies policies = null)
 {
     return(new FundingStreamPermissionService(
                userRepository ?? CreateUserRepository(),
                specificationRepository ?? CreateSpecificationRepository(),
                fundingStreamPermissionVersionRepository ?? CreateFundingStreamPermissionRepository(),
                cacheProvider ?? CreateCacheProvider(),
                mapper ?? CreateMappingConfiguration(),
                logger ?? CreateLogger(),
                policies ?? CreatePoliciesNoOp()
                ));
 }
 public AdminController(IBikeRepository bikeRepository,
                        ILogger <AdminController> logger,
                        IRepo <Size> sizeRepository,
                        IRepo <Color> colorRepository,
                        ICategoryRepository categoryRepository,
                        ISpecificationRepository specificaionRepository,
                        IRepo <SpecificationCategory> specificationCategoryRepository,
                        IRepo <ImgContent> imgRepo,
                        IMapper mapper)
 {
     _bikeRepo                  = bikeRepository ?? throw new ArgumentNullException(nameof(bikeRepository));
     _logger                    = logger ?? throw new ArgumentNullException(nameof(logger));
     _colorRepo                 = colorRepository ?? throw new ArgumentNullException(nameof(colorRepository));
     _sizeRepo                  = sizeRepository ?? throw new ArgumentNullException(nameof(sizeRepository));
     _categoryRepo              = categoryRepository ?? throw new ArgumentNullException(nameof(categoryRepository));
     _specificaionRepo          = specificaionRepository ?? throw new ArgumentNullException(nameof(specificaionRepository));
     _specificationCategoryRepo = specificationCategoryRepository ?? throw new ArgumentNullException(nameof(specificationCategoryRepository));
     _mapper                    = mapper ?? throw new ArgumentNullException(nameof(mapper));
     _imgRepo                   = imgRepo ?? throw new ArgumentNullException(nameof(imgRepo));
 }
Beispiel #20
0
        public async Task IsCalculationNameValid_WhenSpecificationDoesNotExist_ThenReturnsNotFoundResult()
        {
            // Arrange
            string specificationId = "spec1";

            ISpecificationRepository specificationRepository = CreateSpecificationRepository();

            specificationRepository
            .GetSpecificationSummaryById(Arg.Is(specificationId))
            .Returns((SpecificationSummary)null);

            CalculationService service = CreateCalculationService(specificationRepository: specificationRepository);

            // Act
            IActionResult result = await service.IsCalculationNameValid(specificationId, "calc1", null);

            // Assert
            result
            .Should()
            .BeOfType <NotFoundResult>();
        }
Beispiel #21
0
        public SpecificationForm()
        {
            InitializeComponent();

            // Defines the progressbar and submit button to allow the progressbar methods to work in the FormUserControl(base)
            progressBar  = prog;
            submitButton = btnSubmit;

            SpecModel = new Specification()
            {
                LocalizedSpecifications = new List <LocalizedSpecification>()
            };

            _specRepo = new SpecificationRepository();

            InitializeCreateForm();

            // Model binding is not always working for checkboxes, so I'm checking these in code.
            cbIsBool.IsChecked = true;

            DataContext = this;
        }
        public async Task EditCalculationStatus_GivenNewStatusOfUpdated_UpdatesSearchReturnsOK()
        {
            //Arrange
            EditStatusModel CalculationEditStatusModel = new EditStatusModel
            {
                PublishStatus = PublishStatus.Updated
            };

            string json = JsonConvert.SerializeObject(CalculationEditStatusModel);

            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>
            {
                { "calculationId", new StringValues(CalculationId) },
            });

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

            request
            .HttpContext
            .Returns(context);

            ILogger logger = CreateLogger();

            Calculation calculation = CreateCalculation();

            calculation.Current.PublishStatus = PublishStatus.Approved;

            CalculationVersion calculationVersion = calculation.Current.Clone() as CalculationVersion;

            calculationVersion.PublishStatus = PublishStatus.Updated;

            ICalculationsRepository CalculationsRepository = CreateCalculationsRepository();

            CalculationsRepository
            .GetCalculationById(Arg.Is(CalculationId))
            .Returns(calculation);

            CalculationsRepository
            .UpdateCalculation(Arg.Any <Calculation>())
            .Returns(HttpStatusCode.OK);


            ISearchRepository <CalculationIndex> searchRepository = CreateSearchRepository();

            Models.Specs.SpecificationSummary specificationSummary = new Models.Specs.SpecificationSummary();

            ISpecificationRepository specificationRepository = CreateSpecificationRepository();

            specificationRepository
            .GetSpecificationSummaryById(Arg.Is(calculation.SpecificationId))
            .Returns(specificationSummary);

            IVersionRepository <CalculationVersion> versionRepository = CreateCalculationVersionRepository();

            versionRepository
            .CreateVersion(Arg.Any <CalculationVersion>(), Arg.Any <CalculationVersion>())
            .Returns(calculationVersion);

            Build build = new Build
            {
                SourceFiles = new List <SourceFile> {
                    new SourceFile()
                }
            };

            BuildProject buildProject = new BuildProject();

            IBuildProjectsService buildProjectsService = CreateBuildProjectsService();

            buildProjectsService
            .GetBuildProjectForSpecificationId(Arg.Is(calculation.SpecificationId))
            .Returns(buildProject);

            ISourceCodeService sourceCodeService = CreateSourceCodeService();

            sourceCodeService
            .Compile(Arg.Any <BuildProject>(), Arg.Any <IEnumerable <Models.Calcs.Calculation> >(), Arg.Any <CompilerOptions>())
            .Returns(build);

            CalculationService service = CreateCalculationService(
                logger: logger, calculationsRepository: CalculationsRepository, searchRepository: searchRepository,
                specificationRepository: specificationRepository, calculationVersionRepository: versionRepository,
                sourceCodeService: sourceCodeService, buildProjectsService: buildProjectsService);

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

            //Arrange
            result
            .Should()
            .BeOfType <OkObjectResult>()
            .Which
            .Value
            .Should()
            .BeOfType <PublishStatusResultModel>()
            .Which
            .PublishStatus
            .Should()
            .Be(PublishStatus.Updated);

            calculation
            .Current
            .PublishStatus
            .Should()
            .Be(PublishStatus.Updated);

            await
            searchRepository
            .Received(1)
            .Index(Arg.Is <IEnumerable <CalculationIndex> >(m => m.First().Status == "Updated"));
        }
        public async Task EditCalculationStatus_GivenCalculationIsApprovedButNewStatusIsDraft_UpdatesSearchReturnsOK()
        {
            //Arrange
            EditStatusModel CalculationEditStatusModel = new EditStatusModel
            {
                PublishStatus = PublishStatus.Draft
            };

            string json = JsonConvert.SerializeObject(CalculationEditStatusModel);

            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>
            {
                { "calculationId", new StringValues(CalculationId) },
            });

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

            request
            .HttpContext
            .Returns(context);

            ILogger logger = CreateLogger();

            Calculation calculation = CreateCalculation();

            calculation.Current.PublishStatus = PublishStatus.Approved;

            ICalculationsRepository CalculationsRepository = CreateCalculationsRepository();

            CalculationsRepository
            .GetCalculationById(Arg.Is(CalculationId))
            .Returns(calculation);

            CalculationsRepository
            .UpdateCalculation(Arg.Any <Calculation>())
            .Returns(HttpStatusCode.OK);


            Models.Specs.SpecificationSummary specificationSummary = new Models.Specs.SpecificationSummary();

            ISpecificationRepository specificationRepository = CreateSpecificationRepository();

            specificationRepository
            .GetSpecificationSummaryById(Arg.Is(calculation.SpecificationId))
            .Returns(specificationSummary);

            ISearchRepository <CalculationIndex> searchRepository = CreateSearchRepository();

            CalculationService service = CreateCalculationService(
                logger: logger, calculationsRepository: CalculationsRepository, searchRepository: searchRepository, specificationRepository: specificationRepository);

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

            //Arrange
            result
            .Should()
            .BeOfType <BadRequestObjectResult>()
            .Which
            .Value
            .Should()
            .Be("Publish status can't be changed to Draft from Updated or Approved");

            calculation
            .Current
            .PublishStatus
            .Should()
            .Be(PublishStatus.Approved);

            await
            searchRepository
            .Received(0)
            .Index(Arg.Any <IEnumerable <CalculationIndex> >());
        }
        public async Task EditCalculationStatus_GivenNewStatusButUpdatingDbReturnsBadRequest_ReturnsStatusCode400()
        {
            //Arrange
            EditStatusModel CalculationEditStatusModel = new EditStatusModel
            {
                PublishStatus = PublishStatus.Approved
            };

            string json = JsonConvert.SerializeObject(CalculationEditStatusModel);

            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>
            {
                { "calculationId", new StringValues(CalculationId) },
            });

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

            request
            .HttpContext
            .Returns(context);

            ILogger logger = CreateLogger();

            Calculation calculation = CreateCalculation();

            ICalculationsRepository CalculationsRepository = CreateCalculationsRepository();

            CalculationsRepository
            .GetCalculationById(Arg.Is(CalculationId))
            .Returns(calculation);

            CalculationsRepository
            .UpdateCalculation(Arg.Any <Calculation>())
            .Returns(HttpStatusCode.BadRequest);

            Models.Specs.SpecificationSummary specificationSummary = new Models.Specs.SpecificationSummary();

            ISpecificationRepository specificationRepository = CreateSpecificationRepository();

            specificationRepository
            .GetSpecificationSummaryById(Arg.Is(calculation.SpecificationId))
            .Returns(specificationSummary);

            CalculationService service = CreateCalculationService(
                logger: logger, calculationsRepository: CalculationsRepository, specificationRepository: specificationRepository);

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

            //Arrange
            result
            .Should()
            .BeAssignableTo <StatusCodeResult>()
            .Which
            .StatusCode
            .Should()
            .Be(400);
        }
Beispiel #25
0
 public SpecificationBehavior(ISpecificationRepository repository)
 {
     _repository = repository;
 }
Beispiel #26
0
 public CreateSpecificationCommandHandler(ISpecificationRepository specificationRepository)
 {
     _specificationRepository = specificationRepository;
 }
 public SpecificationComponent(ISpecificationRepository specificationRepository)
 {
     _specificationRepository = specificationRepository;
 }
        public async Task ResetCalculationForFieldDefinitionChanges_GivenCalculationRequiresReset_UpdatesCalculationsAndDeletesAssembly()
        {
            //Arrange
            const string specificationId = "spec-id";

            IEnumerable <DatasetSpecificationRelationshipViewModel> relationships = new[]
            {
                new DatasetSpecificationRelationshipViewModel
                {
                    Name = "Test Name"
                }
            };

            IEnumerable <string> currentFieldDefinitionNames = new[]
            {
                "Test Field"
            };

            ILogger logger = CreateLogger();

            CalculationVersion calculationVersion = new CalculationVersion
            {
                SourceCode = "return Datasets.TestName.TestField",
                Date       = DateTimeOffset.Now
            };

            IEnumerable <Calculation> calculations = new[]
            {
                new Calculation
                {
                    Current                  = calculationVersion,
                    SpecificationId          = specificationId,
                    CalculationSpecification = new Reference("calc-spac-id", "calc spec name"),
                    FundingPeriod            = new Reference("fp1", "fp 1"),
                    FundingStream            = new Reference("fs1", "fs 1"),
                    Policies                 = new List <Reference> {
                        new Reference {
                            Id = "policy-1", Name = "policy 1"
                        }
                    }
                }
            };

            IEnumerable <Models.Specs.Calculation> calculationSpecifications = new[]
            {
                new Models.Specs.Calculation
                {
                    Id = "calc-spec-id"
                }
            };

            BuildProject buildProject = new BuildProject();

            Build build = new Build
            {
                SourceFiles = new List <SourceFile>()
            };

            Models.Specs.SpecificationSummary specificationSummary = new Models.Specs.SpecificationSummary();

            ICalculationsRepository calculationsRepository = CreateCalculationsRepository();

            calculationsRepository
            .GetCalculationsBySpecificationId(Arg.Is(specificationId))
            .Returns(calculations);
            calculationsRepository
            .UpdateCalculation(Arg.Any <Calculation>())
            .Returns(HttpStatusCode.OK);

            ISpecificationRepository specificationRepository = CreateSpecificationRepository();

            specificationRepository
            .GetCalculationSpecificationsForSpecification(Arg.Is(specificationId))
            .Returns(calculationSpecifications);

            specificationRepository
            .GetSpecificationSummaryById(Arg.Is(specificationId))
            .Returns(specificationSummary);

            IBuildProjectsService buildProjectsService = CreateBuildProjectsService();

            buildProjectsService
            .GetBuildProjectForSpecificationId(Arg.Is(specificationId))
            .Returns(buildProject);

            ISourceCodeService sourceCodeService = CreateSourceCodeService();

            sourceCodeService
            .Compile(Arg.Is(buildProject), Arg.Any <IEnumerable <Calculation> >(), Arg.Any <CompilerOptions>())
            .Returns(build);

            IVersionRepository <CalculationVersion> calculationVersionRepository = CreateCalculationVersionRepository();

            calculationVersionRepository
            .CreateVersion(Arg.Any <CalculationVersion>(), Arg.Any <CalculationVersion>())
            .Returns(calculationVersion);

            ICacheProvider cacheProvider = CreateCacheProvider();

            CalculationService calculationService = CreateCalculationService(
                logger: logger,
                calculationsRepository: calculationsRepository,
                specificationRepository: specificationRepository,
                buildProjectsService: buildProjectsService,
                sourceCodeService: sourceCodeService,
                calculationVersionRepository: calculationVersionRepository,
                cacheProvider: cacheProvider);

            //Act
            await calculationService.ResetCalculationForFieldDefinitionChanges(relationships, specificationId, currentFieldDefinitionNames);

            //Assert
            await
            sourceCodeService
            .Received(1)
            .DeleteAssembly(Arg.Is(specificationId));

            await
            cacheProvider
            .Received(1)
            .RemoveAsync <List <DatasetSchemaRelationshipModel> >(Arg.Is($"{CacheKeys.DatasetRelationshipFieldsForSpecification}{specificationId}"));
        }
        public async Task CreateCalculation_GivenValidCalculationWithNullFundingStream_AndSavesLogs()
        {
            //Arrange
            Calculation calculation = CreateCalculation();

            calculation.FundingStream = null;

            IEnumerable <Calculation> calculations = new[]
            {
                calculation
            };

            IEnumerable <Models.Specs.Calculation> calculationSpecifications = new[]
            {
                new Models.Specs.Calculation
                {
                    Id = calculation.CalculationSpecification.Id
                }
            };

            string json = JsonConvert.SerializeObject(calculation);

            Message message = new Message(Encoding.UTF8.GetBytes(json));

            message.UserProperties.Add("user-id", UserId);
            message.UserProperties.Add("user-name", Username);

            ICalculationsRepository repository = CreateCalculationsRepository();

            repository
            .CreateDraftCalculation(Arg.Any <Calculation>())
            .Returns(HttpStatusCode.Created);

            repository
            .GetCalculationsBySpecificationId(Arg.Is("any-spec-id"))
            .Returns(calculations);

            Models.Specs.SpecificationSummary specificationSummary = new Models.Specs.SpecificationSummary()
            {
                Id   = calculation.SpecificationId,
                Name = "Test Spec Name",
            };

            ISpecificationRepository specificationRepository = CreateSpecificationRepository();

            specificationRepository
            .GetSpecificationSummaryById(Arg.Is(calculation.SpecificationId))
            .Returns(specificationSummary);

            specificationRepository
            .GetCalculationSpecificationsForSpecification(Arg.Is(calculation.SpecificationId))
            .Returns(calculationSpecifications);

            ILogger logger = CreateLogger();

            ISearchRepository <CalculationIndex> searchRepository = CreateSearchRepository();

            Build build = new Build
            {
                SourceFiles = new List <SourceFile> {
                    new SourceFile()
                }
            };

            ISourceCodeService sourceCodeService = CreateSourceCodeService();

            sourceCodeService
            .Compile(Arg.Any <BuildProject>(), Arg.Any <IEnumerable <Models.Calcs.Calculation> >(), Arg.Any <CompilerOptions>())
            .Returns(build);

            CalculationService service = CreateCalculationService(
                calculationsRepository: repository,
                logger: logger, searchRepository:
                searchRepository,
                specificationRepository: specificationRepository,
                sourceCodeService: sourceCodeService);

            //Act
            await service.CreateCalculation(message);

            //Assert
            logger
            .Received(1)
            .Information($"Calculation with id: {calculation.Id} was successfully saved to Cosmos Db");

            await
            repository
            .Received(1)
            .CreateDraftCalculation(Arg.Is <Calculation>(m =>
                                                         m.Id == CalculationId &&
                                                         m.Current.PublishStatus == PublishStatus.Draft &&
                                                         m.Current.Author.Id == UserId &&
                                                         m.Current.Author.Name == Username &&
                                                         m.Current.Date.Date == DateTimeOffset.Now.Date &&
                                                         m.Current.Version == 1 &&
                                                         m.Current.DecimalPlaces == 6
                                                         ));

            await
            searchRepository
            .Received(1)
            .Index(Arg.Is <List <CalculationIndex> >(
                       m => m.First().Id == CalculationId &&
                       m.First().Name == "Test Calc Name" &&
                       m.First().CalculationSpecificationId == "any-calc-id" &&
                       m.First().CalculationSpecificationName == "Test Calc Name" &&
                       m.First().SpecificationId == "any-spec-id" &&
                       m.First().SpecificationName == "Test Spec Name" &&
                       m.First().FundingPeriodId == "18/19" &&
                       m.First().FundingPeriodName == "2018/2019" &&
                       m.First().FundingStreamId == string.Empty &&
                       m.First().FundingStreamName == "No funding stream set" &&
                       m.First().AllocationLineId == "test-alloc-id" &&
                       m.First().AllocationLineName == "test-alloc-name" &&
                       m.First().PolicySpecificationIds.First() == "policy-id" &&
                       m.First().PolicySpecificationNames.First() == "policy-name"
                       ));
        }
        public async Task CreateCalculation_GivenValidCalculation_ButFailedToSave_DoesNotUpdateSearch()
        {
            //Arrange
            Calculation calculation = CreateCalculation();

            IEnumerable <Calculation> calculations = new[]
            {
                calculation
            };

            IEnumerable <Models.Specs.Calculation> calculationSpecifications = new[]
            {
                new Models.Specs.Calculation
                {
                    Id = calculation.CalculationSpecification.Id
                }
            };

            string json = JsonConvert.SerializeObject(calculation);

            Message message = new Message(Encoding.UTF8.GetBytes(json));

            message.UserProperties.Add("user-id", UserId);
            message.UserProperties.Add("user-name", Username);

            ICalculationsRepository repository = CreateCalculationsRepository();

            repository
            .CreateDraftCalculation(Arg.Any <Calculation>())
            .Returns(HttpStatusCode.BadRequest);

            repository
            .GetCalculationsBySpecificationId(Arg.Is("any-spec-id"))
            .Returns(calculations);

            ILogger logger = CreateLogger();

            ISearchRepository <CalculationIndex> searchRepository = CreateSearchRepository();

            Models.Specs.SpecificationSummary specificationSummary = new Models.Specs.SpecificationSummary()
            {
                Id   = calculation.SpecificationId,
                Name = "Test Spec Name",
            };

            ISpecificationRepository specificationRepository = CreateSpecificationRepository();

            specificationRepository
            .GetSpecificationSummaryById(Arg.Is(calculation.SpecificationId))
            .Returns(specificationSummary);

            specificationRepository
            .GetCalculationSpecificationsForSpecification(Arg.Is(calculation.SpecificationId))
            .Returns(calculationSpecifications);

            CalculationService service = CreateCalculationService(calculationsRepository: repository, logger: logger, searchRepository: searchRepository, specificationRepository: specificationRepository);

            //Act
            await service.CreateCalculation(message);

            //Assert
            logger
            .Received(1)
            .Error($"There was problem creating a new calculation with id {calculation.Id} in Cosmos Db with status code 400");

            await
            repository
            .Received(1)
            .CreateDraftCalculation(Arg.Is <Calculation>(m =>
                                                         m.Id == CalculationId &&
                                                         m.Current.PublishStatus == PublishStatus.Draft &&
                                                         m.Current.Author.Id == UserId &&
                                                         m.Current.Author.Name == Username &&
                                                         m.Current.Date.Date == DateTimeOffset.Now.Date &&
                                                         m.Current.Version == 1 &&
                                                         m.Current.DecimalPlaces == 6
                                                         ));

            await
            searchRepository
            .DidNotReceive()
            .Index(Arg.Any <List <CalculationIndex> >());
        }