public async Task GetChildrenForOrganization(
            string[] include,
            bool includeFamily,
            bool includeDeterminations
            )
        {
            Guid[] ids;
            int    organizationId;

            using (var context = new TestHedwigContextProvider().Context)
            {
                var organization = OrganizationHelper.CreateOrganization(context);
                var children     = ChildHelper.CreateChildren(context, 3, organization: organization);
                ids            = children.Select(c => c.Id).ToArray();
                organizationId = organization.Id;
            }

            using (var context = new TestHedwigContextProvider().Context)
            {
                var childRepo = new ChildRepository(context);
                var res       = await childRepo.GetChildrenForOrganizationAsync(organizationId, include);

                Assert.Equal(ids.OrderBy(id => id), res.Select(c => c.Id).OrderBy(id => id));
                Assert.Equal(includeFamily, res.TrueForAll(c => c.Family != null));
                Assert.Equal(includeDeterminations, res.TrueForAll(c => c.Family != null && c.Family.Determinations != null));
            }
        }
        public async Task GetSiteForOrganization_ReturnsSiteWithIdAndOrganizationId_IncludesEntities(
            string[] include,
            bool includeEnrollments,
            bool includeFundings,
            bool includeChildren
            )
        {
            int orgId;
            int id;

            using (var context = new TestHedwigContextProvider().Context)
            {
                var enrollment = EnrollmentHelper.CreateEnrollment(context);

                id    = enrollment.SiteId;
                orgId = enrollment.Site.OrganizationId;
            }

            using (var context = new TestHedwigContextProvider().Context)
            {
                var siteRepo = new SiteRepository(context);
                var res      = await siteRepo.GetSiteForOrganizationAsync(id, orgId, include);

                Assert.Equal(includeEnrollments, res.Enrollments != null);
                Assert.Equal(includeFundings, res.Enrollments != null && res.Enrollments.All(e => e.Fundings != null));
                Assert.Equal(includeChildren, res.Enrollments != null && res.Enrollments.All(e => e.Child != null));
            }
        }
        public async Task GetEnrollmentForSite_ReturnsEnrollmentWithIdAndSiteId_IncludesEntities(
            string[] include,
            bool includeFundings,
            bool includeChild,
            bool includeFamily,
            bool includeDeterminations,
            bool includePastEnrollments
            )
        {
            int id;
            int siteId;

            using (var context = new TestHedwigContextProvider().Context)
            {
                var enrollment = EnrollmentHelper.CreateEnrollment(context);
                EnrollmentHelper.CreateEnrollment(context, child: enrollment.Child);
                id     = enrollment.Id;
                siteId = enrollment.SiteId;
            }

            using (var context = new TestHedwigContextProvider().Context)
            {
                var enrollmentRepo = new EnrollmentRepository(context);
                var res            = await enrollmentRepo.GetEnrollmentForSiteAsync(id, siteId, include);

                Assert.Equal(id, res.Id);
                Assert.Equal(includeFundings, res.Fundings != null);
                Assert.Equal(includeChild, res.Child != null);
                Assert.Equal(includeFamily, res.Child != null && res.Child.Family != null);
                Assert.Equal(includeDeterminations, res.Child != null && res.Child.Family != null && res.Child.Family.Determinations != null);
                Assert.Equal(includePastEnrollments, res.PastEnrollments != null);
            }
        }
        public void DeleteEnrollment_DeletesDanglingSubObjects()
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                var enrollment = new Enrollment();
                var child      = new Child();
                var funding    = new Funding();
                enrollment.Id        = 1;
                funding.Enrollment   = enrollment;
                funding.EnrollmentId = enrollment.Id;
                enrollment.Child     = child;

                var enrollmentRepo = new EnrollmentRepository(context);
                var fundingRepo    = new FundingRepository(context);
                enrollmentRepo.AddEnrollment(enrollment);

                Assert.Equal(EntityState.Added, context.Entry(enrollment).State);

                enrollmentRepo.DeleteEnrollment(enrollment);

                Assert.Equal(EntityState.Detached, context.Entry(funding).State);
                Assert.Equal(EntityState.Added, context.Entry(child).State);
                Assert.Equal(EntityState.Detached, context.Entry(enrollment).State);
            }
        }
        public async Task GetEnrollmentsForSite_ReturnsEnrollmentsWithSiteId_IncludesEntities(
            string[] include,
            bool includeFundings,
            bool includeChildren,
            bool includeFamilies,
            bool includeDeterminations
            )
        {
            int[] ids;
            int   siteId;

            using (var context = new TestHedwigContextProvider().Context)
            {
                var site        = SiteHelper.CreateSite(context);
                var enrollments = EnrollmentHelper.CreateEnrollments(context, 3, site: site);
                ids    = enrollments.Select(e => e.Id).ToArray();
                siteId = site.Id;
            }

            using (var context = new TestHedwigContextProvider().Context)
            {
                var enrollmentRepo = new EnrollmentRepository(context);
                var res            = await enrollmentRepo.GetEnrollmentsForSiteAsync(siteId, include : include);

                Assert.Equal(ids.OrderBy(id => id), res.Select(e => e.Id).OrderBy(id => id));
                Assert.Equal(includeFundings, res.TrueForAll(e => e.Fundings != null));
                Assert.Equal(includeChildren, res.TrueForAll(e => e.Child != null));
                Assert.Equal(includeFamilies, res.TrueForAll(e => e.Child != null && e.Child.Family != null));
                Assert.Equal(includeDeterminations, res.TrueForAll(e => e.Child != null && e.Child.Family != null && e.Child.Family.Determinations != null));
            }
        }
        public void Execute_DoesNotAddEnrollmentsToReport(bool reportHasEnrollmentsReference)
        {
            CdcReport report;

            using (var context = new TestHedwigContextProvider().Context)
            {
                report = ReportHelper.CreateCdcReport(context) as CdcReport;
                var site        = SiteHelper.CreateSite(context, organization: report.Organization);
                var enrollments = EnrollmentHelper.CreateEnrollments(context, 1, site: site);
                report.Enrollments = enrollments;
            }

            if (!reportHasEnrollmentsReference)
            {
                report.Enrollments = null;
            }

            using (var context = new TestHedwigContextProvider().Context)
            {
                context.Attach(report);

                var _serviceProvider = new Mock <IServiceProvider>();
                _serviceProvider.Setup(sp => sp.GetService(typeof(IEnumerable <IValidationRule <Enrollment> >)))
                .Returns(new List <IValidationRule <Enrollment> >());
                var _validator = new NonBlockingValidator(_serviceProvider.Object);
                var _reports   = new ReportRepository(context);

                // when
                var rule = new EnrollmentsAreValid(_validator, _reports);
                rule.Execute(report, new NonBlockingValidationContext());

                // then
                Assert.Equal(reportHasEnrollmentsReference, report.Enrollments != null);
            }
        }
