public void New_name_returns_shorter_name_for_folder_on_second_level()
        {
            // Arrange
            var validator = new PackageValidator();
            // 300 Zeichen
            var longEntry =
                "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lore";
            var packageItems = new List <TempValidationObject>
            {
                new TempValidationObject
                {
                    // Fullname sind 331
                    Path          = $@"Test1\{longEntry}\Test2\Test3",
                    Name          = "My Directory",
                    FullName      = $@"Test1\{longEntry}\Test2\Test3\My Directory",
                    HierachyLevel = 5, // gives an average lenth of 40 allowed chars per level
                    IdPath        = @"id1\id2\id3\id4",
                    RepositoryId  = "id5",
                    Type          = TempValidationObjectType.Folder
                }
            };

            // Act
            var result = validator.GetNewShorterNameForLongestElement(packageItems);

            // Assert
            result.Key.Should().Be("id2");
            // zweiter Eintrag um 131 Zeichen gekürzt
            result.Value.Should().Be(longEntry.Substring(0, longEntry.Length - 131));
        }
        public void New_name_returns_shorter_name_for_file()
        {
            // Arrange
            var validator = new PackageValidator();
            // file name with 200 chars + 4 chars for extension
            var longEntry =
                "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores.pdf";
            var packageItems = new List <TempValidationObject>
            {
                new TempValidationObject
                {
                    // Fullname sind 208
                    Path          = @"Test",
                    Name          = longEntry,
                    FullName      = $@"Test\{longEntry}",
                    HierachyLevel = 2,
                    IdPath        = @"id1",
                    RepositoryId  = "id2",
                    Type          = TempValidationObjectType.File
                }
            };

            // Act
            var result = validator.GetNewShorterNameForLongestElement(packageItems);

            // Assert
            result.Key.Should().Be("id2");
            // Ester Eintrag um 8 + 4 Zeichen gekürzt
            result.Value.Should().Be(longEntry.Substring(0, longEntry.Length - (8 + 4)) + ".pdf");
            // aber extension immer noch vorhanden
            result.Value.Should().EndWith(".pdf");
        }
        public void New_name_returns_shorter_name_for_folder_with_more_than_average_overflow()
        {
            // Arrange
            var validator = new PackageValidator();
            // 40 Zeichen
            var longEntry =
                "Lorem ipsum dolor sit amet, consetetur s";
            var packageItems = new List <TempValidationObject>
            {
                new TempValidationObject
                {
                    // Fullname sind 331
                    Path          = $@"{longEntry}1\{longEntry}2\{longEntry}3\{longEntry}4",
                    Name          = $"{longEntry}5",
                    FullName      = $@"{longEntry}1\{longEntry}2\{longEntry}3\{longEntry}4\{longEntry}5",
                    HierachyLevel = 5, // gives an average lenth of 40 allowed chars per level
                    IdPath        = @"id1\id2\id3\id4",
                    RepositoryId  = "id5",
                    Type          = TempValidationObjectType.Folder
                }
            };

            // Act
            var result = validator.GetNewShorterNameForLongestElement(packageItems);

            // Assert
            result.Key.Should().Be("id1"); // The first found entry
            // we just cut off one char from the longest entry, as we don't want to cut off
            // too much chars from one entry, if the distribution of length is similar
            result.Value.Should().Be(longEntry.Substring(0, longEntry.Length));
        }
