public void GeneratePDFTest()
        {
            string templateId     = "tpl_000000000000000001";
            var    submissionData = new SubmissionData(
                test: false,
                data: new {
                title       = "Test PDF",
                description = "This PDF is great!"
            },
                fieldOverrides: new {
                title = new {
                    required = false
                }
            }
                );

            var response = instance.GeneratePDF(templateId, submissionData);

            Assert.IsInstanceOf <CreateSubmissionResponse> (response, "response is CreateSubmissionResponse");
            Assert.AreEqual(
                CreateSubmissionResponse.StatusEnum.Success,
                response.Status);
            var submission = response.Submission;

            StringAssert.StartsWith("sub_", submission.Id);
            Assert.AreEqual(false, submission.Expired);
            Assert.AreEqual(
                Submission.StateEnum.Pending,
                submission.State);
        }
Exemplo n.º 2
0
        public AbstractSyntaxTreeNode CreateFromFile(SubmissionData data, string path)
        {
            using (var handler =
                       new DirectoryHandler(GetCompilationDirectory(data)))
            {
                var process  = GetEngineProcess(GetEngineProcessData(handler.Directory, path));
                var exitCode = process.Run();
                if (exitCode == 0)
                {
                    process.Stop();
                    using (var reader = new StreamReader(GetOutputFile(handler.Directory)))
                    {
                        return(Extractor.Extract(reader));
                    }
                }
                EngineReportExceptionData exception;

                using (var reader = process.StandardError)
                {
                    exception = new EngineReportExceptionData(reader.ReadToEnd())
                    {
                        Type = "Compilation",
                    };
                }
                process.Stop();
                throw exception;
            }
        }
Exemplo n.º 3
0
        public void Init()
        {
            Root = Path.Combine(Directory.GetCurrentDirectory(), nameof(SnapshotReportGeneratorTests));
            AbstractSyntaxTreeGenerator = new MockAbstractSyntaxTreeGenerator {
                Throw = false
            };
            Reports   = new MockRepository <SnapshotReport, int>();
            Generator = new SnapshotReportGenerator(
                AbstractSyntaxTreeGenerator,
                new MockAbstractSyntaxTreeClassExtractor(), Reports,
                new MockSnapshotMethodGenerator(),
                new MockUnitTestGenerator()
                );
            Data = new SubmissionData(new StudentSubmissionDto()
            {
                ClassName      = "ClassName",
                StudentName    = "StudentName",
                SnapshotFolder = MockSnapshots.GetCalculatorSnapshots(),
            }, Root);

            Assignment = new Assignment()
            {
                Filename = MockSnapshots.GetCalculatorFile(),
                Solution = new AssignmentSolution()
                {
                    Name = MockSnapshots.GetCalculatorClassName(),
                },
            };
        }
 public void Dispose_CheckRootFolderIsCreated()
 {
     using (var data = new SubmissionData(Submission, Root))
     {
         Assert.IsTrue(Directory.Exists(Root));
     }
 }
        protected virtual async Task <bool> BindDataAsync(SubmissionData model, Dictionary <string, StringValues> dataToBind)
        {
            var formValueProvider = new FormValueProvider(BindingSource.Form, new FormCollection(dataToBind), CultureInfo.CurrentCulture);
            var bindingSuccessful = await TryUpdateModelAsync(model, "", formValueProvider);

            return(bindingSuccessful);
        }
 public void Dispose_CheckRootFolderIsRemove()
 {
     using (var data = new SubmissionData(Submission, Root))
     {
     }
     Assert.IsFalse(Directory.Exists(Root));
 }
Exemplo n.º 7
0
        public async Task <IList <Snapshot> > Generate(SubmissionData data, DevAssignment assignment)
        {
            var newSnapshots = new List <Snapshot>();
            var generateObj  = new SnapshotGeneratorObj(data, assignment, this);

            var solutionNode = GetSolutionAbstractSyntaxTreeNode(data, assignment);

            foreach (var snapshotName in generateObj.SnapshotNames())
            {
                if (generateObj.IsNewSnapshot(snapshotName))
                {
                    var snapshotSubmission = await generateObj.AddSubmissionToStudentSubmission(snapshotName);

                    var snapshot = new Snapshot()
                    {
                        StudentId          = generateObj.Data.Student.Id,
                        AssignmentId       = generateObj.Assignment.Id,
                        SnapshotSubmission = snapshotSubmission,
                        Report             = await ReportGenerator.Generate(generateObj.Data, snapshotName, assignment, solutionNode),
                    };
                    await Snapshots.Add(snapshot);

                    newSnapshots.Add(snapshot);
                    generateObj.LastSnapshot = snapshot;
                }
            }
            return(newSnapshots);
        }
