Example #1
0
        public void Write_WithDictionary_WritesCorrectFileContent()
        {
            // Arrange
            using (var filename = TestFileName.Create("test", ".toml"))
            {
                // Act
                var data = new Dictionary <string, object>()
                {
                    { "EnableDebug", false },
                    { "Server", new Dictionary <string, object>()
                      {
                          { "Timeout", TimeSpan.FromMinutes(2) }
                      } },
                    { "Client", new Dictionary <string, object>()
                      {
                          { "ServerAddress", "http://*****:*****@"
EnableDebug = false
[Server]
Timeout = 2m
[Client]
ServerAddress = ""http://localhost:8082""");
            }
        }
Example #2
0
        public void CommentsNotLostWhenPorpertyValueIsSet()
        {
            // Arrange
            var expectedChanged = @"#Some comment
b = false

#Comment on nested table
[a]
#Comment on C
c = """"
";

            using var filename = TestFileName.Create($"settings", Toml.FileExtension);
            var config = Config.CreateAs()
                         .MappedToType(() => new Configuration())
                         .StoredAs(builder => builder.File(filename))
                         .Initialize();

            var readValue = File.ReadAllText(filename);

            readValue.ShouldBeNormalizedEqualTo(InitialToml);

            // Act
            config.Set(c => c.b, false);

            // Assert
            readValue = File.ReadAllText(filename);
            readValue.ShouldBeNormalizedEqualTo(expectedChanged);
        }
Example #3
0
        public void WasChangedExternally_WhenFileWasModified_ReturnsTrueUntilLoadIsPerformed()
        {
            using (var file = TestFileName.Create("x", Toml.FileExtension))
            {
                // Arrange
                File.WriteAllText(file, "x=0");
                var cfg = new FileConfigStore(TomlSettings.DefaultInstance, file);
                cfg.Load();
                using (var sw = File.AppendText(file))
                {
                    sw.WriteLine();
                    sw.WriteLine("y=1");
                }

                // Act
                var r1 = cfg.WasChangedExternally();
                var r2 = cfg.WasChangedExternally();
                cfg.Load();
                var r3 = cfg.WasChangedExternally();

                // Assert
                r1.Should().Be(true);
                r2.Should().Be(true);
                r3.Should().Be(false);
            }
        }
Example #4
0
        public void SetConfigProperty_WhenMultiLevelTypeHasConverter_WritesTheSubPropertyCorrectly()
        {
            using (var fn = TestFileName.Create("file", Toml.FileExtension))
            {
                // Arrange
                var tmlCfg = TomlSettings.Create(c => c
                                                 .ConfigureType <MultiTableConverterObject>(tc => tc
                                                                                            .WithConversionFor <TomlString>(conv => conv
                                                                                                                            .ToToml(o => o.ToString())
                                                                                                                            .FromToml(s => MultiTableConverterObject.Parse(s.Value)))));

                var cfg = Config.CreateAs()
                          .MappedToType(() => new Root())
                          .UseTomlConfiguration(tmlCfg)
                          .StoredAs(s => s.File(fn))
                          .Initialize();

                // Act
                cfg.Set(c => c.ConvertedItem.UnitItem.Unit, "B");

                // Assert
                var tbl = Toml.ReadFile <Root>(fn, tmlCfg);
                tbl.ConvertedItem.UnitItem.Unit.Should().Be("B");
            }
        }
Example #5
0
        public void SetProperty_InSpecializedScopeForConvertedMultiLevelType_WritesItBackToSpecScope()
        {
            using (var main = TestFileName.Create("main", Toml.FileExtension))
                using (var spec = TestFileName.Create("spec", Toml.FileExtension))
                {
                    // Arrange
                    var tmlCfg = TomlSettings.Create(c => c
                                                     .ConfigureType <MultiTableConverterObject>(tc => tc
                                                                                                .WithConversionFor <TomlString>(conv => conv
                                                                                                                                .ToToml(o => o.ToString())
                                                                                                                                .FromToml(s => MultiTableConverterObject.Parse(s.Value)))));

                    Toml.WriteFile(Toml.Create(), main, tmlCfg);;
                    Toml.WriteFile(Toml.Create(CreateWithUnitItem(2.0, "X")), spec, tmlCfg);

                    var cfg = Config.CreateAs()
                              .MappedToType(() => new Root())
                              .UseTomlConfiguration(tmlCfg)
                              .StoredAs(s => s
                                        .File(main).MergeWith(
                                            s.File(spec)))
                              .Initialize();

                    // Act
                    cfg.Set(c => c.ConvertedItem.UnitItem.Unit, "EX");


                    // Assert
                    var root = Toml.ReadFile <Root>(spec, tmlCfg);
                    root.ConvertedItem.UnitItem.Unit.Should().Be("EX");
                }
        }
Example #6
0
        public void Write_WithInlineTableProperty_WritesThatTableAsInlineTable()
        {
            using (var file = TestFileName.Create("Input", ".toml"))
            {
                // Arrange
                const string expected = @"UserItems = { X = true, Y = false }
";
                const string input    = "UserItems = { 'X' = false, 'Y' = true }";
                File.WriteAllText(file, input);
                var toWrite = new Cfg.Items()
                {
                    { "X", true },
                    { "Y", false }
                };

                // Act
                var cfg = Config.CreateAs()
                          .MappedToType(() => new Cfg())
                          .StoredAs(store => store.File(file))
                          .Initialize();
                cfg.Set(c => c.UserItems, toWrite);

                // Assert
                var f = File.ReadAllText(file);
                f.ShouldBeNormalizedEqualTo(expected);
            }
        }
Example #7
0
        public void ReadConfigPropertyAfterInit_WhenMultiLevelTypeHasConverterInSpecializedScope_ReadsItemFromSpecScope()
        {
            using (var main = TestFileName.Create("main", Toml.FileExtension))
                using (var spec = TestFileName.Create("spec", Toml.FileExtension))
                {
                    // Arrange
                    var tmlCfg = TomlSettings.Create(c => c
                                                     .ConfigureType <MultiTableConverterObject>(tc => tc
                                                                                                .WithConversionFor <TomlString>(conv => conv
                                                                                                                                .ToToml(o => o.ToString())
                                                                                                                                .FromToml(s => MultiTableConverterObject.Parse(s.Value)))));

                    Toml.WriteFile(Toml.Create(), main, tmlCfg);;
                    Toml.WriteFile(Toml.Create(CreateWithUnitItem(2.0, "X")), spec, tmlCfg);

                    var cfg = Config.CreateAs()
                              .MappedToType(() => new Root())
                              .UseTomlConfiguration(tmlCfg)
                              .StoredAs(s =>
                                        s.File(main).AccessedBySource("main", out var _).MergeWith(
                                            s.File(spec).AccessedBySource("spec", out var _)))
                              .Initialize();

                    // Act
                    var val = cfg.Get(c => c.ConvertedItem.UnitItem.Unit);
                    var src = cfg.GetSource(c => c.ConvertedItem.UnitItem.Unit);

                    // Assert
                    val.Should().Be("X");
                    src.Name.Should().Be("spec");
                }
        }
Example #8
0
        public void Foo()
        {
            using (var fn = TestFileName.Create("input", ".toml"))
            {
                // Arrange
                const string tml = @"
[User]

[User.Items]
first = true
second = false
third = true
";
                File.WriteAllText(fn, tml);

                // Act
                var cfg = Config.CreateAs()
                          .MappedToType(() => new AppSettings())
                          .StoredAs(store => store.File(fn))
                          .Initialize();
                var u = Toml.ReadString <AppSettings>(tml);

                // Assert
                cfg.Get(c => c.User.Items).Count.Should().Be(3);
            }
        }
Example #9
0
        public void LoadConfig_WhenConfigContainsTableArrays_LoadsThatConfigCorrectly_()
        {
            using (var fn = TestFileName.Create("productinfo", ".toml"))
            {
                File.WriteAllText(fn, @"
[info]
[[info.product]]
name = ""product1""
number = 10000
[[info.product]]
name = ""product2""
number = 10001
");

                var config = Config.CreateAs()
                             .MappedToType(() => new ProductInfo())
                             .StoredAs(store => store.File(fn))
                             .Initialize()
                             .Get(_ => _);

                config.info.product.Length.Should().Be(2);
                config.info.product[0].name.Should().Be("product1");
                config.info.product[1].name.Should().Be("product2");
            }
        }
Example #10
0
        public void WhenUpdatingRowWithNewValues_WrittenTomlHasTheseNewRowValues()
        {
            using var machine = TestFileName.Create("machine", ".toml");

            // Arrange
            const string machineText = @"
[Tbl]
a = 1
d = ""D""
e = [""b"", ""c""]";

            File.WriteAllText(machine, machineText);

            var cfg = Config.CreateAs()
                      .MappedToType(() => new DictConfig())
                      .StoredAs(store => store.File(machine))
                      .Initialize();

            // Act
            cfg.Set(c => c.Tbl["e"], new string[] { "x", "y" });

            // Assert
            File.ReadAllText(machine).Should().BeAfterTransforms(StringTransformForComparison, @"
[Tbl]
a = 1
d = ""D""
e = [""x"", ""y""]");
        }
Example #11
0
        public void WhenUpdatingValueOfLoadedGenericDict_TheWrittentomlContainsTheUpdatedValue()
        {
            using var machine = TestFileName.Create("machine", ".toml");
            using var user    = TestFileName.Create("user", ".toml");

            // Arrange
            const string machineText = @"[Tbl]
x = 1";
            const string userText    = @"[Tbl]
x = 2";

            File.WriteAllText(machine, machineText);
            File.WriteAllText(user, userText);

            // Act
            IConfigSource src = null;
            var           cfg = Config.CreateAs()
                                .MappedToType(() => new DictConfig())
                                .StoredAs(store => store.File(machine)
                                          .MergeWith(store.File(user).AccessedBySource("user", out src)))
                                .Initialize();

            var tbl = cfg.Get(c => c.Tbl);

            tbl["x"] = 4;
            cfg.Set(c => c.Tbl, tbl, src);

            // Assert
            File.ReadAllText(user).ShouldBeSemanticallyEquivalentTo(@"[Tbl]
x = 4");
        }
Example #12
0
        public void Write_WithTomlTable_WritesCorrectFileContent()
        {
            // Arrange
            using (var filename = TestFileName.Create("test", ".toml"))
            {
                // Act
                var server = Toml.Create();
                server.Add("Timeout", TimeSpan.FromMinutes(2));

                var client = Toml.Create();
                client.Add("ServerAddress", "http://*****:*****@"
EnableDebug = false
[Server]
Timeout = 2m
[Client]
ServerAddress = ""http://localhost:8082""");
            }
        }
Example #13
0
        private MoneyScenario(string test)
        {
            this.FilePath = TestFileName.Create("money", Toml.FileExtension, test);

            this.TmlConfig = TomlSettings.Create(cfg => cfg
                                                 .ConfigureType <Money>(typeConfig => typeConfig
                                                                        .WithConversionFor <TomlString>(conversion => conversion
                                                                                                        .ToToml(m => m.ToString())
                                                                                                        .FromToml(s => Money.Parse(s.Value)))));
        }
Example #14
0
 public void XmlFileIsNotZipFile()
 {
     TestFileName = _testXmlFileName;
     TestFileName.CreateFileFromEmbeddedStream(TestFilepath, EmbeddedTestFilePath);
     using (_zipbomb = new ZipBomb(TestFilepath, 5))
     {
         _zipbomb.Inspect();
         _zipbomb.CanDispose = true;
     };
     Assert.IsFalse(_zipbomb.IsZipFile);
     Assert.IsFalse(_zipbomb.IsZipBomb);
 }
Example #15
0
 public void FileIsZipBombPassWrongPasswordShouldThrowException()
 {
     TestFileName = TestZipBombFileName;
     TestFileName.CreateFileFromEmbeddedStream(TestFilepath, EmbeddedTestFilePath);
     using (_zipbomb = new ZipBomb(TestFilepath, 5, "---", null, true))
     {
         _zipbomb.ThrowException = true;
         _zipbomb.Inspect();
         _zipbomb.CanDispose = true;
     };
     Assert.IsTrue(_zipbomb.IsZipFile);
 }
Example #16
0
 public void SetThreasholdTooLargeShouldThrowException()
 {
     TestFileName = TestZipBombFileName;
     TestFileName.CreateFileFromEmbeddedStream(TestFilepath, EmbeddedTestFilePath);
     using (_zipbomb = new ZipBomb(TestFilepath, 2001))
     {
         _zipbomb.ThrowException = true;
         _zipbomb.Inspect();
         _zipbomb.CanDispose = true;
     };
     Assert.IsTrue(_zipbomb.IsZipFile);
 }
Example #17
0
 public void RecurseZipWalkTest()
 {
     TestFileName = SourceZipfileName;
     TestFileName.CreateFileFromEmbeddedStream(TestFilepath, EmbeddedTestFilePath);
     using (var zipWalker = new ZipWalker(this,
                                          new[] { TestFilepath },
                                          2))
     {
         zipWalker.Inspect();
         Assert.AreEqual(zipWalker.CurrentDeepLevel, 1);
         zipWalker.CanDispose = true;//clear the results
     }
 }
Example #18
0
 public void RecurseUnZipMultipeArchiveTypesTest()
 {
     TestFileName = TestZipFileName;
     TestFileName.CreateFileFromEmbeddedStream(TestFilepath, EmbeddedTestFilePath);
     using (var zipWalker = new ZipWalker(this,
                                          new[] { TestFilepath },
                                          2))
     {
         zipWalker.Inspect();
         Assert.AreEqual(zipWalker.CurrentDeepLevel, 1);
         zipWalker.CanDispose = true;
     }
 }
Example #19
0
 public void FileIsZipBomb()
 {
     TestFileName = TestZipBombFileName;
     TestFileName.CreateFileFromEmbeddedStream(TestFilepath, EmbeddedTestFilePath);
     using (_zipbomb = new ZipBomb(TestFilepath,
                                   3,
                                   GlobalDefinitions.DefaultInfectedPassword))
     {
         _zipbomb.Inspect();
         _zipbomb.CanDispose = true;
     };
     Assert.IsTrue(_zipbomb.IsZipFile);
     Assert.IsTrue(_zipbomb.IsZipBomb);
 }
Example #20
0
 public void UnpackedSizeAcceptable()
 {
     TestFileName = TestZipBombFileName;
     TestFileName.CreateFileFromEmbeddedStream(TestFilepath, EmbeddedTestFilePath);
     using (_zipbomb = new ZipBomb(TestFilepath,
                                   5,
                                   null,
                                   600000))
     {
         _zipbomb.Inspect();
         _zipbomb.CanDispose = true;
     };
     Assert.IsTrue(_zipbomb.IsZipFile);
     Assert.IsFalse(_zipbomb.IsUnpackedSizeTooLarge);
 }
Example #21
0
 public void SizeSetTooSmalTheNormaZipFileShowAsZipbomb()
 {
     TestFileName = TestZipFileName;
     TestFileName.CreateFileFromEmbeddedStream(TestFilepath, EmbeddedTestFilePath);
     using (_zipbomb = new ZipBomb(TestFilepath,
                                   5,
                                   GlobalDefinitions.DefaultInfectedPassword,
                                   100000))
     {
         _zipbomb.Inspect();
         _zipbomb.CanDispose = true;
     };
     Assert.IsTrue(_zipbomb.IsZipFile);
     Assert.IsTrue(_zipbomb.IsZipBomb);
     Assert.IsTrue(_zipbomb.IsUnpackedSizeTooLarge);
 }
Example #22
0
        public void VerifyIssue25_UnitializedDateTime_DoesNotCrasComaInit()
        {
            using (var fn = TestFileName.Create("thecfg", ".toml"))
            {
                // Act
                Action a = () => Config.CreateAs()
                           .MappedToType(() => new TheCfg())
                           .StoredAs(store => store.File(fn))
                           .Initialize();

                // Assert
                a.ShouldNotThrow <ArgumentOutOfRangeException>(because: "Nett's converters should be able to handle the " +
                                                               "following case internally in any time zone: var off = new DateTimeOfffset(DateTime.MinValue) which happens " +
                                                               "when the DateTime field of a class is not initialized with an explicit value.");
            }
        }
Example #23
0
        public void WasChangedExternally_WhenThereWasNoModification_ReturnsFalse()
        {
            using (var file = TestFileName.Create("x", Toml.FileExtension))
            {
                // Arrange
                File.WriteAllText(file, "x=0");
                var cfg = new FileConfigStore(TomlSettings.DefaultInstance, file);
                cfg.Load();

                // Act
                var r = cfg.WasChangedExternally();

                // Assert
                r.Should().Be(false);
            }
        }
Example #24
0
        public void WasChangedExternally_WhenFileWasNotLoadedAtLeastOnce_WillAlwaysReturnTrue()
        {
            using (var file = TestFileName.Create("x", Toml.FileExtension))
            {
                // Arrange
                File.WriteAllText(file, "x=0");
                var cfg = new FileConfigStore(TomlSettings.DefaultInstance, file);

                // Act
                var r1 = cfg.WasChangedExternally();
                var r2 = cfg.WasChangedExternally();

                // Assert
                r1.Should().Be(true);
                r2.Should().Be(true);
            }
        }
        public void Save_UpdatesInMemoryConfigSoNextLoadWillDeliverThatConfig()
        {
            using (var fn = TestFileName.Create("file", Toml.FileExtension))
            {
                // Arrange
                var fc = new FileConfigStore(TomlSettings.DefaultInstance, fn);
                var oc = new ConfigStoreWithSource(new ConfigSource(fn), fc);
                File.WriteAllText(fn, "X = 1");
                oc.Load(); // At least one load needs to be done, otherwise a load will be done because not any data was loaded yet

                // Act
                oc.Save(Toml.ReadString("X = 2"));

                // Assert
                var readBack = oc.Load();
                ((TomlInt)readBack["X"]).Value.Should().Be(2);
            }
        }
Example #26
0
        public void Read_AsTomlTable_ReadsTableCorrectly()
        {
            // Arrange
            using (var filename = TestFileName.Create("test", ".toml"))
            {
                File.WriteAllText(filename, exp);

                // Act
                var toml = Toml.ReadFile(filename);
                Console.WriteLine("EnableDebug: " + toml.Get <bool>("EnableDebug"));
                Console.WriteLine("Timeout: " + toml.Get <TomlTable>("Server").Get <TimeSpan>("Timeout"));
                Console.WriteLine("ServerAddress: " + toml.Get <TomlTable>("Client").Get <string>("ServerAddress"));

                // Assert
                toml.Get <bool>("EnableDebug").Should().Be(true);
                toml.Get <TomlTable>("Server").Get <TimeSpan>("Timeout").Should().Be(TimeSpan.FromMinutes(1));
                toml.Get <TomlTable>("Client").Get <string>("ServerAddress").Should().Be("http://127.0.0.1:8080");
            }
        }
Example #27
0
        public void Write_WithCustomObject_WritesCorrectFileContent()
        {
            // Arrange
            using (var filename = TestFileName.Create("test", ".toml"))
            {
                // Act
                var obj = new Configuration();
                Toml.WriteFile(obj, filename);

                // Assert
                File.ReadAllText(filename).ShouldBeSemanticallyEquivalentTo(
                    @"
EnableDebug = false
[Server]
Timeout = 2m
[Client]
ServerAddress = ""http://localhost:8082""");
            }
        }
Example #28
0
        public void Read_AsCustomObject_ReadsTableCorrectly()
        {
            // Arrange
            using (var filename = TestFileName.Create("test", ".toml"))
            {
                File.WriteAllText(filename, exp);

                // Act
                var cust = Toml.ReadFile <Configuration>(filename);

                Console.WriteLine("EnableDebug: " + cust.EnableDebug);
                Console.WriteLine("Timeout: " + cust.Server.Timeout);
                Console.WriteLine("ServerAddress: " + cust.Client.ServerAddress);

                // Assert
                cust.EnableDebug.Should().Be(true);
                cust.Server.Timeout.Should().Be(TimeSpan.FromMinutes(1));
                cust.Client.ServerAddress.Should().Be("http://127.0.0.1:8080");
            }
        }
Example #29
0
        public void MultiThreadMimic()
        {
            TestFileName = TestZipBombFileName;
            TestFileName.CreateFileFromEmbeddedStream(TestFilepath, EmbeddedTestFilePath);
            var tasklist    = new List <Task>();
            var sourcefiles = new List <string>();

            Parallel.Invoke(new ParallelOptions {
                MaxDegreeOfParallelism = 10
            }, () =>
            {
                tasklist.Add(Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 2; ++i)
                    {
                        var sourcefileName = string.Format(@"{0}_{1}.zip", Path.GetFullPath(TestFilepath).Replace(@".zip", string.Empty), i);
                        File.Copy(TestFilepath, sourcefileName, true);
                        sourcefiles.Add(sourcefileName);
                        using (var zipbomb = new ZipBomb(TestFilepath,
                                                         3,
                                                         GlobalDefinitions.DefaultInfectedPassword))
                        {
                            zipbomb.Inspect();
                            Assert.IsTrue(zipbomb.IsZipFile);
                            Assert.IsTrue(zipbomb.IsZipBomb);
                            zipbomb.CanDispose = true;
                        };
                    }
                }
                                                   ));
            });
            Task.WaitAll(tasklist.ToArray(), new TimeSpan(0, 0, 100));

            sourcefiles.ForEach(x =>
            {
                if (File.Exists(x))
                {
                    File.Delete(x);
                }
            });
        }
Example #30
0
        public void LoadMergedConfig_LocalSettingOverwritesMoreGlobalSetting()
        {
            using (var global = TestFileName.Create("global", Toml.FileExtension))
                using (var local = TestFileName.Create("local", Toml.FileExtension))
                {
                    // Arrange
                    File.WriteAllText(global, Config1);
                    File.WriteAllText(local, Config1A);

                    // Act
                    var c = Config.CreateAs()
                            .MappedToType(() => new SingleLevelConfig())
                            .StoredAs(store =>
                                      store.File(global).MergeWith(
                                          store.File(local)))
                            .Initialize();

                    // Assert
                    c.Get(r => r.IntValue).Equals(2);
                }
        }