예제 #1
0
        public void DeleteConfigurationResetsReversalToShippedDefaultIfNoProjectAllReversal()
        {
            var defaultReversalPath = Path.Combine(FwDirectoryFinder.DefaultConfigurations, "ReversalIndex");

            // construct a controller to work in the default reversal directory
            _controller = new DictionaryConfigurationManagerController(Cache, null, _configurations, new List <string>(), _projectConfigPath, defaultReversalPath);
            var allRevFileName = DictionaryConfigurationModel.AllReversalIndexesFilenameBase + DictionaryConfigurationModel.FileExtension;
            var shippedRootDefaultConfigurationPath = Path.Combine(defaultReversalPath, allRevFileName);

            FileUtils.WriteStringtoFile(shippedRootDefaultConfigurationPath, "bogus data that is unread, the file is read from the real defaults", Encoding.UTF8);

            var configurationToDelete = _configurations[0];

            configurationToDelete.FilePath      = Path.Combine("whateverdir", "en" + DictionaryConfigurationModel.FileExtension);
            configurationToDelete.Label         = "English";
            configurationToDelete.WritingSystem = "en";

            var pathToConfiguration = configurationToDelete.FilePath;

            FileUtils.WriteStringtoFile(pathToConfiguration, "customized file contents", Encoding.UTF8);
            Assert.That(FileUtils.FileExists(pathToConfiguration), "Unit test not set up right");
            Assert.IsFalse(FileUtils.FileExists(Path.Combine(_projectConfigPath, allRevFileName)), "Unit test not set up right");

            // SUT
            _controller.DeleteConfiguration(configurationToDelete);

            Assert.That(FileUtils.FileExists(pathToConfiguration), "The English reversal file should have been reset to defaults, not deleted.");
            Assert.That(configurationToDelete.Label, Is.EqualTo("English"), "The label should still be English after a reset.");
            Assert.That(configurationToDelete.WritingSystem, Is.EqualTo("en"), "The writingsystem should still be en after a reset.");
            Assert.That(configurationToDelete.IsReversal, Is.True, "The reset configuration files should still be a reversal file.");
            Assert.Contains(configurationToDelete, _configurations, "The configuration should still be present in the list after being reset.");
            Assert.That(_controller.IsDirty, "Resetting is a change that is saved later; should be dirty");

            // Not asserting that the configurationToDelete.FilePath file contents are reset because that will happen later when it is saved.
        }
예제 #2
0
        private string UserRequestsOverwrite_Helper()
        {
            // This model has the same label but a non-colliding filename. Proves overwrite the code will always overwrite.
            var alreadyExistingModelWithSameLabel = new DictionaryConfigurationModel
            {
                Label        = configLabel,
                Publications = new List <string> {
                    "Main Dictionary", "unknown pub 1", "unknown pub 2"
                },
                FilePath = Path.Combine(_projectConfigPath, "Different" + configFilename)
            };

            FileUtils.WriteStringtoFile(alreadyExistingModelWithSameLabel.FilePath, "arbitrary file content", Encoding.UTF8);
            var anotherAlreadyExistingModel = new DictionaryConfigurationModel
            {
                Label        = "importexportConfiguration-Imported1",
                Publications = new List <string> {
                    "Main Dictionary", "unknown pub 1", "unknown pub 2"
                },
                FilePath = Path.GetTempPath() + configFilename
            };

            DictionaryConfigurationManagerController.GenerateFilePath(_projectConfigPath, _controller._configurations,
                                                                      anotherAlreadyExistingModel);
            FileUtils.WriteStringtoFile(anotherAlreadyExistingModel.FilePath, "arbitrary file content", Encoding.UTF8);

            _controller._configurations.Add(alreadyExistingModelWithSameLabel);
            _controller._configurations.Add(anotherAlreadyExistingModel);

            _controller.PrepareImport(_zipFile);

            return(alreadyExistingModelWithSameLabel.FilePath);
        }
예제 #3
0
 public void ExportConfiguration_ThrowsOnBadInput()
 {
     Assert.Throws <ArgumentNullException>(() => DictionaryConfigurationManagerController.ExportConfiguration(null, "a", Cache));
     Assert.Throws <ArgumentNullException>(() => DictionaryConfigurationManagerController.ExportConfiguration(_configurations[0], null, Cache));
     Assert.Throws <ArgumentNullException>(() => DictionaryConfigurationManagerController.ExportConfiguration(_configurations[0], "a", null));
     Assert.Throws <ArgumentNullException>(() => DictionaryConfigurationManagerController.ExportConfiguration(null, null, null));
     // Empty string
     Assert.Throws <ArgumentException>(() => DictionaryConfigurationManagerController.ExportConfiguration(_configurations[0], "", Cache));
 }