Esempio n. 4
0
        public async Task <IHttpActionResult> Update(PackagesEditViewModel viewModel)
        {
            try
            {
                //Validation
                Package   package = Db.Packages.FirstOrDefault(p => p.Id == viewModel.Id);
                Validator result  = PackageValidator.Edit(viewModel, package);

                if (!result.Success)
                {
                    return(BadRequest(result.ErrorMessage));
                }

                viewModel.UpdatePackage(package);

                await Db.SaveChangesAsync();

                return(Ok("Package updated successfully"));
            }
            catch (DbUpdateConcurrencyException)
            {
                return(BadRequest("Package was changed by another user"));
            }
            catch
            {
                return(BadRequest("An error has occurred"));
            }
        }
        public void New_name_returns_shorter_name_for_file_without_extension()
        {
            // Arrange
            var validator = new PackageValidator();
            // file name with 200 chars
            var longEntry =
                "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua, At vero eos et accusam et justo duo doloresi";
            var packageItems = new List <TempValidationObject>
            {
                new TempValidationObject
                {
                    // Fullname sind 205
                    Path          = @"Test",
                    Name          = longEntry,
                    FullName      = $@"Test\{longEntry}",
                    HierachyLevel = 2,
                    IdPath        = @"id1",
                    RepositoryId  = "id2",
                    Type          = TempValidationObjectType.File
                }
            };

            // Act
            var result = validator.GetNewShorterNameForLongestElement(packageItems);

            // Assert
            result.Key.Should().Be("id2");
            // Ester Eintrag um 5 gekürzt
            result.Value.Should().Be(longEntry.Substring(0, longEntry.Length - 5));
            // Make sure not dot in filename
            result.Value.Should().NotContain(".");
        }
        public void Make_sure_duplicate_file_names_are_extended_with_suffix()
        {
            // Arrange
            var validator = new PackageValidator();
            var package   = CreateTestData();
            // Pick a directory and add files with same name
            var dir = package.Folders.FirstOrDefault(f => f.Id == "Dir00000032");

            dir.Files.AddRange(new[]
            {
                new RepositoryFile {
                    Id = "T1", LogicalName = "p1.pdf", PhysicalName = "p1.pdf"
                },
                new RepositoryFile {
                    Id = "T2", LogicalName = "p1.pdf", PhysicalName = "p1.pdf"
                },
                new RepositoryFile {
                    Id = "T3", LogicalName = "p1.pdf", PhysicalName = "p1.pdf"
                }
            });

            // Act
            validator.EnsureValidPhysicalFileAndFolderNames(package, @"C:\Users\jlang\Downloads\Repository");

            // Assert
            var flatList = validator.ConvertToRepositoryObject(package);

            flatList.First(f => f.RepositoryId == "T1").Name.Should().Be("p1.pdf");
            flatList.First(f => f.RepositoryId == "T2").Name.Should().Be("p1_1.pdf");
            flatList.First(f => f.RepositoryId == "T3").Name.Should().Be("p1_2.pdf");
        }
        void ValidatePackage()
        {
            PackageDetails details = store.LoadPackageFromStore(Location);

            if (details != null)
            {
                Warnings = details.Warnings;
                Id       = details.PackageId;
            }
            else
            {
                PackageValidatorSettings settings = new PackageValidatorSettings(ValidationBehavior.LogWarning, ValidationBehavior.None, ValidationBehavior.Enforce, ValidationBehavior.LogWarning);
                ValidationResults        log      = PackageValidator.Validate(reader, settings);
                if (log.HasErrors)
                {
                    // Shouldn't have any since enforcing errors.
                    throw new SafeToDisplayException(log, culture.Format(culture.Resources.PackageNotValid, string.Empty));
                }
                else if (log.HasWarnings)
                {
                    using (System.Xml.XmlReader xmlLog = log.ToXml())
                    {
                        Warnings = LearningStoreXml.CreateAndLoad(xmlLog);
                    }
                }
            }
        }
        public RunViaUnityEditorStrategy(ISolution solution,
                                         IUnitTestResultManager unitTestResultManager,
                                         UnityEditorProtocol editorProtocol,
                                         NUnitTestProvider unitTestProvider,
                                         IUnitTestElementIdFactory idFactory,
                                         ISolutionSaver riderSolutionSaver,
                                         UnityRefresher unityRefresher,
                                         NotificationsModel notificationsModel,
                                         UnityHost unityHost,
                                         ILogger logger,
                                         Lifetime lifetime,
                                         PackageValidator packageValidator
                                         )
        {
            mySolution = solution;
            myUnitTestResultManager = unitTestResultManager;
            myEditorProtocol        = editorProtocol;
            myUnitTestProvider      = unitTestProvider;
            myIDFactory             = idFactory;
            myRiderSolutionSaver    = riderSolutionSaver;
            myUnityRefresher        = unityRefresher;
            myNotificationsModel    = notificationsModel;
            myUnityHost             = unityHost;
            myLogger           = logger;
            myLifetime         = lifetime;
            myPackageValidator = packageValidator;
            myElements         = new WeakToWeakDictionary <UnitTestElementId, IUnitTestElement>();

            myUnityProcessId = new Property <int?>(lifetime, "RunViaUnityEditorStrategy.UnityProcessId");

            myUnityProcessId.ForEachValue_NotNull(lifetime, (lt, processId) =>
            {
                var process = myLogger.CatchIgnore(() => Process.GetProcessById(processId.NotNull()));
                if (process == null)
                {
                    myUnityProcessId.Value = null;
                    return;
                }

                process.EnableRaisingEvents = true;

                void OnProcessExited(object sender, EventArgs a) => myUnityProcessId.Value = null;
                lt.Bracket(() => process.Exited += OnProcessExited, () => process.Exited -= OnProcessExited);

                if (process.HasExited)
                {
                    myUnityProcessId.Value = null;
                }
            });

            myEditorProtocol.UnityModel.ViewNotNull(lifetime, (lt, model) =>
            {
                if (model.UnityProcessId.HasValue())
                {
                    myUnityProcessId.Value = model.UnityProcessId.Value;
                }

                model.UnityProcessId.FlowInto(lt, myUnityProcessId, id => id);
            });
        }
        protected override void Init(IDictionary <string, string> arguments, CancellationToken cancellationToken)
        {
            var gallery            = arguments.GetOrThrow <string>(Arguments.Gallery);
            var index              = arguments.GetOrThrow <string>(Arguments.Index);
            var packageBaseAddress = arguments.GetOrThrow <string>(Arguments.ContentBaseAddress);
            var source             = arguments.GetOrThrow <string>(Arguments.Source);
            var requireSignature   = arguments.GetOrDefault(Arguments.RequireSignature, false);
            var verbose            = arguments.GetOrDefault(Arguments.Verbose, false);

            CommandHelpers.AssertAzureStorage(arguments);

            var monitoringStorageFactory = CommandHelpers.CreateStorageFactory(arguments, verbose);
            var auditingStorageFactory   = CommandHelpers.CreateSuffixedStorageFactory("Auditing", arguments, verbose);

            var endpointInputs        = CommandHelpers.GetEndpointFactoryInputs(arguments);
            var messageHandlerFactory = CommandHelpers.GetHttpMessageHandlerFactory(TelemetryService, verbose);

            Logger.LogInformation(
                "CONFIG gallery: {Gallery} index: {Index} storage: {Storage} auditingStorage: {AuditingStorage} endpoints: {Endpoints}",
                gallery, index, monitoringStorageFactory, auditingStorageFactory, string.Join(", ", endpointInputs.Select(e => e.Name)));

            _packageValidator = new PackageValidatorFactory(LoggerFactory)
                                .Create(gallery, index, packageBaseAddress, auditingStorageFactory, endpointInputs, messageHandlerFactory, requireSignature, verbose);

            _queue = CommandHelpers.CreateStorageQueue <PackageValidatorContext>(arguments, PackageValidatorContext.Version);

            _statusService = CommandHelpers.GetPackageMonitoringStatusService(arguments, monitoringStorageFactory, LoggerFactory);

            _notificationService = new LoggerMonitoringNotificationService(LoggerFactory.CreateLogger <LoggerMonitoringNotificationService>());

            _regResource = Repository.Factory.GetCoreV3(index).GetResource <RegistrationResourceV3>(cancellationToken);

            _client = new CollectorHttpClient(messageHandlerFactory());
        }