Ejemplo n.º 7
0
        public void GetReportsForFiscalYear(
            int year,
            int month,
            int day,
            int total
            )
        {
            var          reportDate = new DateTime(year, month, day);
            Organization organization;

            using (var context = new TestHedwigContextProvider().Context)
            {
                var dates = new List <DateTime> {
                    new DateTime(2010, 1, 1),
                    new DateTime(2010, 5, 1),
                    new DateTime(2010, 7, 1),
                    new DateTime(2011, 2, 1),
                    new DateTime(2011, 7, 1),
                };
                organization = OrganizationHelper.CreateOrganization(context);
                foreach (var date in dates)
                {
                    var reportingPeriod = ReportingPeriodHelper.CreateReportingPeriod(context, period: date.ToString("yyyy-MM-dd"));
                    ReportHelper.CreateCdcReport(context, organization: organization, reportingPeriod: reportingPeriod);
                }
            }

            using (var context = new TestHedwigContextProvider().Context)
            {
                var reportRepo = new ReportRepository(context);
                var result     = reportRepo.GetReportsForOrganizationByFiscalYear(organization.Id, reportDate);

                Assert.Equal(total, result.Count());
            }
        }
        public void Execute_DoesNotAddEnrollmentToFunding(bool fundingHasEnrollmentReference)
        {
            Funding funding;

            using (var context = new TestHedwigContextProvider().Context)
            {
                funding = FundingHelper.CreateFunding(context);
            }

            if (!fundingHasEnrollmentReference)
            {
                funding.Enrollment = null;
            }

            using (var context = new TestHedwigContextProvider().Context)
            {
                // Only attach found entity to avoid attaching the entire object graph
                // (which would find & attach the enrollment navigation property)
                context.Attach(context.Find(funding.GetType(), funding.Id));

                var _serviceProvider  = new Mock <IServiceProvider>();
                var _validator        = new NonBlockingValidator(_serviceProvider.Object);
                var _fundings         = new FundingRepository(context);
                var _enrollments      = new EnrollmentRepository(context);
                var _reportingPeriods = new ReportingPeriodRepository(context);

                // when
                var rule = new FundingTimelinesAreValid(_fundings, _enrollments, _reportingPeriods);
                rule.Execute(funding, new NonBlockingValidationContext());

                // then
                Assert.Equal(fundingHasEnrollmentReference, funding.Enrollment != null);
            }
        }
        public void Execute_DoesNotAddFundingsToEnrollment(bool enrollmentHasFundingsReference)
        {
            Enrollment enrollment;

            using (var context = new TestHedwigContextProvider().Context)
            {
                enrollment = EnrollmentHelper.CreateEnrollment(context);
                FundingHelper.CreateFunding(context, enrollment: enrollment);
            }

            if (!enrollmentHasFundingsReference)
            {
                enrollment.Fundings = null;
            }

            using (var context = new TestHedwigContextProvider().Context)
            {
                // Only attach found entity to avoid attaching the entire object graph
                // (which would find & attach the fundings navigation property)
                context.Attach(context.Find(enrollment.GetType(), enrollment.Id));
                var _serviceProvider = new Mock <IServiceProvider>();
                _serviceProvider.Setup(sp => sp.GetService(typeof(IEnumerable <IValidationRule <Funding> >)))
                .Returns(new List <IValidationRule <Funding> >());
                var _validator = new NonBlockingValidator(_serviceProvider.Object);
                var _fundings  = new FundingRepository(context);

                // when
                var rule = new FundingsAreValid(_validator, _fundings);
                rule.Execute(enrollment, new NonBlockingValidationContext());

                // then
                Assert.Equal(enrollmentHasFundingsReference, enrollment.Fundings != null);
            }
        }