예제 #4
0
        public void GenerateFilePath_AccountsForFilesOnDisk()
        {
            List <DictionaryConfigurationModel> conflictingConfigs;
            var configToRename = GenerateFilePath_Helper(out conflictingConfigs);

            FileUtils.WriteStringtoFile(Path.Combine(_projectConfigPath, "configuration3_3.fwdictconfig"), "file contents of config file that is in the way on disk but not actually registered in the list of configurations", Encoding.UTF8);

            // SUT
            DictionaryConfigurationManagerController.GenerateFilePath(_controller._projectConfigDir, _controller._configurations, configToRename);

            var newFilePath = configToRename.FilePath;

            Assert.That(newFilePath, Is.EqualTo(Path.Combine(_projectConfigPath, "configuration3_4.fwdictconfig")), "Did not account for collision with unregistered configuration on disk");
        }
예제 #5
0
        public void Rename_RenamesConfigAndFile()
        {
            const string newLabel       = "NewLabel";
            var          selectedConfig = _configurations[0];

            selectedConfig.FilePath = null;
            // SUT
            Assert.True(_controller.RenameConfiguration(new ListViewItem {
                Tag = selectedConfig
            }, new LabelEditEventArgs(0, newLabel)),
                        "Renaming a config to a unique name should complete successfully");
            Assert.AreEqual(newLabel, selectedConfig.Label, "The configuration should have been renamed");
            Assert.AreEqual(DictionaryConfigurationManagerController.FormatFilePath(_controller._projectConfigDir, newLabel), selectedConfig.FilePath, "The FilePath should have been generated");
            Assert.True(_controller.IsDirty, "Made changes; should be dirty");
        }
예제 #6
0
        public void PrepareCustomFieldsExport_Works()
        {
            var customFieldLabel = "TestField";

            using (new CustomFieldForTest(Cache, customFieldLabel, customFieldLabel, LexEntryTags.kClassId, StTextTags.kClassId, -1,
                                          CellarPropertyType.OwningAtomic, Guid.Empty))
            {
                // SUT
                var customFieldFiles = DictionaryConfigurationManagerController.PrepareCustomFieldsExport(Cache).ToList();
                Assert.That(customFieldFiles.Count, Is.EqualTo(2), "Not enough files prepared");
                Assert.That(customFieldFiles[0], Is.StringEnding("CustomFields.lift"));
                Assert.That(customFieldFiles[1], Is.StringEnding("CustomFields.lift-ranges"));
                AssertThatXmlIn.File(customFieldFiles[0]).HasAtLeastOneMatchForXpath("//field[@tag='" + customFieldLabel + "']");
            }
        }
예제 #7
0
        public void DeleteConfigurationRemovesFromDisk()
        {
            var configurationToDelete = _configurations[0];

            DictionaryConfigurationManagerController.GenerateFilePath(_controller._projectConfigDir, _controller._configurations, configurationToDelete);
            var pathToConfiguration = configurationToDelete.FilePath;

            FileUtils.WriteStringtoFile(pathToConfiguration, "file contents", Encoding.UTF8);
            Assert.That(FileUtils.FileExists(pathToConfiguration), "Unit test not set up right");

            // SUT
            _controller.DeleteConfiguration(configurationToDelete);

            Assert.That(!FileUtils.FileExists(pathToConfiguration), "File should have been deleted");
            Assert.That(_controller.IsDirty, "made changes; should be dirty");
        }
예제 #8
0
        public void FormatFilePath()
        {
            var formattedFilePath = DictionaryConfigurationManagerController.FormatFilePath(_controller._projectConfigDir, "\nFile\\Name/With\"Chars<?>");             // SUT

            StringAssert.StartsWith(_projectConfigPath, formattedFilePath);
            StringAssert.EndsWith(DictionaryConfigurationModel.FileExtension, formattedFilePath);
            StringAssert.DoesNotContain("\n", formattedFilePath);
            StringAssert.DoesNotContain("\\", Path.GetFileName(formattedFilePath));
            StringAssert.DoesNotContain("/", Path.GetFileName(formattedFilePath));
            StringAssert.DoesNotContain("\"", formattedFilePath);
            StringAssert.DoesNotContain("<", formattedFilePath);
            StringAssert.DoesNotContain("?", formattedFilePath);
            StringAssert.DoesNotContain(">", formattedFilePath);
            StringAssert.Contains("File", formattedFilePath);
            StringAssert.Contains("Name", formattedFilePath);
            StringAssert.Contains("With", formattedFilePath);
            StringAssert.Contains("Chars", formattedFilePath);
        }