Exemplo n.º 8
0
 public SnapshotGeneratorObj(SubmissionData data, DevAssignment assignment, SnapshotGenerator parent)
 {
     Data         = data;
     Assignment   = assignment;
     Parent       = parent;
     LastSnapshot = GetLastSnapshotOrDefault(data, assignment);
 }
 public void HasSourceFile_ShouldThrowExceptionForBadSnapshotName()
 {
     using (var data = new SubmissionData(Submission, Root))
     {
         data.HasSourceFile("Random", MockSnapshots.GetCalculatorFile());
     }
 }
Exemplo n.º 10
0
        public async Task <ICollection <UnitTestResult> > GenerateResultsImpl(SubmissionData data, string snapshot, DevAssignment assignment,
                                                                              ICollection <SnapshotMethod> snapshotMethods)
        {
            using (var handler =
                       new DirectoryHandler(GetTestDirectory(data)))
            {
                var testProject = new TestProjectObj(handler.Directory, assignment.TestProject);
                testProject.MoveFilesToProject(data.SnapshotSourceFiles(snapshot));

                var preprocessorArguments = GetPreprocessorArguments(snapshotMethods);

                var process = new EngineProcess(GetEngineProcessData(handler.Directory,
                                                                     testProject, preprocessorArguments));

                var exitCode = process.Run();
                if (exitCode == 0)
                {
                    process.Stop();
                    return(GetUnitTestResults(assignment.TestProject,
                                              ResultsFile(handler.Directory)));
                }

                EngineReportExceptionData exception;

                using (var reader = process.StandardError)
                {
                    exception = new EngineReportExceptionData(reader.ReadToEnd())
                    {
                        Type = "Build",
                    };
                }
                process.Stop();
                throw exception;
            }
        }
Exemplo n.º 11
0
        public void Init()
        {
            Root = Path.Combine(MockSnapshots.GetShortRoot(), "Powershell");
            Data = new SubmissionData(new StudentSubmissionDto()
            {
                StudentName    = "StudentName",
                ClassName      = "ClassName",
                SnapshotFolder = MockSnapshots.GetCalculatorSnapshots(),
            }, Root);

            Assignment = new Assignment()
            {
                TestProject = new TestProject()
                {
                    Id              = 1,
                    Files           = MockSnapshots.GetCalculatorTestProjectFiles(),
                    TestFolder      = MockSnapshots.GetCalculatorTestProjectFolder(),
                    TestDllFile     = MockSnapshots.GetCalculatorTestProjectDll(),
                    TestProjectFile = MockSnapshots.GetCalculatorTestProjectFile(),
                    UnitTests       = MockSnapshots.GetCalculatorUnitTests(),
                },
                TestProjectId = 1,
            };
            Generator = new PowershellUnitTestGenerator(
                Microsoft.Extensions.Options.Options.Create(
                    new PowershellOptions()
            {
                CommandPath = MockSnapshots.PowershellScript(),
                PassedValue = MockSnapshots.PowershellPassedValue(),
                ResultsFile = "test_results.txt",
            }));
        }
        public void Arrange()
        {
            _fixture = new Fixture();

            var collectionPeriods = new List <CollectionCalendarPeriod>()
            {
                new CollectionCalendarPeriod(new CollectionPeriod(1, _fixture.Create <short>()), _fixture.Create <byte>(), _fixture.Create <short>(), _fixture.Create <DateTime>(), _fixture.Create <DateTime>(), true, false),
            };
            var collectionCalendar = new CollectionCalendar(collectionPeriods);

            _mockCollectionCalendarService = new Mock <ICollectionCalendarService>();
            _mockCollectionCalendarService.Setup(m => m.Get()).ReturnsAsync(collectionCalendar);

            _sutModel = _fixture.Build <ApprenticeshipIncentiveModel>().With(x => x.Status, IncentiveStatus.Active).Create();
            _sutModel.PendingPaymentModels = new List <PendingPaymentModel>();
            _sutModel.PendingPaymentModels.Add(_fixture.Build <PendingPaymentModel>().With(x => x.DueDate, new DateTime(2021, 1, 1)).With(x => x.ClawedBack, false).With(x => x.PaymentMadeDate, (DateTime?)null).Create());
            _sutModel.PendingPaymentModels.Add(_fixture.Build <PendingPaymentModel>().With(x => x.DueDate, new DateTime(2021, 2, 28)).With(x => x.ClawedBack, false).With(x => x.PaymentMadeDate, (DateTime?)null).Create());
            _sutModel.PaymentModels         = new List <PaymentModel>();
            _sutModel.ClawbackPaymentModels = new List <ClawbackPaymentModel>();
            _sut = Sut(_sutModel);

            var learningData = new LearningData(true);

            learningData.SetIsStopped(new LearningStoppedStatus(true, _sutModel.PendingPaymentModels.Last().DueDate.AddDays(-1)));
            var submissionData = new SubmissionData();

            submissionData.SetSubmissionDate(DateTime.Now);
            submissionData.SetLearningData(learningData);
            _learner = Learner.New(_fixture.Create <Guid>(), _sutModel.Id, _fixture.Create <long>(), _fixture.Create <long>(), _fixture.Create <long>());
            _learner.SetSubmissionData(submissionData);
        }
        public AbstractSyntaxTreeNode GetStudentSnapshot(SubmissionData data, string snapshot, Assignment assignment)
        {
            var root      = AbstractSyntaxTreeGenerator.CreateFromFile(data, data.SnapshotSourceFileFullPath(snapshot, assignment.Filename));
            var classNode = ClassExtractor.Extract(root, assignment.Solution.Name);

            return(classNode);
        }
        public async Task <SnapshotReport> GenerateImpl(SubmissionData data, string snapshot, Assignment assignment,
                                                        AbstractSyntaxTreeNode solutionNode)
        {
            var studentNode = GetStudentSnapshot(data, snapshot, assignment);

            var snapshotMethods = assignment
                                  .Solution
                                  .MethodDeclarations
                                  .Select(methodDeclaration =>
                                          MethodGenerator.Generate(studentNode, solutionNode, methodDeclaration))
                                  .ToList();

            var unitTests = await UnitTestGenerator.GenerateResults(data, snapshot,
                                                                    assignment, snapshotMethods);

            var report = new SnapshotSuccessReport()
            {
                SnapshotMethods = snapshotMethods,
                UnitTestResults = unitTests,
            };

            await SnapshotReports.Add(report);

            return(report);
        }
