public void IniFileWriteNoChangeRevert()
        {
            // Read the ini file.
            string        originalContent            = File.ReadAllText(TestUtil.GetLocalFile("write-test.ini"));
            IniFileReader reader                     = new TestIniFileReader(originalContent);
            Dictionary <string, string> originalData = reader.ReadData();

            // Update all values.
            Dictionary <string, string> updatedData =
                originalData.ToDictionary(kv => kv.Key, kv => $"{kv.Value}-{kv.Value}".ToUpper());

            // Write the new data.
            IniFileWriter writer1        = new TestIniFileWriter(originalContent);
            string        updatedContent = writer1.Write(updatedData).Result;

            // The content should have changed
            Assert.NotEqual(originalContent, updatedContent);

            // Write back the original data
            IniFileWriter writer2         = new TestIniFileWriter(updatedContent);
            string        revertedContent = writer2.Write(originalData).Result;

            // Result should be the same - however, the indentation on some multi-line values are not preserved.
            // Remove these large indentations before comparing.
            string fixedOriginal = Regex.Replace(originalContent, " {9,}", "    ", RegexOptions.Multiline);

            Assert.Equal(fixedOriginal, revertedContent);
        }
        public void IniFileWriteNoChange()
        {
            // Read the ini file
            string        content            = File.ReadAllText(TestUtil.GetLocalFile("write-test.ini"));
            IniFileReader reader             = new TestIniFileReader(content);
            Dictionary <string, string> data = reader.ReadData();

            // Write back the same data
            IniFileWriter writer1     = new TestIniFileWriter(content);
            string        writtenData = writer1.Write(data).Result;

            // Result should be the same
            Assert.Equal(content, writtenData);
        }
        public void DoReadTest(string eol)
        {
            string iniFile = TestUtil.GetLocalFile("read-test.ini");

            Dictionary <string, string> expected = new Dictionary <string, string>();

            Regex getExpected = new Regex("^#@ *{?(?<key>[^:]*)}?:{?(?<value>.*?)}?$");

            // read-test.ini contains the expected data, on lines that start with '#@'.
            // Extract this json from the file.
            foreach (string line in File.ReadAllLines(iniFile))
            {
                if (line.StartsWith("#@"))
                {
                    Match match = getExpected.Match(line);
                    expected[match.Groups["key"].Value] = match.Groups["value"].Value.Replace("\\n", eol);
                }
            }

            // Read the ini data from the file
            IniFileReader iniReader = new TestIniFileReader(ReplaceEol(File.ReadAllText(iniFile), eol));

            Dictionary <string, string> data = iniReader.ReadData();

            // Compare the results
            foreach ((string key, string value) in expected)
            {
                if (data.TryGetValue(key, out string actualValue))
                {
                    if (actualValue != value)
                    {
                        this.output.WriteLine($"{key}: {value} != {actualValue}");
                    }
                    Assert.Equal(value, actualValue);
                }
                else
                {
                    this.output.WriteLine($"{key}: {value} (not found)");
                    Assert.True(true);
                }
            }

            List <string> wrong = data.Keys.Except(expected.Keys).ToList();

            wrong.ForEach(key => this.output.WriteLine($"{key}: {data[key]} (unexpected)"));

            Assert.Equal(expected.Count, data.Count);
        }