예제 #9
0
        public void GenerateFilePath()
        {
            List <DictionaryConfigurationModel> conflictingConfigs;
            var configToRename = GenerateFilePath_Helper(out conflictingConfigs);

            // SUT
            DictionaryConfigurationManagerController.GenerateFilePath(_controller._projectConfigDir, _controller._configurations, configToRename);

            var newFilePath = configToRename.FilePath;

            StringAssert.StartsWith(_projectConfigPath, newFilePath);
            StringAssert.EndsWith(DictionaryConfigurationModel.FileExtension, newFilePath);
            Assert.AreEqual(DictionaryConfigurationManagerController.FormatFilePath(_controller._projectConfigDir, "configuration3_3"), configToRename.FilePath, "The file path should be based on the label");
            foreach (var config in conflictingConfigs)
            {
                Assert.AreNotEqual(Path.GetFileName(newFilePath), Path.GetFileName(config.FilePath), "File name should be unique");
            }
        }
예제 #10
0
        public void DoImport_UseUniqueFileNameToAvoidCollision()
        {
            var alreadyExistingModelWithSameLabel = new DictionaryConfigurationModel
            {
                Label        = configLabel,
                Publications = new List <string>(),
            };

            DictionaryConfigurationManagerController.GenerateFilePath(_projectConfigPath, _controller._configurations,
                                                                      alreadyExistingModelWithSameLabel);

            var anotherAlreadyExistingModel = new DictionaryConfigurationModel
            {
                Label        = "importexportConfiguration-Imported1",
                Publications = new List <string>(),
            };

            DictionaryConfigurationManagerController.GenerateFilePath(_projectConfigPath, _controller._configurations,
                                                                      anotherAlreadyExistingModel);

            _controller._configurations.Add(alreadyExistingModelWithSameLabel);
            _controller._configurations.Add(anotherAlreadyExistingModel);

            // File that exists but isn't actually registered in the list of configurations
            var fileInTheWay = Path.Combine(_projectConfigPath, "importexportConfiguration-Imported2.fwdictconfig");

            // ReSharper disable once LocalizableElement
            File.WriteAllText(fileInTheWay, "arbitrary file content");

            _controller.PrepareImport(_zipFile);

            // SUT
            _controller.DoImport();
            // What the filename is will be a combination of label collision handling in PrepareImport() and existing file collision handling performed by DictionaryConfigurationManagerController.
            Assert.That(File.Exists(Path.Combine(_projectConfigPath, "importexportConfiguration-Imported2_1.fwdictconfig")),
                        "Configuration not imported or to the right place. Perhaps the existing but not-registered importexportConfiguration-Imported2.fwdictconfig file was not accounted for.");
            Assert.That(_controller._configurations.Any(config => config.Label == "importexportConfiguration-Imported2"),
                        "Imported configuration was not registered, or with the expected label.");
            Assert.That(_controller.NewConfigToImport.FilePath,
                        Is.EqualTo(Path.Combine(_projectConfigPath, "importexportConfiguration-Imported2_1.fwdictconfig")),
                        "FilePath of imported config was not set as expected.");
        }