Esempio n. 10
0
        public List <string> Validate(string path, ref int countCourses, ref int countValidCourses, ref int countInvalidCourses)
        {
            List <string> messages = new List <string>();

            var pathToExtract = Path.Combine(GetFolderPath(), Guid.NewGuid().ToString());

            Zipper.ExtractZipFile(path, pathToExtract);

            if (Directory.GetFiles(pathToExtract, "*.disc").Count() == 0)
            {
                messages.Add("Archive doesn't contain file with .disc extension");
            }

            string[] files = Directory.GetFiles(pathToExtract, "*.zip");
            countCourses = files.Count();

            foreach (var courseFile in files)
            {
                List <string> courseMessages = PackageValidator.Validate(courseFile);
                messages.AddRange(courseMessages.AsEnumerable());

                if (courseMessages.Contains("Package is valid."))
                {
                    countValidCourses++;
                }
                else
                {
                    countInvalidCourses++;
                }
            }

            Directory.Delete(pathToExtract, true);

            return(messages);
        }
Esempio n. 11
0
        public bool Validate(HttpPostedFileBase file)
        {
            var fileName = GetImportFileName(Path.GetFileNameWithoutExtension(file.FileName));
            var path     = Path.Combine(GetFolderPath(), fileName);

            Directory.CreateDirectory(GetFolderPath());
            file.SaveAs(path);
            var pathToExtract = Path.Combine(GetFolderPath(), Guid.NewGuid().ToString());

            Zipper.ExtractZipFile(path, pathToExtract);

            if (Directory.GetFiles(pathToExtract, "*.disc").Count() == 0)
            {
                Directory.Delete(pathToExtract, true);
                return(false);
            }

            foreach (var courseFile in Directory.GetFiles(pathToExtract, "*.zip"))
            {
                if (!PackageValidator.Validate(courseFile).Contains("Package is valid."))
                {
                    Directory.Delete(pathToExtract, true);
                    return(false);
                }
            }

            Directory.Delete(pathToExtract, true);
            return(true);
        }
        public void New_name_returns_shorter_name_for_folder()
        {
            // Arrange
            var validator = new PackageValidator();
            var longEntry =
                "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores";
            var packageItems = new List <TempValidationObject>
            {
                new TempValidationObject
                {
                    // Erster Eintrag hat 200 Zeichen
                    // Fullname sind 217
                    Path          = $@"{longEntry}\Test",
                    Name          = "My Directory",
                    FullName      = $@"{longEntry}\Test\My Directory",
                    HierachyLevel = 3,
                    IdPath        = @"id1\id2",
                    RepositoryId  = "id3",
                    Type          = TempValidationObjectType.Folder
                }
            };

            // Act
            var result = validator.GetNewShorterNameForLongestElement(packageItems);

            // Assert
            result.Key.Should().Be("id1");
            // Ester Eintrag um 17 Zeichen gekürzt (und getrimmt)
            result.Value.Should().Be(longEntry.Substring(0, longEntry.Length - 17).Trim());
        }