Exemplo n.º 15
0
        public void Arrange()
        {
            _fixture = new Fixture();

            _collectionYear = _fixture.Create <short>();

            _collectionPeriod = new CollectionPeriod(1, _collectionYear);

            _fixture.Build <PendingPaymentModel>().With(p => p.PendingPaymentValidationResultModels, new List <PendingPaymentValidationResultModel>()).Create();

            _sutModel = _fixture
                        .Build <ApprenticeshipIncentiveModel>()
                        .With(a => a.PendingPaymentModels, new List <PendingPaymentModel>()
            {
                _fixture.Build <PendingPaymentModel>().With(p => p.PendingPaymentValidationResultModels, new List <PendingPaymentValidationResultModel>()).Create()
            })
                        .Create();

            _sutModel.Apprenticeship.SetProvider(_fixture.Create <Provider>());

            _learner = Learner.New(
                Guid.NewGuid(),
                _sutModel.Id,
                _sutModel.Apprenticeship.Id,
                _sutModel.Apprenticeship.Provider.Ukprn,
                _sutModel.Apprenticeship.UniqueLearnerNumber);

            var submisssionData = new SubmissionData();

            submisssionData.SetSubmissionDate(DateTime.Now);
            _learner.SetSubmissionData(submisssionData);

            _sut = Sut(_sutModel);
        }
Exemplo n.º 16
0
        public async Task <EmailData> RunSubmission(SubmissionData data)
        {
            data.Student = await GetStudent(data);

            data.Course = await GetCourseClass(data.Student, data);

            return(await GetEmailData(data));
        }
 public void HasSourceFile_ShouldFailForNonFileName()
 {
     using (var data = new SubmissionData(Submission, Root))
     {
         var first = data.SnapshotFolderNames().First();
         Assert.IsFalse(data.HasSourceFile(first, "Random.hpp"));
     }
 }