예제 #11
0
        public void PrepareStylesheetExport_Works()
        {
            // SUT
            var styleSheetFile = DictionaryConfigurationManagerController.PrepareStylesheetExport(Cache);

            Assert.False(string.IsNullOrEmpty(styleSheetFile), "No stylesheet data prepared");
            AssertThatXmlIn.File(styleSheetFile).HasSpecifiedNumberOfMatchesForXpath("/Styles/markup", 1);
            AssertThatXmlIn.File(styleSheetFile).HasSpecifiedNumberOfMatchesForXpath("/Styles/markup/tag[@id='" + _characterTestStyle.Name + "']", 1);
            var enWsId = Cache.WritingSystemFactory.GetStrFromWs(_characterTestStyle.Usage.AvailableWritingSystemIds[0]);

            AssertThatXmlIn.File(styleSheetFile).HasSpecifiedNumberOfMatchesForXpath("/Styles/markup/tag/usage[@wsId='" + enWsId + "']", 1);
            // Test font color, underline, underline color, bold and italic
            var attributeTests = "@family='times' and @color='red' and @underline='double' and @underlineColor='blue' and @bold='true' and @italic='true'";

            AssertThatXmlIn.File(styleSheetFile).HasSpecifiedNumberOfMatchesForXpath("/Styles/markup/tag/font[" + attributeTests + "]", 1);

            AssertThatXmlIn.File(styleSheetFile).HasSpecifiedNumberOfMatchesForXpath("/Styles/markup/tag[@id='" + _paraTestStyle.Name + "']", 1);
            // Test paragraph alignment margins and spacing
            attributeTests = "@lineSpacing='3 pt' and @lineSpacingType='exact' and @alignment='center' and @indentRight='4 pt' and @hanging='5 pt' and @indentLeft='6 pt' and @spaceBefore='7 pt' and @spaceAfter='8 pt'";
            AssertThatXmlIn.File(styleSheetFile).HasSpecifiedNumberOfMatchesForXpath("/Styles/markup/tag/paragraph[" + attributeTests + "]", 1);
            // Test paragraph background color, TODO border type and bullet info
            attributeTests = "@background='(0,255,0)'";
            AssertThatXmlIn.File(styleSheetFile).HasSpecifiedNumberOfMatchesForXpath("/Styles/markup/tag/paragraph[" + attributeTests + "]", 1);

            // Test that a child style gets the basedOn for paragraph and does not write out inherited values
            AssertThatXmlIn.File(styleSheetFile).HasSpecifiedNumberOfMatchesForXpath("/Styles/markup/tag[@id='" + _paraChildTestStyle.Name + "']", 1);
            attributeTests = string.Format("@basedOn='{0}' and @alignment='full' and not(@lineSpacing='3 pt') and not(@indentRight='4 pt')",
                                           _paraTestStyle.Name);
            AssertThatXmlIn.File(styleSheetFile).HasSpecifiedNumberOfMatchesForXpath("/Styles/markup/tag/paragraph[" + attributeTests + "]", 1);

            // LT-18267 Make sure character styles based on another style have their basedOn
            // information recorded. Assert that there is 1 character style with a non-empty
            // basedOn attribute, that was successfully exported.
            attributeTests = "@type='character' and @basedOn!=''";
            AssertThatXmlIn.File(styleSheetFile).HasSpecifiedNumberOfMatchesForXpath("/Styles/markup/tag[" + attributeTests + "]", 1);

            // Verify that each known unsupported style is excluded from the export
            foreach (var unsupported in DictionaryConfigurationImportController.UnsupportedStyles)
            {
                AssertThatXmlIn.File(styleSheetFile).HasNoMatchForXpath("/Styles/markup/tag[@id='" + unsupported.Replace(' ', '_') + "']");
            }
        }
예제 #12
0
        public void Setup()
        {
            _configurations = new List <DictionaryConfigurationModel>
            {
                new DictionaryConfigurationModel {
                    Label = "configuration0", Publications = new List <string>()
                },
                new DictionaryConfigurationModel {
                    Label = "configuration1", Publications = new List <string>()
                }
            };

            var publications = new List <string>
            {
                "publicationA",
                "publicationB"
            };

            _controller = new DictionaryConfigurationManagerController(Cache, null, _configurations, publications, _projectConfigPath, _defaultConfigPath);
        }
예제 #13
0
        public void ExportConfiguration_ExportsZip()
        {
            // Writing to disk, not just in memory, so can use zip library.

            FileUtils.Manager.Reset();
            string expectedZipOutput = null;

            try
            {
                var configurationToExport = _configurations[0];
                DictionaryConfigurationManagerController.GenerateFilePath(_controller._projectConfigDir, _controller._configurations, configurationToExport);
                var pathToConfiguration = configurationToExport.FilePath;
                expectedZipOutput = Path.GetTempFileName();
                File.WriteAllText(pathToConfiguration, "file contents");
                Assert.That(File.Exists(pathToConfiguration), "Unit test not set up right");
                Assert.That(new FileInfo(expectedZipOutput).Length, Is.EqualTo(0),
                            "Unit test not set up right. File will exist for convenience of writing the test but should not have any content yet.");

                // SUT
                DictionaryConfigurationManagerController.ExportConfiguration(configurationToExport, expectedZipOutput, Cache);

                Assert.That(File.Exists(expectedZipOutput), "File not exported");
                Assert.That(new FileInfo(expectedZipOutput).Length, Is.GreaterThan(0),
                            "Exported file should have content");

                using (var zip = new ZipFile(expectedZipOutput))
                {
                    Assert.That(zip.Count, Is.GreaterThanOrEqualTo(3), "Zip file must be missing parts of the export");
                }
            }
            finally
            {
                if (expectedZipOutput != null)
                {
                    File.Delete(expectedZipOutput);
                }
                FileUtils.Manager.SetFileAdapter(_mockFilesystem);
            }
        }