Ejemplo n.º 10
0
        public void DeleteEnrollment()
        {
            var mapper = new MapperConfiguration(opts =>
            {
                opts.AddProfile(new EnrollmentProfile());
                opts.AddProfile(new FundingProfile());
                opts.AddProfile(new ChildProfile());
                opts.AddProfile(new FamilyProfile());
                opts.AddProfile(new SiteProfile());
            }).CreateMapper();

            using (var context = new TestHedwigContextProvider().Context)
            {
                var enrollment = new Enrollment();

                var enrollmentRepo = new EnrollmentRepository(context, mapper);
                enrollmentRepo.AddEnrollment(enrollment);

                Assert.Equal(EntityState.Added, context.Entry(enrollment).State);

                enrollmentRepo.DeleteEnrollment(enrollment);

                Assert.Equal(EntityState.Detached, context.Entry(enrollment).State);
            }
        }
        public async Task GetEnrollmentsForSite_FiltersByDates(
            string entry,
            string exit,
            string from,
            string to,
            bool included
            )
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                // if enrollment exists with entry and exit
                var enrollment = EnrollmentHelper.CreateEnrollment(context, entry, exit);

                // when repo is queried with to and from
                var enrollmentRepo = new EnrollmentRepository(context);
                var result         = await enrollmentRepo.GetEnrollmentsForSiteAsync(
                    enrollment.SiteId,
                    DateTime.Parse(from),
                    DateTime.Parse(to)
                    );

                var resultIds = result.Select(e => e.Id);

                // then
                Assert.Equal(included, resultIds.Contains(enrollment.Id));
            }
        }
