diff options
| author | Elena ``of Valhalla'' Grandi <valhalla@trueelena.org> | 2021-03-19 09:34:22 +0100 | 
|---|---|---|
| committer | Elena ``of Valhalla'' Grandi <valhalla@trueelena.org> | 2021-03-19 09:34:22 +0100 | 
| commit | 897bd5e601f9a602b2e0aef592780c63d3730048 (patch) | |
| tree | 9e3f9b988879ecb461d9a510dfc6cf2bbb95b84c | |
| parent | 2def416dba68521b9387fc98b20ec99cea6a2efa (diff) | |
Fix converting multiline and long strings to yaml
| -rw-r--r-- | lesana/templating.py | 12 | ||||
| -rw-r--r-- | tests/test_templating.py | 18 | 
2 files changed, 27 insertions, 3 deletions
| diff --git a/lesana/templating.py b/lesana/templating.py index 375a6f0..8ff9fcb 100644 --- a/lesana/templating.py +++ b/lesana/templating.py @@ -2,6 +2,7 @@  Custom jinja2 filters and other templating helpers  """  import decimal +import io  import jinja2  import ruamel.yaml @@ -22,6 +23,13 @@ def to_yaml(data):      """      Return the yaml representation of data.      """ -    if isinstance(data, decimal.Decimal): +    if isinstance(data, str): +        if len(data) > 75 or "\n" in data: +            data = ruamel.yaml.scalarstring.LiteralScalarString(data + "\n") +    elif isinstance(data, decimal.Decimal):          data = str(data) -    return ruamel.yaml.dump(data).strip('...\n').strip() +    yaml = ruamel.yaml.YAML() +    s_io = io.StringIO() +    yaml.dump(data, s_io) +    res = s_io.getvalue().strip('...\n').strip() +    return res diff --git a/tests/test_templating.py b/tests/test_templating.py index 33889ae..aadcf66 100644 --- a/tests/test_templating.py +++ b/tests/test_templating.py @@ -28,7 +28,16 @@ class testFilters(unittest.TestCase):          """          res = templating.to_yaml(s)          self.assertIsInstance(res, str) -        self.assertIn('"', res) +        self.assertTrue(res.startswith('|')) +        self.assertIn('\n', res) + +        s = """ +        short +        multiline +        """ +        res = templating.to_yaml(s) +        self.assertIsInstance(res, str) +        self.assertTrue(res.startswith('|'))          self.assertIn('\n', res)          res = templating.to_yaml(10) @@ -37,6 +46,13 @@ class testFilters(unittest.TestCase):          res = templating.to_yaml(decimal.Decimal('10.1'))          self.assertEqual(res, "'10.1'") +        s = "A very long line, but one that has no new lines " \ +            + "even if it is definitely longer than a standard " \ +            + "80 columns line" +        res = templating.to_yaml(s) +        self.assertTrue(res.startswith("|\n")) +        self.assertNotIn('\n', res.lstrip("|\n")) +  if __name__ == '__main__':      unittest.main() | 