예제 #14
0
        private DictionaryConfigurationModel GenerateFilePath_Helper(out List <DictionaryConfigurationModel> conflictingConfigs)
        {
            var configToRename = new DictionaryConfigurationModel
            {
                Label        = "configuration3",
                FilePath     = null,
                Publications = new List <string>()
            };

            conflictingConfigs = new List <DictionaryConfigurationModel>
            {
                new DictionaryConfigurationModel
                {
                    Label        = "conflicting file 3-0",
                    FilePath     = DictionaryConfigurationManagerController.FormatFilePath(_controller._projectConfigDir, "configuration3"),
                    Publications = new List <string>()
                },
                new DictionaryConfigurationModel
                {
                    Label        = "conflicting file 3-1",
                    FilePath     = DictionaryConfigurationManagerController.FormatFilePath(_controller._projectConfigDir, "configuration3_1"),
                    Publications = new List <string>()
                },
                new DictionaryConfigurationModel
                {
                    Label =
                        "conflicting file 3-2--in another directory to prove we can't accidentally mask unchanged default configurations",
                    FilePath = Path.Combine(Path.Combine(_projectConfigPath, "subdir"),
                                            "configuration3_2" + DictionaryConfigurationModel.FileExtension),
                    Publications = new List <string>()
                }
            };
            _configurations.Add(configToRename);
            _configurations.AddRange(conflictingConfigs);
            return(configToRename);
        }
예제 #15
0
        /// <summary>
        /// Perform the configuration import that the controller has prepared to do.
        /// </summary>
        internal void DoImport()
        {
            Debug.Assert(NewConfigToImport != null);

            ImportCustomFields(_importLiftLocation);

            // If the configuration to import has the same label as an existing configuration in the project folder
            // then overwrite the existing configuration.
            var existingConfigurationInTheWay = _configurations.FirstOrDefault(config => config.Label == NewConfigToImport.Label &&
                                                                               Path.GetDirectoryName(config.FilePath) == _projectConfigDir);

            NewConfigToImport.Publications.ForEach(
                publication =>
            {
                AddPublicationTypeIfNotPresent(publication, _cache);
            });
            try
            {
                ImportStyles(_importStylesLocation);
                ImportHappened = true;
            }
            catch (InstallationException e)             // This is the exception thrown if the dtd guid in the style file doesn't match our program
            {
#if DEBUG
                if (_view == null)                 // _view is sometimes null in unit tests, and it's helpful to know what exactly went wrong.
                {
                    throw new Exception(xWorksStrings.kstidCannotImport, e);
                }
#endif
                _view.explanationLabel.Text = xWorksStrings.kstidCannotImport;
            }

            // We have re-loaded the model from disk to preserve custom field state so the Label must be set here
            NewConfigToImport.FilePath = _temporaryImportConfigLocation;
            NewConfigToImport.Load(_cache);
            if (existingConfigurationInTheWay != null)
            {
                _configurations.Remove(existingConfigurationInTheWay);
                if (existingConfigurationInTheWay.FilePath != null)
                {
                    FileUtils.Delete(existingConfigurationInTheWay.FilePath);
                }
            }
            else
            {
                NewConfigToImport.Label = _proposedNewConfigLabel;
            }

            // Set a filename for the new configuration. Use a unique filename that isn't either registered with another configuration, or existing on disk. Note that in this way, we ignore what the original filename was of the configuration file in the .zip file.
            DictionaryConfigurationManagerController.GenerateFilePath(_projectConfigDir, _configurations, NewConfigToImport);

            var outputConfigPath = existingConfigurationInTheWay != null ? existingConfigurationInTheWay.FilePath : NewConfigToImport.FilePath;

            File.Move(_temporaryImportConfigLocation, outputConfigPath);

            NewConfigToImport.FilePath = outputConfigPath;
            _configurations.Add(NewConfigToImport);

            // phone home (analytics)
            var configType = NewConfigToImport.Type;
            var configDir  = DictionaryConfigurationListener.GetDefaultConfigurationDirectory(
                configType == DictionaryConfigurationModel.ConfigType.Reversal
                                        ? DictionaryConfigurationListener.ReversalIndexConfigurationDirectoryName
                                        : DictionaryConfigurationListener.DictionaryConfigurationDirectoryName);
            var isCustomizedOriginal = DictionaryConfigurationManagerController.IsConfigurationACustomizedOriginal(NewConfigToImport, configDir, _cache);
            UsageReporter.SendEvent("DictionaryConfigurationImport", "Import", "Import Config",
                                    string.Format("Import of [{0}{1}]:{2}",
                                                  configType, isCustomizedOriginal ? string.Empty : "-Custom", ImportHappened ? "succeeded" : "failed"), 0);
        }