Ejemplo n.º 12
0
        public void DeleteEnrollment_DeletesDanglingSubObjects()
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                var enrollment = new Enrollment();
                var child      = new Child();
                var funding    = new Funding();
                enrollment.Id        = 1;
                funding.Enrollment   = enrollment;
                funding.EnrollmentId = enrollment.Id;
                enrollment.Child     = child;

                var mapper = new MapperConfiguration(opts =>
                {
                    opts.AddProfile(new EnrollmentProfile());
                    opts.AddProfile(new FundingProfile());
                    opts.AddProfile(new ChildProfile());
                    opts.AddProfile(new FamilyProfile());
                    opts.AddProfile(new SiteProfile());
                }).CreateMapper();
                var enrollmentRepo = new EnrollmentRepository(context, mapper);
                var fundingRepo    = new FundingRepository(context);
                enrollmentRepo.AddEnrollment(enrollment);

                Assert.Equal(EntityState.Added, context.Entry(enrollment).State);

                enrollmentRepo.DeleteEnrollment(enrollment);

                Assert.Equal(EntityState.Detached, context.Entry(funding).State);
                Assert.Equal(EntityState.Added, context.Entry(child).State);
                Assert.Equal(EntityState.Detached, context.Entry(enrollment).State);
            }
        }
Ejemplo n.º 13
0
        public async Task CreatesReportForOrganization(
            bool hasFundingSpace,
            string today,
            int numOfReportsGenerated
            )
        {
            int organizationId;
            int lastReportingPeriodId;

            using (var context = new TestHedwigContextProvider().Context)
            {
                var organization = OrganizationHelper.CreateOrganization(context);
                organizationId = organization.Id;
                if (hasFundingSpace)
                {
                    FundingSpaceHelper.CreateFundingSpace(context, organizationId);
                }

                var lastReportingPeriod = ReportingPeriodHelper.GetOrCreateReportingPeriodForPeriod(
                    context,
                    period: "2010-10-01",
                    periodStart: "2010-10-01",
                    periodEnd: "2010-10-31"
                    );
                lastReportingPeriodId = lastReportingPeriod.Id;
            }

            using (var context = new TestHedwigContextProvider().Context)
            {
                var logger              = new Mock <ILogger <CdcReportGeneratorScopedService> >();
                var orgRepo             = new OrganizationRepository(context);
                var reportingPeriodRepo = new ReportingPeriodRepository(context);
                var reportRepo          = new ReportRepository(context);
                var dateTime            = new Mock <IDateTime>();
                dateTime.Setup(dateTime => dateTime.UtcNow).Returns(DateTime.Parse(today));

                var cdcReportGenerator = new CdcReportGeneratorScopedService(
                    logger.Object,
                    orgRepo,
                    reportingPeriodRepo,
                    reportRepo,
                    dateTime.Object
                    );

                var previousReports = reportRepo.GetReportsForOrganization(organizationId);

                await cdcReportGenerator.TryGenerateReports();

                var reports = reportRepo.GetReportsForOrganization(organizationId);

                Assert.Empty(previousReports);
                Assert.Equal(numOfReportsGenerated, reports.Count());
                if (numOfReportsGenerated > 0)
                {
                    Assert.True(reports.All(report => report.ReportingPeriodId == lastReportingPeriodId));
                }
            }
        }
Ejemplo n.º 14
0
        public void UpdateEnrollment_AddsFundings()
        {
            Enrollment   enrollment;
            FundingSpace fundingSpace;

            using (var context = new TestHedwigContextProvider().Context)
            {
                enrollment   = EnrollmentHelper.CreateEnrollment(context);
                fundingSpace = FundingSpaceHelper.CreateFundingSpace(
                    context,
                    organizationId: enrollment.Site.OrganizationId,
                    source: FundingSource.CDC,
                    ageGroup: enrollment.AgeGroup.Value
                    );
            }

            Funding funding = new Funding
            {
                EnrollmentId   = enrollment.Id,
                Source         = FundingSource.CDC,
                FundingSpaceId = fundingSpace.Id
            };

            Assert.Null(enrollment.Fundings);

            enrollment.Fundings = new List <Funding> {
                funding
            };

            var mapper = new MapperConfiguration(opts =>
            {
                opts.AddProfile(new EnrollmentProfile());
                opts.AddProfile(new FundingProfile());
                opts.AddProfile(new ChildProfile());
                opts.AddProfile(new FamilyProfile());
                opts.AddProfile(new SiteProfile());
            }).CreateMapper();

            using (var context = new TestHedwigContextProvider().Context)
            {
                var enrollmentRepo = new EnrollmentRepository(context, mapper);

                var enrollmentDTO = mapper.Map <Enrollment, EnrollmentDTO>(enrollment);
                enrollmentRepo.UpdateEnrollment(enrollment, enrollmentDTO);
                context.SaveChanges();
            }

            using (var context = new TestHedwigContextProvider().Context)
            {
                var enrollmentRepo      = new EnrollmentRepository(context, mapper);
                var retrievedEnrollment = enrollmentRepo.GetEnrollmentById(enrollment.Id);
                Assert.NotEmpty(retrievedEnrollment.Fundings);

                var retrievedFunding = retrievedEnrollment.Fundings.FirstOrDefault();
                Assert.Equal(funding.Id, retrievedFunding.Id);
            }
        }
