コード例 #1
0
 public void Test_Tokenize_ThrowsInvalidFirstToken()
 {
     Assert.Throws(typeof(InvalidDataException), () => DeserializerUtils.Tokenize(new[] {
         "key=value",
         "-second = thing"
     }));
 }
コード例 #2
0
 public void Test_Tokenize_ThrowsRangedCommentNeverClosed()
 {
     Assert.Throws(typeof(InvalidDataException), () => DeserializerUtils.Tokenize(new[] {
         "",
         "ranged/* comment",
         "that is never *\\/",
         "closed \\*/",
         ""
     }));
 }
コード例 #3
0
 public void Test_Tokenize_ThrowsStringNeverClosed()
 {
     Assert.Throws(typeof(InvalidDataException), () => DeserializerUtils.Tokenize(new[] {
         "",
         "\"string\\\"",
         "that \\\" is never",
         "\\\" closed.",
         ""
     }));
 }
        public void Test_Deserialize_SingleFieldType()
        {
            ExampleSingleFieldConfig expectedConfig = new ExampleSingleFieldConfig
            {
                firstField = new ExampleSingleFieldConfig.SingleFieldType1 {
                    secondField = new ExampleSingleFieldConfig.SingleFieldType2 {
                        a = 1, b = 2
                    }
                }
            };
            const string configString = @"
- a = 1
- b = 2
";

            ConfigDeserializer <ExampleSingleFieldConfig> configDeserializer = new ConfigDeserializer <ExampleSingleFieldConfig>(
                DeserializerUtils.Tokenize(new LineReader(new StringReader(configString))).ToList(),
                new ConfigOptions()
                );
            ExampleSingleFieldConfig deserializeResult = configDeserializer.Deserialize();

            Assert.AreEqual(expectedConfig, deserializeResult);
        }
コード例 #5
0
        public void Test_Tokenize_Works()
        {
            List <ConfigNode> tokens = DeserializerUtils.Tokenize(new[] {
                "-key=123",
                "",
                "--deeperKey:\\4\\5\\6\\",
                "",
                "asd//comment",
                "fg/* ranged",
                "",
                "comment */",
                "/abortedComment/ 2/\"3 4\"",
                "--key:",
                "---=----",
                "/\\*escapedComment",
                "\" quoted",
                "",
                "string///*-With-Dash\"\\",
                "/"
            }).ToList();

            List <ConfigNodeVerifier> verifiers = new List <ConfigNodeVerifier> {
                new ConfigNodeVerifier(1, 1, "key", "123"),
                new ConfigNodeVerifier(3, 2, "deeperKey", "456\nasdfg/abortedComment/2/3 4"),
                new ConfigNodeVerifier(10, 2, "key", null),
                new ConfigNodeVerifier(11, 3, null, null),
                new ConfigNodeVerifier(11, 4, null, "/*escapedComment quoted\n\nstring///*-With-Dash\n/"),
            };

            Assert.AreEqual(tokens.Count, verifiers.Count);
            int tokenCount = tokens.Count;

            for (int i = 0; i < tokenCount; i++)
            {
                verifiers[i].Verify(tokens[i]);
            }
        }