예제 #16
0
        public void PrepareImport_DoImport_CreatesCustomFieldsFromExportResult()
        {
            var customFieldSameLabel = "KeepMeImGood";
            var customFieldLabel     = "TempCustomField";
            var customFieldWrongType = "WrongTypeField";
            var zipFile = Path.GetTempFileName();

            using (new CustomFieldForTest(Cache, customFieldSameLabel, customFieldSameLabel, LexSenseTags.kClassId, StTextTags.kClassId, -1,
                                          CellarPropertyType.OwningAtomic, Guid.Empty))
            {
                using (new CustomFieldForTest(Cache, customFieldLabel, customFieldLabel, LexEntryTags.kClassId, StTextTags.kClassId, -1,
                                              CellarPropertyType.OwningAtomic, Guid.Empty))
                    using (new CustomFieldForTest(Cache, customFieldWrongType, customFieldWrongType, LexEntryTags.kClassId, CmPossibilityTags.kClassId, -1,
                                                  CellarPropertyType.ReferenceAtom, Cache.LangProject.LexDbOA.ComplexEntryTypesOA.Guid))
                    {
                        var importExportDCModel = new DictionaryConfigurationModel
                        {
                            Label        = "importexportConfiguration",
                            Publications = new List <string>(),
                            FilePath     = Path.GetTempPath() + "importexportConfigurationFile.fwdictconfig",
                        };

                        var configurationToExport = importExportDCModel;
                        _pathToConfiguration = configurationToExport.FilePath;
                        const string XmlOpenTagsThruRoot  = @"<?xml version=""1.0"" encoding=""utf-8""?>
			<DictionaryConfiguration name=""Root"" allPublications=""true"" isRootBased=""true"" version=""1"" lastModified=""2014-02-13"">"            ;
                        const string XmlCloseTagsFromRoot = @"</DictionaryConfiguration>";
                        const string XmlTagsHeaword       = @"<ConfigurationItem name=""Main Entry"" isEnabled=""true"" field=""LexEntry"">\r\n\t\t\t\t\t<ConfigurationItem name=""Testword"" nameSuffix=""2b"" before=""["" between="", "" after=""] "" style=""Dictionary-Headword"" isEnabled=""true"" field=""HeadWord"">""\r\n\r\n\r\n\t\t\t\t\t</ConfigurationItem>\r\n\t\t\t\t</ConfigurationItem>\r\n\t\t\t\t<SharedItems/>";
                        const string XmlTagsCustomField   = @" <ConfigurationItem name = ""CustomField1"" isEnabled=""true"" isCustomField=""true"" before="" "" field=""OwningEntry"" subField=""CustomField1"" />";
                        File.WriteAllText(_pathToConfiguration,
                                          XmlOpenTagsThruRoot + XmlTagsHeaword + XmlTagsCustomField + XmlCloseTagsFromRoot);
                        // This export should create the zipfile containing the custom field information (currently in LIFT format)
                        DictionaryConfigurationManagerController.ExportConfiguration(configurationToExport, zipFile, Cache);
                    }             // Destroy two of the custom fields and verify the state
                VerifyCustomFieldPresent(customFieldSameLabel, LexSenseTags.kClassId, StTextTags.kClassId, CellarPropertyType.OwningAtomic);
                VerifyCustomFieldAbsent(customFieldLabel, LexEntryTags.kClassId);
                VerifyCustomFieldAbsent(customFieldWrongType, LexEntryTags.kClassId);
                // Re-introduce one of the fields that was in the export, but with a different type
                using (new CustomFieldForTest(Cache, customFieldWrongType, customFieldWrongType, LexEntryTags.kClassId, StTextTags.kClassId, -1,
                                              CellarPropertyType.OwningAtomic, Guid.Empty))
                {
                    // SUT
                    _controller.PrepareImport(zipFile);
                    // Verify prepare import counted the custom fields
                    CollectionAssert.IsNotEmpty(_controller._customFieldsToImport, "No custom fields found in the lift file by PrepareImport");
                    CollectionAssert.AreEquivalent(_controller._customFieldsToImport, new[] { customFieldLabel, customFieldSameLabel, customFieldWrongType });

                    // Make sure the 'wrongType' custom field has been re-introduced by the test with a different type
                    VerifyCustomFieldPresent(customFieldWrongType, LexEntryTags.kClassId, StTextTags.kClassId);
                    // SUT
                    _controller.DoImport();
                    var configToImport = (DictionaryConfigurationModel)_controller.NewConfigToImport;
                    // Assert that the field which was Enabled or not
                    Assert.IsTrue(configToImport.Parts[1].IsEnabled, "CustomField1 should be enabled");
                    // Assert that the field which was present before the import is still there
                    VerifyCustomFieldPresent(customFieldSameLabel, LexSenseTags.kClassId, StTextTags.kClassId);
                    // Assert that the field which was not present before the import has been added
                    VerifyCustomFieldPresent(customFieldLabel, LexEntryTags.kClassId, StTextTags.kClassId);
                    // Assert that the field which was present with the wrong type is still present.
                    // In the future if we implement overwriting an existing custom field with the data from the export this
                    // is where we would assert the change.
                    VerifyCustomFieldPresent(customFieldWrongType, LexEntryTags.kClassId, StTextTags.kClassId);
                }
            }
        }