Exemple #4
0
        public async Task IniGet()
        {
            TestIniFileReader reader = new TestIniFileReader()
            {
                ContentOverride = TestContent
            };

            ServiceCollection serviceCollection = TestUtil.GetTestServices();

            serviceCollection.ReplaceTransient <IniFileReader>(s => reader);
            IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();

            Solutions sr = Solutions.FromFile(serviceProvider, TestUtil.GetLocalFile("..\\test-solutions.json5"));

            // Capture the preferences.
            Solution            solution            = sr.GetSolution("ini");
            SolutionPreferences solutionPreferences = new SolutionPreferences();

            await solution.Capture(solutionPreferences);

            // The correct file path is used
            Assert.Equal("test-file.ini", reader.FilePath);

            Dictionary <string, string> expect = TestUtil.StringToDictionary(@"
settingA=valueOneA
settingB=valueTwoA
settingC=valueThreeA
settingD=valueOneB
settingE=valueTwoB
settingF=valueT1
settingG=valueOneParent
settingH=valueTwoParent
settingI=valueT2
settingJ=valueOneChild
settingK=valueTwoChild
settingL=valueT3
");

            Dictionary <string, string> actual =
                solutionPreferences.Values.ToDictionary(kv => kv.Key, kv => kv.Value?.ToString() ?? string.Empty);

            // Check the correct values are read.
            TestUtil.CompareDictionaries(expect, actual, this.output.WriteLine);
        }
Exemple #5
0
        public async Task IniSet()
        {
            TestIniFileWriter writer = new TestIniFileWriter()
            {
                ContentOverride = TestUtil.ReadLocalFile("handler-test.ini")
            };
            TestIniFileReader reader = new TestIniFileReader()
            {
                ContentOverride = TestUtil.ReadLocalFile("handler-test.ini")
            };

            ServiceProvider serviceProvider = TestUtil.GetTestServices()
                                              .ReplaceTransient <IniFileWriter>(s => writer)
                                              .ReplaceTransient <IniFileReader>(s => reader)
                                              .BuildServiceProvider();

            Solutions sr = Solutions.FromFile(serviceProvider, TestUtil.GetLocalFile("..\\test-solutions.json5"));

            Solution            solution            = sr.GetSolution("ini");
            SolutionPreferences solutionPreferences = new SolutionPreferences();

            // Set the new values
            Dictionary <string, string> newValues = TestUtil.StringToDictionary(@"
settingA=value-UPDATED-OneA
settingC=value-UPDATED-ThreeA
settingD=value-UPDATED-OneB
settingF=value-UPDATED-T1
settingG=value-UPDATED-OneParent
settingI=value-UPDATED-T2
settingJ=value-UPDATED-OneChild
settingL=value-UPDATED-T3
");

            foreach ((string?key, string?value) in newValues)
            {
                solutionPreferences.Values.Add(key, value);
            }

            // Apply the preferences.
            await solution.Apply(solutionPreferences);

            // Check the correct file path is used
            Assert.Equal("test-file.ini", writer.FilePath);
            // Check the file was saved
            Assert.True(writer.Saved, "INI file was saved");

            string iniContent = writer.Result !;

            // Check the new content is correct.
            string expected = @"ignoreA=AA
key1=value-UPDATED-OneA
key2=valueTwoA
key3=value-UPDATED-ThreeA
[test1]
ignoreB=BB
key1=value-UPDATED-OneB
key2=valueTwoB
keyT1=value-UPDATED-T1
[test2]
ignoreC=CC
key1=value-UPDATED-OneParent
key2=valueTwoParent
keyT2=value-UPDATED-T2
[[test3]]
ignoreD=DD
key1=value-UPDATED-OneChild
key2=valueTwoChild
keyT3=value-UPDATED-T3
";

            //File.WriteAllText(TestUtil.GetLocalFile("out.ini"), iniContent);
            Assert.Equal(expected, iniContent);

            return;

            ;
        }
        private static void DoWriteTest(string eol)
        {
            // Read the ini file.
            string originalContent =
                ReplaceEol(File.ReadAllText(TestUtil.GetLocalFile("write-test.ini")), eol);

            IniFileReader reader = new TestIniFileReader(originalContent);
            Dictionary <string, string> originalData = reader.ReadData();

            Regex getKey = new Regex(@"^(?:.*\.)?([^.]+)$");

            // Update all values. ("key=value" => "key=abc key xyz")
            Dictionary <string, string> updatedData =
                originalData
                .Select(kv =>
            {
                string key      = getKey.Replace(kv.Key, "$1");
                string newValue = "abc " + key + " xyz";
                if (key.Contains("remove_"))
                {
                    newValue = null;
                }
                else if (key.StartsWith("ml_"))
                {
                    if (!int.TryParse(key[3].ToString(), out int num))
                    {
                        num = 3;
                    }

                    List <string> lines = new List <string>();
                    for (int i = 0; i < num; i++)
                    {
                        lines.Add($"{newValue} line{i}");
                    }

                    newValue = string.Join(eol, lines);
                }

                return(new KeyValuePair <string, string>(kv.Key, newValue));
            }).ToDictionary(kv => kv.Key, kv => kv.Value);

            // Make some specific changes
            updatedData["empty_me"]   = "";
            updatedData["null_me"]    = null;
            updatedData["number_me1"] = "42";
            updatedData["number_me2"] = "12345";
            updatedData["true_me1"]   = "true";
            updatedData["true_me2"]   = "true";

            // Add some new ones
            updatedData["new_empty"]  = "";
            updatedData["new_null"]   = null;
            updatedData["new_number"] = "42";
            updatedData["new_true"]   = "true";
            updatedData["newKey1"]    = "new value";

            // Change within sections
            updatedData["section1.newKey1"] = "new value 1, in section1";
            updatedData["section1.newKey2"] = "new value 2";

            // Add new sections
            updatedData["newSection1.newKey1"] = "new value 1, in new section 1";
            updatedData["newSection1.newKey3"] = "new value 3";

            updatedData["newSection2.newKey1"] = "new value 1, in new section 2";
            updatedData["newSection2.newKey4"] = "new value 4";

            updatedData["newSection2.newSubSection.newKey1"] = "new value 1, in new sub section";
            updatedData["newSection2.newSubSection.newKey5"] = "new value 5";

            // Write the new data
            IniFileWriter writer =
                new TestIniFileWriter(ReplaceEol(File.ReadAllText(TestUtil.GetLocalFile("write-test.ini")), eol));
            string updatedContent  = writer.Write(updatedData).Result;
            string expectedContent = ReplaceEol(File.ReadAllText(TestUtil.GetLocalFile("write-test.expect.ini")), eol);

            Assert.Equal(expectedContent, updatedContent);
        }