コード例 #6
0
        public void Test_Tokenize_SupportsNull()
        {
            List <ConfigNode> tokens = DeserializerUtils.Tokenize(new[] {
                "-value=~",
                "-value2=\\~",
                "-listValue:",
                "--~",
                "-", "-~",
                "--\\~",
                "-dictValue:",
                "--key1=~",
                "--~=~",
                "--\\~=\\~"
            }).ToList();

            List <ConfigNodeVerifier> verifiers = new List <ConfigNodeVerifier> {
                new ConfigNodeVerifier(1, 1, "value", null),
                new ConfigNodeVerifier(2, 1, "value2", "~"),
                new ConfigNodeVerifier(3, 1, "listValue", null),
                new ConfigNodeVerifier(4, 2, null, null),
                new ConfigNodeVerifier(5, 2, null, null),
                new ConfigNodeVerifier(7, 2, null, "~"),
                new ConfigNodeVerifier(8, 1, "dictValue", null),
                new ConfigNodeVerifier(9, 2, "key1", null),
                new ConfigNodeVerifier(10, 2, null, null),
                new ConfigNodeVerifier(11, 2, "~", "~")
            };

            Assert.AreEqual(tokens.Count, verifiers.Count);
            int tokenCount = tokens.Count;

            for (int i = 0; i < tokenCount; i++)
            {
                verifiers[i].Verify(tokens[i]);
            }
        }
        public void Test_Deserialize_ExistingSingleFieldType()
        {
            ExampleSingleFieldConfig targetInstance = new ExampleSingleFieldConfig
            {
                firstField = new ExampleSingleFieldConfig.SingleFieldType1 {
                    secondField = new ExampleSingleFieldConfig.SingleFieldType2 {
                        a = 1, b = 2
                    }
                }
            };
            const string configString = @"
- a = 3
- b = 4
";
            ConfigDeserializer <ExampleSingleFieldConfig> configDeserializer = new ConfigDeserializer <ExampleSingleFieldConfig>(
                DeserializerUtils.Tokenize(new LineReader(new StringReader(configString))).ToList(),
                new ConfigOptions()
                );

            configDeserializer.Deserialize(targetInstance);

            Assert.AreEqual(3, targetInstance.firstField.secondField.a);
            Assert.AreEqual(4, targetInstance.firstField.secondField.b);
        }
コード例 #8
0
 public void Test_Tokenize_ThrowsUnescapedNullCharInString()
 {
     Assert.Throws(typeof(InvalidDataException), () => DeserializerUtils.Tokenize(new[] {
         "-key=va~lue"
     }));
 }