Ejemplo n.º 15
0
        public async Task Get_Report_For_Organization(bool submitted, string[] include)
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                // Set up test data
                var organization    = OrganizationHelper.CreateOrganization(context);
                var reportingPeriod = ReportingPeriodHelper.CreateReportingPeriod(context);
                var report          = ReportHelper.CreateCdcReport(context, organization: organization, reportingPeriod: reportingPeriod);
                var site            = SiteHelper.CreateSite(context, organization: organization);
                var enrollment      = EnrollmentHelper.CreateEnrollment(context, site: site, ageGroup: Age.Preschool);
                var funding         = FundingHelper.CreateFunding(context, enrollment: enrollment, firstReportingPeriod: reportingPeriod);

                if (submitted)
                {
                    Thread.Sleep(1000);

                    report.SubmittedAt = DateTime.Now;
                    context.SaveChanges();

                    Thread.Sleep(1000);
                }

                enrollment.AgeGroup = Age.SchoolAge;
                context.SaveChanges();

                // When the repository is queried
                var repo   = new ReportRepository(context);
                var result = await repo.GetReportForOrganizationAsync(report.Id, organization.Id, include) as CdcReport;

                // It returns the Report
                Assert.Equal(result.Id, report.Id);

                // It includes the Organization
                Assert.Equal(include.Contains("organizations"), result.Organization != null);

                // It includes the Sites
                Assert.Equal(include.Contains("sites"), result.Organization != null && result.Organization.Sites != null);

                // It includes the Enrollments (and Fundings too)
                Assert.Equal(
                    include.Contains("enrollments"),
                    result.Enrollments != null &&
                    result.Enrollments.FirstOrDefault().Fundings != null
                    );

                // When it includes enrollments
                if (include.Contains("enrollments"))
                {
                    var enrollmentResult = result.Enrollments.FirstOrDefault();
                    var fundingResult    = enrollmentResult.Fundings.FirstOrDefault();

                    // A submitted report should return the data as of when it was submitted
                    Assert.Equal(submitted ? Age.Preschool : Age.SchoolAge, enrollmentResult.AgeGroup);
                }
            }
        }
        public void GetFamilyById_ReturnsFamilyWithId()
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                var family = FamilyHelper.CreateFamily(context);

                var familyRepo = new FamilyRepository(context);
                var res        = familyRepo.GetFamilyById(family.Id);

                Assert.Equal(family.Id, res.Id);
            }
        }
        public void AddEnrollment()
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                var enrollment = new Enrollment();

                var enrollmentRepo = new EnrollmentRepository(context);
                enrollmentRepo.AddEnrollment(enrollment);

                Assert.Equal(EntityState.Added, context.Entry(enrollment).State);
            }
        }