Exemplo n.º 18
0
        private async Task SetDcJobSucceeded(SubmissionData submission, string dcJobSucceeded)
        {
            var isValid = bool.TryParse(dcJobSucceeded, out var dcJobSucceededVal);

            submission.JobModel.DcJobSucceeded = (isValid == false ? (bool?)null : dcJobSucceededVal);
            submissionDataContext.Jobs.Update(submission.JobModel);
            await submissionDataContext.SaveChangesAsync();
        }
 public void SnapshotFolderNames_CheckThatSnapshotExists()
 {
     using (var data = new SubmissionData(Submission, Root))
     {
         var folder = data.SnapshotFolderNames();
         Assert.IsTrue(folder.Any());
     }
 }
Exemplo n.º 20
0
        public async Task Handle(RefreshLearnerCommand command, CancellationToken cancellationToken = default)
        {
            var incentive = await _incentiveDomainRepository.Find(command.ApprenticeshipIncentiveId);

            var learner = await _learnerDomainRepository.GetOrCreate(incentive);

            _logger.LogInformation("Start Learner data refresh from Learner match service for ApprenticeshipIncentiveId: {ApprenticeshipIncentiveId}, ApprenticeshipId: {ApprenticeshipId}, UKPRN: {UKPRN}, ULN: {ULN}",
                                   learner.ApprenticeshipIncentiveId, learner.ApprenticeshipId, learner.Ukprn, learner.UniqueLearnerNumber);

            SubmissionData submissionData = new SubmissionData();
            var            learnerData    = await _learnerService.Get(learner);

            _logger.LogInformation("End Learner data refresh from Learner match service for ApprenticeshipIncentiveId: {ApprenticeshipIncentiveId}, ApprenticeshipId: {ApprenticeshipId}, UKPRN: {UKPRN}, ULN: {ULN}",
                                   learner.ApprenticeshipIncentiveId, learner.ApprenticeshipId, learner.Ukprn, learner.UniqueLearnerNumber);

            if (learnerData != null)
            {
                if (LearnerAndEarningsHaveNotChanged(learnerData, learner, incentive))
                {
                    return;
                }

                submissionData.SetSubmissionDate(learnerData.IlrSubmissionDate);

                var learningFoundStatus = learnerData.LearningFound(incentive);
                submissionData.SetLearningData(new LearningData(learningFoundStatus.LearningFound, learningFoundStatus.NotFoundReason));

                if (learningFoundStatus.LearningFound)
                {
                    submissionData.LearningData.SetStartDate(learnerData.LearningStartDate(incentive));
                    submissionData.LearningData.SetHasDataLock(learnerData.HasProviderDataLocks(incentive));
                    submissionData.LearningData.SetIsInLearning(learnerData.IsInLearning(incentive));
                    submissionData.LearningData.SetIsStopped(learnerData.IsStopped(incentive));
                }
                submissionData.SetRawJson(learnerData.RawJson);
            }

            if (submissionData.HasChangeOfCircumstances(learner.SubmissionData))
            {
                incentive.SetHasPossibleChangeOfCircumstances(true);
            }

            learner.SetSubmissionData(submissionData);
            incentive.LearnerRefreshCompleted();

            learner.SetLearningPeriods(learnerData.LearningPeriods(incentive));

            if (!learner.SubmissionData.LearningData.LearningFound)
            {
                _logger.LogInformation("Matching ILR record not found for ApprenticeshipIncentiveId: {ApprenticeshipIncentiveId}, ApprenticeshipId: {ApprenticeshipId}, UKPRN: {UKPRN}, ULN: {ULN} with reason: {NotFoundReason}",
                                       learner.ApprenticeshipIncentiveId, learner.ApprenticeshipId, learner.Ukprn, learner.UniqueLearnerNumber, learner.SubmissionData.LearningData.NotFoundReason);
            }

            await _learnerDomainRepository.Save(learner);

            await _incentiveDomainRepository.Save(incentive);
        }
 public async Task GetStudent_ShouldThrowForStudentNotInRepository()
 {
     Submission.StudentName = "Random Student";
     Submission.ClassName   = ClassName;
     using (var data = new SubmissionData(Submission, Root))
     {
         await Runner.GetStudent(data);
     }
 }
        public void GeneratePDFWithDataRequestsTest()
        {
            string templateId     = "tpl_000000000000000001";
            var    submissionData = new SubmissionData(
                test: false,
                data: new {
                title = "Test PDF",
            },
                dataRequests: new List <CreateSubmissionDataRequestData> {
                new CreateSubmissionDataRequestData(
                    name: "John Smith",
                    email: "*****@*****.**",
                    fields: new List <string> {
                    "description"
                },
                    order: 1,
                    authType: CreateSubmissionDataRequestData.AuthTypeEnum.Emaillink
                    )
            }
                );

            var response = instance.GeneratePDF(templateId, submissionData);

            Assert.IsInstanceOf <CreateSubmissionResponse> (response, "response is CreateSubmissionResponse");
            Assert.AreEqual(
                CreateSubmissionResponse.StatusEnum.Success,
                response.Status);
            var submission = response.Submission;

            StringAssert.StartsWith("sub_", submission.Id);
            Assert.AreEqual(submission.Expired, false);
            Assert.AreEqual(
                submission.State,
                Submission.StateEnum.Waitingfordatarequests);

            var dataRequests = submission.DataRequests;

            Assert.That(dataRequests, Has.Count.EqualTo(1));

            var dataRequest = dataRequests.First();

            Assert.IsInstanceOf <SubmissionDataRequest> (dataRequest, "dataRequest is SubmissionDataRequest");

            StringAssert.StartsWith("drq_", dataRequest.Id);
            Assert.AreEqual(
                dataRequest.State,
                SubmissionDataRequest.StateEnum.Pending);
            CollectionAssert.AreEqual(
                new List <string> {
                "description"
            },
                dataRequest.Fields);
            Assert.AreEqual(1, dataRequest.Order);
            Assert.AreEqual("John Smith", dataRequest.Name);
            Assert.AreEqual("*****@*****.**", dataRequest.Email);
        }