コード例 #9
0
        /// <summary>
        /// Loads a config from a file.
        /// If an instance is provided, the config will be loaded to that instance
        /// otherwise a new instance is created
        /// </summary>
        /// <param name="pathToFile">absolute path to the config file. '/' will be replaced with the DirectorySeparatorChar</param>
        /// <param name="instance">optional - instance of the existing config</param>
        /// <param name="configOptions">use this to configure the de/serializer</param>
        /// <typeparam name="TConfigType">type of the config to load</typeparam>
        /// <returns>instance of the loaded config</returns>
        public static TConfigType LoadConfigFile <TConfigType>(string pathToFile, [CanBeNull] TConfigType instance, ConfigOptions configOptions = null)
        {
            pathToFile = pathToFile.Replace('/', Path.DirectorySeparatorChar);
            if (!File.Exists(pathToFile))
            {
                if (instance == null)
                {
                    instance = (TConfigType)Activator.CreateInstance(typeof(TConfigType));
                }
                IEnumerable <string> lines = new ConfigSerializer(configOptions).Serialize(instance);

                using (StreamWriter writer = new StreamWriter(pathToFile, false)) {
                    foreach (string line in lines)
                    {
                        writer.WriteLine(line);
                    }
                }
                return(instance);
            }

            try {
                using (StreamReader reader = File.OpenText(pathToFile)) {
                    List <string> lines = new List <string>();
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            lines.Add(line);
                        }
                    }
                    ConfigDeserializer <TConfigType> deserializer = new ConfigDeserializer <TConfigType>(DeserializerUtils.Tokenize(lines).ToList(), configOptions);
                    return(instance == null?deserializer.Deserialize() : deserializer.Deserialize(instance));
                }
            } catch (Exception e) {
                Debug.LogError("Failed to load config at path: '" + pathToFile + "', caught exception: " + e);
                return(default);
        public void Test_Deserialize_Implicitly()
        {
            /* Scenarios to check:
             *  - explicit by default, no override
             *    + implicit by default, override both types
             *  - explicit by default, override outer type
             *    + implicit by default, override inner type
             *  - explicit by default, override inner type
             *    + implicit by default, override outer type
             *  - explicit by default, override both types
             *    + implicit by default, no override
             */

            IEnumerable <string> GetLines(bool outerIsExplicit, bool innerIsExplicit)
            {
                if (!outerIsExplicit)
                {
                    yield return("- a = 3");
                }
                yield return("- b = 4");

                if (!outerIsExplicit)
                {
                    yield return("- subClass :");

                    if (!innerIsExplicit)
                    {
                        yield return("-- a = 5");
                    }
                    yield return("-- b = 6");
                }
            }

            void RunTest(bool outerIsExplicit, bool innerIsExplicit, ConfigOptions configOptions)
            {
                ConfigDeserializer <ImplicitConfig> configDeserializer = new ConfigDeserializer <ImplicitConfig>(
                    DeserializerUtils.Tokenize(new LineReader(GetLines(outerIsExplicit, innerIsExplicit))).ToList(),
                    configOptions);
                ImplicitConfig result = configDeserializer.Deserialize();

                if (outerIsExplicit)
                {
                    Assert.AreEqual(0, result.a);
                    Assert.AreEqual(4, result.c);
                    Assert.AreEqual(null, result.subClass);
                }
                else
                {
                    Assert.AreEqual(3, result.a);
                    Assert.AreEqual(4, result.c);
                    Assert.NotNull(result.subClass);
                    Assert.AreEqual(innerIsExplicit ? 0 : 5, result.subClass.a);
                    Assert.AreEqual(6, result.subClass.c);
                }
            }

            Type outerType = typeof(ImplicitConfig);
            Type innerType = typeof(ImplicitConfig.SubClass);

            RunTest(true, true, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Explicit, verifyAllKeysSet = true
            });
            RunTest(true, true, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Implicit, explicitTypes = new List <Type> {
                    outerType, innerType
                }, verifyAllKeysSet = true
            });
            RunTest(false, true, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Explicit, implicitTypes = new List <Type> {
                    outerType
                }, verifyAllKeysSet = true
            });
            RunTest(false, true, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Implicit, explicitTypes = new List <Type> {
                    innerType
                }, verifyAllKeysSet = true
            });
            RunTest(true, false, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Explicit, implicitTypes = new List <Type> {
                    innerType
                }, verifyAllKeysSet = true
            });
            RunTest(true, false, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Implicit, explicitTypes = new List <Type> {
                    outerType
                }, verifyAllKeysSet = true
            });
            RunTest(false, false, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Explicit, implicitTypes = new List <Type> {
                    outerType, innerType
                }, verifyAllKeysSet = true
            });
            RunTest(false, false, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Implicit, verifyAllKeysSet = true
            });
        }
        public void Test_Deserialize_NullDeserializeToDefault()
        {
            ExampleNullableConfig expectedConfig = new ExampleNullableConfig {
                intValue     = 0,
                stringValue  = null,
                stringValue2 = "~",
                intList      = new List <int> {
                    0, 1
                },
                stringList = new List <string> {
                    null, "~"
                },
                subClassList = new List <ExampleNullableConfig.ExampleNullableSubClass> {
                    new ExampleNullableConfig.ExampleNullableSubClass {
                        a = null, b = 0
                    },
                    new ExampleNullableConfig.ExampleNullableSubClass {
                        a = "~", b = 1
                    }
                },
                intDict = new Dictionary <int, int> {
                    { 0, 0 },
                    { 1, 1 }
                },
                stringDict = new Dictionary <string, string> {
                    { "str1", null },
                    { "~", "~" }
                },
                subClassDict = new Dictionary <string, ExampleNullableConfig.ExampleNullableSubClass> {
                    { "str1", new ExampleNullableConfig.ExampleNullableSubClass {
                          a = null, b = 0
                      } },
                    { "~", new ExampleNullableConfig.ExampleNullableSubClass {
                          a = "~", b = 1
                      } }
                }
            };

            const string configString = @"
- intValue = ~
- stringValue = ~
- stringValue2 = ""~""
- intList :
-- ~
-- 1
- stringList :
-- ~
-- ""~""
- subClassList :
-- :
--- a = ~
--- b = ~
-- :
--- a = ""~""
--- b = 1
- intDict :
-- ~ = ~
-- 1 = 1
- stringDict :
-- str1 = ~
-- ""~"" = ""~""
- subClassDict :
-- str1 :
--- a = ~
--- b = ~
-- ""~"" :
--- a = ""~""
--- b = 1
";

            ConfigDeserializer <ExampleNullableConfig> configDeserializer = new ConfigDeserializer <ExampleNullableConfig>(
                DeserializerUtils.Tokenize(new LineReader(new StringReader(configString))).ToList(),
                new ConfigOptions()
                );
            ExampleNullableConfig deserializeResult = configDeserializer.Deserialize();

            Assert.AreEqual(expectedConfig, deserializeResult);
        }