Ejemplo n.º 18
0
        public void UpdateEnrollment_UpdatesFundings()
        {
            Enrollment      enrollment;
            Funding         funding;
            ReportingPeriod reportingPeriod;

            using (var context = new TestHedwigContextProvider().Context)
            {
                enrollment      = EnrollmentHelper.CreateEnrollment(context);
                funding         = FundingHelper.CreateFunding(context, enrollment: enrollment);
                reportingPeriod = ReportingPeriodHelper.CreateReportingPeriod(context);
            }

            Assert.Null(funding.FirstReportingPeriodId);

            funding.FirstReportingPeriodId = reportingPeriod.Id;
            enrollment.Fundings            = new List <Funding> {
                funding
            };

            enrollment.Fundings.FirstOrDefault().Enrollment = null;

            using (var context = new TestHedwigContextProvider().Context)
            {
                var mapper = new MapperConfiguration(opts =>
                {
                    opts.AddProfile(new EnrollmentProfile());
                    opts.AddProfile(new FundingProfile());
                    opts.AddProfile(new FundingSpaceProfile());
                    opts.AddProfile(new ChildProfile());
                    opts.AddProfile(new FamilyProfile());
                    opts.AddProfile(new SiteProfile());
                }).CreateMapper();

                var enrollmentRepo = new EnrollmentRepository(context, mapper);
                var enrollmentDTO  = mapper.Map <Enrollment, EnrollmentDTO>(enrollment);
                enrollmentRepo.UpdateEnrollment(enrollment, enrollmentDTO);
                context.SaveChanges();
            }

            using (var context = new TestHedwigContextProvider().Context)
            {
                var retrievedEnrollment = context.Enrollments
                                          .Where(e => e.Id == enrollment.Id)
                                          .Include(e => e.Fundings)
                                          .FirstOrDefault();
                var retrievedFunding = retrievedEnrollment.Fundings.FirstOrDefault();

                Assert.NotNull(retrievedFunding.FirstReportingPeriodId);
                Assert.Equal(funding.FirstReportingPeriodId, retrievedFunding.FirstReportingPeriodId);
            }
        }
Ejemplo n.º 19
0
        public async Task UpdatedTemporalEntity_IsUpdated_OnSaveChangesAsync()
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                var family    = FamilyHelper.CreateFamily(context);
                var updatedAt = family.UpdatedAt;
                context.Update(family);
                await context.SaveChangesAsync();

                Assert.NotNull(family.AuthorId);
                Assert.NotNull(family.UpdatedAt);
                Assert.NotEqual(updatedAt, family.UpdatedAt);
            }
        }
Ejemplo n.º 20
0
        public async Task ReportControllerOrganizationsReportsGet_ReturnsCorrectResponseShape()
        {
            User         user;
            Organization organization;

            Site[] sites;
            Report report;

            using (var context = new TestHedwigContextProvider().Context)
            {
                organization = OrganizationHelper.CreateOrganization(context);
                var site1 = SiteHelper.CreateSite(context, organization: organization);
                var site2 = SiteHelper.CreateSite(context, organization: organization);
                report = ReportHelper.CreateCdcReport(context, organization: organization);
                sites  = new Site[] { site1, site2 };
                EnrollmentHelper.CreateEnrollment(context, site: site1);
                user = UserHelper.CreateUser(context);
                PermissionHelper.CreateSitePermission(context, user, site1);
                PermissionHelper.CreateSitePermission(context, user, site2);
                PermissionHelper.CreateOrganizationPermission(context, user, organization);
            }

            var client = _factory.CreateClient();

            var request = HedwigAPIRequests.OrganizationReports(
                user,
                organization
                );

            var response = await client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            var responseString = await response.Content.ReadAsStringAsync();

            var responseReports = JsonConvert.DeserializeObject <List <CdcReport> >(responseString);

            Assert.NotEmpty(responseReports);

            var responseReport = responseReports.First();

            Assert.NotNull(responseReport);
            Assert.Equal(report.Id, responseReport.Id);
            Assert.NotNull(responseReport.Organization);
            Assert.Null(responseReport.Organization.FundingSpaces);
            Assert.Null(responseReport.Organization.Sites);
            Assert.NotNull(responseReport.ReportingPeriod);
            Assert.Null(responseReport.Enrollments);
        }
Ejemplo n.º 21
0
        public async Task AddedTemporalEntity_IsUpdated_OnSaveChangesAsync()
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                var family = new Family
                {
                    OrganizationId = context.Organizations.First().Id
                };
                context.Add(family);
                await context.SaveChangesAsync();

                Assert.NotNull(family.AuthorId);
                Assert.NotNull(family.UpdatedAt);
            }
        }