Exemplo n.º 23
0
        private async Task RunImplementation(StudentSubmissionDto submission)
        {
            using (var data = new SubmissionData(submission,
                                                 Path.Combine(Options.RootDirectory, GetUniqueFolderName(Options.RootDirectory))))
            {
                var email = await Runner.RunSubmission(data);

                await EmailService.Send(email);
            }
        }
Exemplo n.º 24
0
 public EmailData GetNoAssignmentsEmail(SubmissionData data)
 {
     return(new EmailData(data.Student)
     {
         Subject = $"{data.Course.Name} has no assignments",
         Content = $"On {DateTime.Today.ToShortDateString()},\n" +
                   $"you submitted a snapshot package, however" +
                   $"the class \'{data.Course.Name}\' has no assignments currently.\n"
     });
 }
 public void SetSubmissionData(SubmissionData submissionData)
 {
     if (submissionData == null)
     {
         Model.SubmissionData = new SubmissionData();
     }
     else
     {
         Model.SubmissionData = submissionData;
     }
 }
 public void HasSourceFile_ShouldPassForEachSnapshot()
 {
     using (var data = new SubmissionData(Submission, Root))
     {
         foreach (var folder in data.SnapshotFolderNames())
         {
             Assert.IsTrue(data.HasSourceFile(folder,
                                              MockSnapshots.GetCalculatorFile()));
         }
     }
 }
            protected override Task <bool> BindDataAsync(SubmissionData model, Dictionary <string, StringValues> dataToBind)
            {
                foreach (var item in dataToBind)
                {
                    var propertyInfo = typeof(SubmissionData).GetProperty(item.Key);
                    var value        = Convert.ChangeType(item.Value.ToString(), propertyInfo.PropertyType);
                    propertyInfo.SetValue(model, value);
                }

                return(Task.FromResult(true));
            }
Exemplo n.º 28
0
 public EmailData NoSnapshotsToReport(SubmissionData data)
 {
     return(new EmailData(data.Student)
     {
         Subject = "No Survey Report",
         Content = $"No snapshots to report. " +
                   $"Either the files haven't changed or the snapshots doesn't contain the required assignments.\n" +
                   $"Below is a list of assignment's files that we're looking for:\n" +
                   $"{data.Course.Assignments.Select(s => $"- {s.Name}, {s.Filename}").Join("\n")}\n"
     });
 }
Exemplo n.º 29
0
        public async Task <EmailData> GetEmailData(SubmissionData data)
        {
            switch (data.Course.Assignments.Count)
            {
            case 0:
                return(GetNoAssignmentsEmail(data));

            default:
                return(await GenerateAssignments(data));
            }
        }
Exemplo n.º 30
0
        public async Task <Student> GetStudent(SubmissionData data)
        {
            var student = await StudentRepository.SingleOrDefault(s => s.Name.Equals(data.StudentName));

            if (student == null)
            {
                throw new EngineExceptionData($"Student '{data.StudentName}' does not exists in the database", data);
            }

            return(student);
        }