3

Our Python application currently loads Durable rules from a YAML file (which will soon be a database or Redis cache), then converts that YAML to JSON, before sending the JSON object to the Durable Rules engine for processing.

I am refactoring this rules engine service and would like to also use the Python version of the Rules in my unit tests, basically incorporating the Durable README examples into our engine. After I create the ruleset in Python, how do I serialize that ruleset to a JSON object?

Below is a pytest unit test that works, except for the last line, where I want to serialize the rule.

The ultimate goal is to be able to write Rules in the Python format (which is readable) and then save them as JSON (which is less readable).


import pytest

from durable.lang import *
from durable.engine import Ruleset

# Tests derived from examples on Durable website.
printed_value = '?'
def mock_print(s):
  global printed_value
  printed_value = s
  return s

def test_hello(builder):
  global ruleset
  with ruleset('test_hello'):
    @when_all(m.subject == 'World')
    def say_hello(c):
      mock_print('Hello {0}'.format(c.m.subject))

  post('test_hello', { 'subject': 'World' })
  assert printed_value == 'Hello World'

  rule_as_json = ???

I cannot even find where the Durbale ruleset JSON format and all its features are described. That documentation alone would be useful.

UPDATE 1:

I found the documentation of the JSON structure supported by durable. Still do not know how to change python into JSON.

https://github.com/jruizgit/rules/blob/master/docs/json/reference.md

UPDATE 2:

Finally found where durable.lang library is in the source code:

libpy\durable\lang.py

This code looks promising to follow to get closer to an answer.

def post(ruleset_name, message, complete = None):
    return get_host().post(ruleset_name, message, complete)
Paul Chernoch
  • 5,275
  • 3
  • 52
  • 73

1 Answers1

0

Here a solution:

from durable.lang import *

def test():
    # global ruleset
    with ruleset("test_hello"):

        @when_all(m.subject == "World")
        def say_hello(c):
            mock_print("Hello {0}".format(c.m.subject))

    post("test_hello", {"subject": "World"})
    assert printed_value == "Hello World"

    rule_as_json = get_host().get_ruleset("test_hello").get_definition()
    return rule_as_json

And execution in iPython:

import durablejson as dj

dj.test()
{'r_0': {'all': [{'m': {'subject': 'World'}}]}}