Ejemplo n.º 22
0
        public void GetReportsForOrganization()
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                var organization = OrganizationHelper.CreateOrganization(context);
                var reports      = ReportHelper.CreateCdcReports(context, 5, organization: organization);
                var reportIds    = reports.Select(report => report.Id);
                ReportHelper.CreateCdcReport(context);

                var reportRepo = new ReportRepository(context);
                var result     = reportRepo.GetReportsForOrganization(organization.Id);
                var resultIds  = result.Select(r => r.Id);
                Assert.Equal(reportIds, resultIds);
            }
        }
Ejemplo n.º 23
0
        public void Get_User_By_Id()
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                // If a user exists
                var user = UserHelper.CreateUser(context);

                // When the repository is queried by Id
                var userRepo = new UserRepository(context);
                var res      = userRepo.GetUserById(user.Id);

                // Then the user with that Id is returned
                Assert.Equal(user.Id, res.Id);
            }
        }
        public void OrganizationController_ReturnsCorrectResult_WhenUserHasVariousSiteAccess(
            bool hasAccessToSite2,
            bool authSucceeds
            )
        {
            using (var dbContext = new TestHedwigContextProvider().Context)
            {
                // If user exists with access to site
                var user  = UserHelper.CreateUser(dbContext);
                var site1 = SiteHelper.CreateSite(dbContext, name: "Test 1");
                var site2 = SiteHelper.CreateSite(dbContext, name: "Test 2");
                PermissionHelper.CreateSitePermission(dbContext, user, site1);
                if (hasAccessToSite2)
                {
                    PermissionHelper.CreateSitePermission(dbContext, user, site2);
                }

                // When requirement is evaluated with:
                // - claim for that user
                var claim     = new Claim("sub", $"{user.WingedKeysId}");
                var userClaim = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { claim }));

                // - httpContext for request to 'Sites' controller for that site
                var httpContext         = new Mock <HttpContext>();
                var httpContextAccessor = new HttpContextAccessor
                {
                    HttpContext = httpContext.Object
                };

                var siteIds = new StringValues(new string[] { site1.Id.ToString(), site2.Id.ToString() });
                httpContext.Setup(hc => hc.Request.Query.TryGetValue(It.IsAny <string>(), out siteIds)).Returns(true);
                // - permission repository
                var permissions = new PermissionRepository(dbContext);

                var reqHandler = new MultipleSiteAccessHandler(httpContextAccessor, permissions);
                var req        = new SiteAccessRequirement();

                var authContext = new AuthorizationHandlerContext(new List <IAuthorizationRequirement> {
                    req
                }, userClaim, new object());

                // When requirement handler handles authorization context
                reqHandler.HandleAsync(authContext);

                // Then authorization context will have succeeded
                Assert.Equal(authSucceeds, authContext.HasSucceeded);
            }
        }
        public void GetChildById_ReturnsChild()
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                // If a child exists
                string name  = "First";
                var    child = ChildHelper.CreateChild(context, name);

                // When the repository is queried for the child:
                var childRepo = new ChildRepository(context);
                var res       = childRepo.GetChildById(child.Id);

                // Then
                Assert.Equal(name, res.FirstName);
            }
        }
Ejemplo n.º 26
0
        public void GetDeterminationByFamilyId_ReturnsDeterminationsWithFamilyId()
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                // If a family determination exist with family Id
                var family        = FamilyHelper.CreateFamily(context);
                var determination = FamilyDeterminationHelper.CreateDetermination(context, family: family);

                // When the repository is queried with a family Id
                var determinationRepo = new FamilyDeterminationRepository(context);
                var res = determinationRepo.GetDeterminationsByFamilyId(family.Id);

                // Then a list including only that determination is returned
                Assert.Single(res);
                Assert.Equal(determination.Id, res.First().Id);
            }
        }
Ejemplo n.º 27
0
        public void UserCanAccessSite_No_Permission()
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                // If user exists without any permissions
                var user = UserHelper.CreateUser(context);
                var site = SiteHelper.CreateSite(context);
                PermissionHelper.CreateSitePermission(context, user, site);

                // When repository is queried for user access to some other site
                var permissionRepo = new PermissionRepository(context);
                var res            = permissionRepo.UserCanAccessSite(user.WingedKeysId, 0);

                // Then result is false
                Assert.False(res);
            }
        }
