From b41e297728c1344bb20b59c32bfd95a2aa1a8d4d Mon Sep 17 00:00:00 2001 From: Nikolay Mahotkin Date: Mon, 19 Oct 2015 12:14:32 +0300 Subject: [PATCH] Adding 'json_pp' function in YAQL * Added new function called 'json_pp' for pretty output json objects using YAQL. It can be used, for example, for sending email containing some dicts or lists. * This function also fixes escaped new-line symbols Change-Id: I8a7d432a957423b832935f46bb04ddd4505258c7 --- mistral/tests/unit/test_expressions.py | 18 ++++++++++++++++++ mistral/utils/yaql_utils.py | 7 +++++++ 2 files changed, 25 insertions(+) diff --git a/mistral/tests/unit/test_expressions.py b/mistral/tests/unit/test_expressions.py index 886ed158..648d4eeb 100644 --- a/mistral/tests/unit/test_expressions.py +++ b/mistral/tests/unit/test_expressions.py @@ -111,6 +111,24 @@ class YaqlEvaluatorTest(base.BaseTest): self._evaluator.validate, {'a': 1}) + def test_json_pp(self): + self.assertEqual('"3"', self._evaluator.evaluate('json_pp($)', '3')) + self.assertEqual('3', self._evaluator.evaluate('json_pp($)', 3)) + self.assertEqual( + '[\n 1, \n 2\n]', + self._evaluator.evaluate('json_pp($)', [1, 2]) + ) + self.assertEqual( + '{\n "a": "b"\n}', + self._evaluator.evaluate('json_pp($)', {'a': 'b'}) + ) + self.assertEqual( + '"Mistral\nis\nawesome"', + self._evaluator.evaluate( + 'json_pp($)', '\n'.join(['Mistral', 'is', 'awesome']) + ) + ) + class InlineYAQLEvaluatorTest(base.BaseTest): def setUp(self): diff --git a/mistral/utils/yaql_utils.py b/mistral/utils/yaql_utils.py index 3719ed79..baaf428f 100644 --- a/mistral/utils/yaql_utils.py +++ b/mistral/utils/yaql_utils.py @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +import json + import yaql from mistral.db.v2 import api as db_api @@ -42,6 +44,7 @@ def _register_functions(yaql_ctx): yaql_ctx.register_function(env_) yaql_ctx.register_function(execution_) yaql_ctx.register_function(task_) + yaql_ctx.register_function(json_pp_, name='json_pp') # Additional YAQL functions needed by Mistral. @@ -56,6 +59,10 @@ def execution_(context): return context['__execution'] +def json_pp_(data): + return json.dumps(data, indent=4).replace("\\n", "\n") + + def task_(context, task_name): # Importing data_flow in order to break cycle dependency between modules. from mistral.workflow import data_flow