Esempio n. 13
0
        public void PackageValidatorInvalidPackageTest()
        {
            var  path = Path.Combine(this.root, @"Invalid package.zip");
            bool valid;
            var  res = PackageValidator.Validate(path, out valid);

            Assert.IsTrue(res.Count == 6);
        }
Esempio n. 14
0
        public void PackageValidatorValidPackageTest()
        {
            //path to file which we want to validate
            var  path = Path.Combine(this.root, @"Valid package.zip");
            bool valid;
            var  res = PackageValidator.Validate(path, out valid);

            Assert.IsTrue(res.Count == 1);
        }
        public RunViaUnityEditorStrategy(ISolution solution,
                                         IUnitTestResultManager unitTestResultManager,
                                         BackendUnityHost backendUnityHost,
                                         NUnitTestProvider unitTestProvider,
                                         IUnitTestElementIdFactory idFactory,
                                         ISolutionSaver riderSolutionSaver,
                                         UnityRefresher unityRefresher,
                                         NotificationsModel notificationsModel,
                                         FrontendBackendHost frontendBackendHost,
                                         ILogger logger,
                                         Lifetime lifetime,
                                         PackageValidator packageValidator,
                                         JetBrains.Application.ActivityTrackingNew.UsageStatistics usageStatistics)
        {
            mySolution = solution;
            myUnitTestResultManager = unitTestResultManager;
            myBackendUnityHost      = backendUnityHost;
            myUnitTestProvider      = unitTestProvider;
            myIDFactory             = idFactory;
            myRiderSolutionSaver    = riderSolutionSaver;
            myUnityRefresher        = unityRefresher;
            myNotificationsModel    = notificationsModel;
            myFrontendBackendHost   = frontendBackendHost;
            myLogger           = logger;
            myLifetime         = lifetime;
            myPackageValidator = packageValidator;
            myUsageStatistics  = usageStatistics;

            myUnityProcessId = new Property <int?>(lifetime, "RunViaUnityEditorStrategy.UnityProcessId");

            myUnityProcessId.ForEachValue_NotNull(lifetime, (lt, processId) =>
            {
                var process = myLogger.CatchIgnore(() => Process.GetProcessById(processId.NotNull()));
                if (process == null)
                {
                    myUnityProcessId.Value = null;
                    return;
                }

                process.EnableRaisingEvents = true;

                void OnProcessExited(object sender, EventArgs a) => myUnityProcessId.Value = null;
                lt.Bracket(() => process.Exited += OnProcessExited, () => process.Exited -= OnProcessExited);

                if (process.HasExited)
                {
                    myUnityProcessId.Value = null;
                }
            });

            myBackendUnityHost.BackendUnityModel.ViewNotNull(lifetime, (lt, model) =>
            {
                // This will set the current value, if it exists
                model.UnityApplicationData.FlowInto(lt, myUnityProcessId, data => data.UnityProcessId);
            });
        }