예제 #17
0
        public void Setup()
        {
            // Start out with a clean project configuration directory, and with a non-random name so it's easier to examine during testing.
            _projectConfigPath = Path.Combine(Path.GetTempPath(), "Dictionary");
            if (Directory.Exists(_projectConfigPath))
            {
                Directory.Delete(_projectConfigPath, true);
            }
            FileUtils.EnsureDirectoryExists(_projectConfigPath);

            _reversalProjectConfigPath = Path.Combine(Path.GetTempPath(), "ReversalIndex");
            if (Directory.Exists(_reversalProjectConfigPath))
            {
                Directory.Delete(_reversalProjectConfigPath, true);
            }
            FileUtils.EnsureDirectoryExists(_reversalProjectConfigPath);

            _controller = new DictionaryConfigurationImportController(Cache, _projectConfigPath,
                                                                      new List <DictionaryConfigurationModel>());

            _reversalController = new DictionaryConfigurationImportController(Cache, _reversalProjectConfigPath,
                                                                              new List <DictionaryConfigurationModel>());

            // Set up data for import testing.

            _zipFile         = null;
            _reversalZipFile = null;

            // Prepare configuration to export

            var configurationToExport = new DictionaryConfigurationModel
            {
                Label        = configLabel,
                Publications = new List <string> {
                    "Main Dictionary", "unknown pub 1", "unknown pub 2"
                },
                Parts = new List <ConfigurableDictionaryNode> {
                    new ConfigurableDictionaryNode {
                        FieldDescription = "LexEntry"
                    }
                },
                FilePath = Path.GetTempPath() + configFilename
            };

            CssGeneratorTests.PopulateFieldsForTesting(configurationToExport);

            _pathToConfiguration = configurationToExport.FilePath;

            // Create XML file
            configurationToExport.Save();

            // Prepare configuration to export
            var configurationReversalToExport = new DictionaryConfigurationModel
            {
                Label         = reversalConfigLabel,
                WritingSystem = "en",
                Publications  = new List <string> {
                    "Main Dictionary", "unknown pub 1", "unknown pub 2"
                },
                Parts = new List <ConfigurableDictionaryNode> {
                    new ConfigurableDictionaryNode {
                        FieldDescription = "LexEntry"
                    }
                },
                FilePath = Path.GetTempPath() + reversalConfigFilename
            };

            CssGeneratorTests.PopulateFieldsForTesting(configurationReversalToExport);
            _reversalPathToConfiguration = configurationReversalToExport.FilePath;
            configurationReversalToExport.Save();

            // Export a configuration that we know how to import

            _zipFile         = Path.GetTempFileName();
            _reversalZipFile = Path.GetTempFileName() + 1;

            // Add a test style to the cache
            NonUndoableUnitOfWorkHelper.Do(Cache.ActionHandlerAccessor, () =>
            {
                var styleFactory = Cache.ServiceLocator.GetInstance <IStStyleFactory>();

                styleFactory.Create(Cache.LangProject.StylesOC, "Dictionary-Headword",
                                    ContextValues.InternalConfigureView, StructureValues.Undefined, FunctionValues.Line, true, 2, true);
                var testStyle = styleFactory.Create(Cache.LangProject.StylesOC, "TestStyle", ContextValues.InternalConfigureView, StructureValues.Undefined,
                                                    FunctionValues.Line, true, 2, false);
                testStyle.Usage.set_String(Cache.DefaultAnalWs, "Test Style");
                var normalStyle = styleFactory.Create(Cache.LangProject.StylesOC, "Normal", ContextValues.InternalConfigureView, StructureValues.Undefined,
                                                      FunctionValues.Line, false, 2, true);
                var propsBldr = TsPropsBldrClass.Create();
                propsBldr.SetIntPropValues((int)FwTextPropType.ktptBackColor, (int)FwTextPropVar.ktpvDefault, 0x2BACCA);                 // arbitrary color to create para element
                normalStyle.Rules        = propsBldr.GetTextProps();
                var styleWithNamedColors = styleFactory.Create(Cache.LangProject.StylesOC, "Nominal", ContextValues.InternalConfigureView, StructureValues.Undefined,
                                                               FunctionValues.Line, false, 2, false);
                styleWithNamedColors.BasedOnRA = normalStyle;
                propsBldr = TsPropsBldrClass.Create();
                propsBldr.SetIntPropValues((int)FwTextPropType.ktptBackColor, (int)FwTextPropVar.ktpvDefault, NamedRedBGR);
                propsBldr.SetIntPropValues((int)FwTextPropType.ktptForeColor, (int)FwTextPropVar.ktpvDefault, NamedRedBGR);
                styleWithNamedColors.Rules = propsBldr.GetTextProps();
                var styleWithCustomColors  = styleFactory.Create(Cache.LangProject.StylesOC, "Abnormal", ContextValues.InternalConfigureView, StructureValues.Undefined,
                                                                 FunctionValues.Line, false, 2, false);
                styleWithCustomColors.BasedOnRA = normalStyle;
                propsBldr = TsPropsBldrClass.Create();
                propsBldr.SetIntPropValues((int)FwTextPropType.ktptBackColor, (int)FwTextPropVar.ktpvDefault, CustomRedBGR);
                propsBldr.SetIntPropValues((int)FwTextPropType.ktptForeColor, (int)FwTextPropVar.ktpvDefault, CustomRedBGR);
                styleWithCustomColors.Rules = propsBldr.GetTextProps();
                DictionaryConfigurationManagerController.ExportConfiguration(configurationToExport, _zipFile, Cache);
                DictionaryConfigurationManagerController.ExportConfiguration(configurationReversalToExport, _reversalZipFile, Cache);
                Cache.LangProject.StylesOC.Clear();
            });
            Assert.That(File.Exists(_zipFile), "Unit test not set up right");
            Assert.That(new FileInfo(_zipFile).Length, Is.GreaterThan(0), "Unit test not set up right");

            // Clear the configuration away so we can see it gets imported

            File.Delete(_pathToConfiguration);
            Assert.That(!File.Exists(_pathToConfiguration),
                        "Unit test not set up right. Configuration should be out of the way for testing export.");
            Assert.That(_controller._configurations.All(config => config.Label != configLabel),
                        "Unit test not set up right. A config exists with the same label as the config we will import.");
            Assert.That(_controller._configurations.All(config => config.Label != configLabel),
                        "Unit test set up unexpectedly. Such a config should not be registered.");
            File.Delete(_reversalPathToConfiguration);
            Assert.That(!File.Exists(_reversalPathToConfiguration),
                        "Unit test not set up right. Reversal configuration should be out of the way for testing export.");
            Assert.That(_reversalController._configurations.All(config => config.Label != configLabel),
                        "Unit test not set up right. A reversal config exists with the same label as the reversal config we will import.");
            Assert.That(_reversalController._configurations.All(config => config.Label != configLabel),
                        "Unit test set up unexpectedly. Such a reversal config should not be registered.");
        }