Ejemplo n.º 28
0
        public async Task DoesNotCreateDuplicateReports()
        {
            int organizationId;

            using (var context = new TestHedwigContextProvider().Context)
            {
                var organization = OrganizationHelper.CreateOrganization(context);
                organizationId = organization.Id;
                var fundingSpace = FundingSpaceHelper.CreateFundingSpace(context, organizationId);
                organization.FundingSpaces = new List <FundingSpace> {
                    fundingSpace
                };
                var currentReportingPeriod = ReportingPeriodHelper.CreateReportingPeriod(context);
            }

            using (var context = new TestHedwigContextProvider().Context)
            {
                var logger              = new Mock <ILogger <CdcReportGeneratorScopedService> >();
                var orgRepo             = new OrganizationRepository(context);
                var reportingPeriodRepo = new ReportingPeriodRepository(context);
                var reportRepo          = new ReportRepository(context);
                var dateTime            = new Mock <IDateTime>();
                dateTime.Setup(dateTime => dateTime.UtcNow).Returns(DateTime.Parse("2019-10-01"));

                var cdcReportGenerator = new CdcReportGeneratorScopedService(
                    logger.Object,
                    orgRepo,
                    reportingPeriodRepo,
                    reportRepo,
                    dateTime.Object
                    );

                var previousReports = reportRepo.GetReportsForOrganization(organizationId);

                await cdcReportGenerator.TryGenerateReports();

                await cdcReportGenerator.TryGenerateReports();

                await cdcReportGenerator.TryGenerateReports();

                var reports = reportRepo.GetReportsForOrganization(organizationId);

                Assert.Empty(previousReports);
                Assert.Single(reports);
            }
        }
Ejemplo n.º 29
0
        public void UserCanAccessSite_OrganizationPermission()
        {
            using (var context = new TestHedwigContextProvider().Context)
            {
                // If user exists with organization permission that includes site
                var user         = UserHelper.CreateUser(context);
                var site         = SiteHelper.CreateSite(context);
                var organization = OrganizationHelper.CreateOrganization(context, sites: new Site[] { site });
                PermissionHelper.CreateOrganizationPermission(context, user, organization);

                // When repository is queried for user access to site
                var permissionRepo = new PermissionRepository(context);
                var res            = permissionRepo.UserCanAccessSite(user.WingedKeysId, site.Id);

                // Then result is true
                Assert.True(res);
            }
        }
        public void Other_Controller_User_Has_Organization_Access_Evaluate_Returns_True()
        {
            using (var dbContext = new TestHedwigContextProvider().Context)
            {
                // If user exists with access to organization
                var user         = UserHelper.CreateUser(dbContext);
                var organization = OrganizationHelper.CreateOrganization(dbContext);
                PermissionHelper.CreateOrganizationPermission(dbContext, user, organization);

                // When requirement is evaluated with:
                // - claim for that user
                var claim     = new Claim("sub", $"{user.WingedKeysId}");
                var userClaim = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { claim }));

                // - httpContext for request to other controller nested under that organization
                var httpContext         = new Mock <HttpContext>();
                var httpContextAccessor = new HttpContextAccessor
                {
                    HttpContext = httpContext.Object
                };
                var routeValues = new RouteValueDictionary(new Dictionary <string, string> {
                    { "controller", "Other" },
                    { "orgId", $"{organization.Id}" }
                });
                httpContext.Setup(hc => hc.Features.Get <IRoutingFeature>()).Returns(new Mock <IRoutingFeature>().Object);
                httpContext.Setup(hc => hc.Request.RouteValues).Returns(routeValues);

                // - permission repository
                var permissions = new PermissionRepository(dbContext);

                var reqHandler = new OrganizationAccessHandler(httpContextAccessor, permissions);
                var req        = new OrganizationAccessRequirement();

                var authContext = new AuthorizationHandlerContext(new List <IAuthorizationRequirement> {
                    req
                }, userClaim, new object());

                // When requirement handler handles authorization context
                reqHandler.HandleAsync(authContext);

                // Then authorization context will have succeeded
                Assert.True(authContext.HasSucceeded);
            }
        }