Esempio n. 16
0
        public void Constructor_WhenArgumentsAreValid_InitializesInstance()
        {
            var validator = new PackageValidator(
                _aggregateValidators,
                _storageFactory,
                _feedToSource,
                _logger,
                _contextLogger);

            Assert.Equal(_aggregateValidators, validator.AggregateValidators);
        }
        void Initialize()
        {
            IsNonELearning = PackageValidator.ValidateIsELearning(reader).HasErrors;

            if (IsNonELearning == false)
            {
                ValidatePackage();

                ManifestReader     manifestReader = new ManifestReader(reader, new ManifestReaderSettings(true, true));
                MetadataNodeReader metadataReader = manifestReader.Metadata;

                // set <title> to the title to display for the package, using these rules:
                //   1. if there's a Title column value, use it;
                //   2. otherwise, if there's a title specified in the package metadata, use it;
                //   3. otherwise, use the file name without the extension
                if (String.IsNullOrEmpty(file.Title) == false)
                {
                    Title = file.Title;
                }
                else
                {
                    string titleFromMetadata = metadataReader.GetTitle(culture.Culture);
                    if (string.IsNullOrEmpty(titleFromMetadata) == false)
                    {
                        Title = titleFromMetadata;
                    }
                    else
                    {
                        Title = System.IO.Path.GetFileNameWithoutExtension(file.Name);
                    }
                }

                // set description to the package description specified in metadata, or null if none
                IList <string> descriptions = metadataReader.GetDescriptions(culture.Culture);
                if (descriptions.Count > 0)
                {
                    Description = descriptions[0];
                    if (Description == null)
                    {
                        Description = string.Empty;
                    }
                }
                else
                {
                    Description = string.Empty;
                }

                // populate the drop-down list of organizations; hide the entire row containing that
                // drop-down if there's only one organization
                Organizations         = manifestReader.Organizations;
                DefaultOrganizationId = manifestReader.DefaultOrganization.Id;
                PackageFormat         = manifestReader.PackageFormat;
            }
        }
        public void Invalid_chars_in_path_are_replaced_with_underscore()
        {
            // Arrange
            var package   = CreateTestData();
            var validator = new PackageValidator();

            // Act
            validator.CreateValidNames(package);

            // Assert
            package.Folders.First(f => f.Id == "Dir00000001").PhysicalName.Should().Be("Das ist ein Ordner_name mit _ ungültigen _ Zeichen _");
        }
        public void Make_sure_very_long_duplicate_file_names_on_deep_nested_folders_are_extended_with_suffix()
        {
            // Arrange
            var validator = new PackageValidator();
            var package   = CreateTestData();

            // Get to the lowest level folder
            var dir = package.Folders.First();

            while (dir.Folders.Any())
            {
                dir = dir.Folders.First();
            }

            // Add duplicate files too long names
            dir.Files.AddRange(new[]
            {
                new RepositoryFile
                {
                    Id          = "T1",
                    LogicalName =
                        "this is a very long name for the pdf file that might lead to problems when saving the content to disk and might be problematic when creating the package.pdf",
                    PhysicalName =
                        "this is a very long name for the pdf file that might lead to problems when saving the content to disk and might be problematic when creating the package.pdf"
                },
                new RepositoryFile
                {
                    Id          = "T2",
                    LogicalName =
                        "this is a very long name for the pdf file that might lead to problems when saving the content to disk and might be problematic when creating the package.pdf",
                    PhysicalName =
                        "this is a very long name for the pdf file that might lead to problems when saving the content to disk and might be problematic when creating the package.pdf"
                },
                new RepositoryFile
                {
                    Id          = "T3",
                    LogicalName =
                        "this is a very long name for the pdf file that might lead to problems when saving the content to disk and might be problematic when creating the package.pdf",
                    PhysicalName =
                        "this is a very long name for the pdf file that might lead to problems when saving the content to disk and might be problematic when creating the package.pdf"
                }
            });

            // Act
            validator.EnsureValidPhysicalFileAndFolderNames(package, @"C:\Users\jlang\Downloads\Repository");

            // Assert
            var flatList = validator.ConvertToRepositoryObject(package);

            flatList.First(f => f.RepositoryId == "T1").Name.Should().Be("this is a very long name for.pdf");
            flatList.First(f => f.RepositoryId == "T2").Name.Should().Be("this is a very long name for_1.pdf");
            flatList.First(f => f.RepositoryId == "T3").Name.Should().Be("this is a very long name for_2.pdf");
        }
        public void Invalid_chars_in_file_are_replaced_with_underscore()
        {
            // Arrange
            var package   = CreateTestData();
            var validator = new PackageValidator();

            // Act
            validator.CreateValidNames(package);

            // Assert
            package.Files.First(f => f.Id == "F00000001").PhysicalName.Should().Be("Und _ ein Datei_Name mit _ _ Sonderzeichen.pdf");
        }
        public void Invalid_chars_in_folder_with_long_name_are_replaced_with_underscore()
        {
            // Arrange
            var package   = CreateTestData();
            var validator = new PackageValidator();

            // Act
            validator.CreateValidNames(package);

            // Assert
            package.Folders.First(f => f.Id == "Dir00000001").Folders.First(f => f.Id == "Dir00000002").PhysicalName.Should().Be(
                "Das ist ein Ordner_name mit _ ungültigen _ Zeichen _ und der dann noch überaus lang ist und viele Zeichen enthält bis er dann irgend wann");
        }
        public void Make_sure_a_normal_root_path_shortens_max_path_length_to_exactly_200_chars()
        {
            // Arrange
            var validator = new PackageValidator();
            var package   = CreateTestData();

            // Act
            validator.EnsureValidPhysicalFileAndFolderNames(package, @"C:\Users\jlang\Downloads\Repository\");
            var list = validator.ConvertToRepositoryObject(package);

            // Assert
            validator.MaxPathLength.Should().Be(200);
        }
        public void Invalid_chars_in_file_with_long_name_are_replaced_with_underscore()
        {
            // Arrange
            var package   = CreateTestData();
            var validator = new PackageValidator();

            // Act
            validator.CreateValidNames(package);

            // Assert
            package.Files.First(f => f.Id == "F00000002").PhysicalName.Should().Be(
                "Und _ ein Datei_Name mit _ _ Sonderzeichen und deren Name dann noch überaus lang ist und viele Zeichen enthält bis er dann irgend wann einfach zu lang ist.pdf");
        }
        public void Make_sure_too_long_path_names_are_shortened()
        {
            // Arrange
            var validator = new PackageValidator();
            var package   = CreateTestData();

            // Act
            validator.EnsureValidPhysicalFileAndFolderNames(package, @"C:\Users\jlang\Downloads\Repository");
            var list = validator.ConvertToRepositoryObject(package);

            // Assert
            (list.Max(l => l.FullName.Length) > validator.MaxPathLength).Should().BeFalse();
        }
        public void Make_sure_we_have_too_long_path_names_correct()
        {
            // Arrange
            var validator = new PackageValidator();
            var package   = CreateTestData();

            validator.CreateValidNames(package);

            // Act
            var list = validator.ConvertToRepositoryObject(package);

            // Assert
            (list.Max(l => l.FullName.Length) > validator.MaxPathLength).Should().BeTrue();
        }
        public void Make_sure_a_long_root_path_shortens_max_path_length_below_200_chars()
        {
            // Arrange
            var validator = new PackageValidator();
            var package   = CreateTestData();

            // Act
            validator.EnsureValidPhysicalFileAndFolderNames(package,
                                                            @"C:\Users\jlang\Downloads\Repository\with a very long path name\that exceeds 60 chars\just for testing");
            var list = validator.ConvertToRepositoryObject(package);

            // Assert
            validator.MaxPathLength.Should().BeLessThan(200);
        }
        public void Update_package_file_with_new_name()
        {
            // Arrange
            var validator = new PackageValidator();
            var package   = CreateTestData();

            // Act
            validator.UpdatePackage(package, new KeyValuePair <string, string>("F00000119", "Happy"));


            // Assert
            var flatList = validator.ConvertToRepositoryObject(package);

            flatList.First(f => f.RepositoryId == "F00000119").Name.Should().Be("Happy");
        }
        public void Make_sure_trainling_dots_at_the_end_of_names_are_removed()
        {
            // Arrange
            var validator = new PackageValidator();
            // file 119 and Dir 5 have illegal endings in test file
            var package = CreateTestData();

            // Act
            validator.EnsureValidPhysicalFileAndFolderNames(package, @"C:\Users\jlang\Downloads\Repository");

            // Assert
            var flatList = validator.ConvertToRepositoryObject(package);

            flatList.First(f => f.RepositoryId == "F00000119").Name.Should().Be("TABLE BROWN.pdf");
            flatList.First(f => f.RepositoryId == "Dir00000005").Name.Should().Be("Zjing Oil");
        }
        public void Make_sure_duplicate_file_names_are_extended_with_suffix2()
        {
            // Arrange
            var validator = new PackageValidator();

            // Sample Package has one duplicate file "\PLUS_3\PLUS3_Bern_V1\P0.pdf"
            var packageTestData = File.ReadAllText(Path.Combine(TestContext.CurrentContext.TestDirectory, "packageSampleData.json"), Encoding.UTF8);
            var package         = JsonConvert.DeserializeObject <RepositoryPackage>(packageTestData);

            // Act
            validator.EnsureValidPhysicalFileAndFolderNames(package, @"C:\Users\jlang\Downloads\Repository");

            // Assert
            var flatList = validator.ConvertToRepositoryObject(package);

            flatList.First(f => f.RepositoryId == "sdb:digitalFile|685fbf49-d67c-4f60-9842-96c35d009210").Name.Should().Be("P0_1.pdf");
        }
Esempio n. 30
0
        public async Task ValidateAsync_WhenCancellationTokenIsCancelled_Throws()
        {
            var validator = new PackageValidator(
                _aggregateValidators,
                _storageFactory,
                _feedToSource,
                _logger,
                _contextLogger);

            var context = new PackageValidatorContext(
                new FeedPackageIdentity(id: "a", version: "1.0.0"),
                catalogEntries: Enumerable.Empty <CatalogIndexEntry>());

            using (var client = new CollectorHttpClient())
            {
                await Assert.ThrowsAsync <OperationCanceledException>(
                    () => validator.ValidateAsync(context, client, new CancellationToken(canceled: true)));
            }
        }