def _transport_java(obj, indent):
    """
	Generate Java source that loads the dump done by Python, dumps it again,
	and outputs this dump which is again loaded by Python.

	(this requires an installed Java compiler and the Java UL4 jar)
	"""

    f = sys._getframe(1)
    print(
        f"Testing UL4ON via Java ({f.f_code.co_filename}, line {f.f_lineno}):")

    dump = ul4on.dumps(obj, indent=indent)
    code = f"""
	String input = {misc.javaexpr(dump)};
	Object object = com.livinglogic.ul4on.Utils.loads(input, null);
	String output = com.livinglogic.ul4on.Utils.dumps(object, {misc.javaexpr(indent)});
	// We can't use ``System.out.print`` here, because this gives us no control over the encoding
	// Use ``System.out.write`` to make sure the output is in UTF-8
	byte[] outputBytes = output.getBytes("utf-8");
	System.out.write(outputBytes, 0, outputBytes.length);
	"""

    output = java_runsource(code)
    return ul4on.loads(output)
Example #2
0
def _transport_js_spidermonkey(obj, indent):
    """
	Generate Javascript source that loads the dump done by Python, dumps it
	again, and outputs this dump which is again loaded by Python.

	(this requires an installed ``js`` shell from Spidermonkey
	"""
    dump = ul4on.dumps(obj, indent=indent)
    js = "obj = ul4on.loads({});\nprint(JSON.stringify(ul4on.dumps(obj, {})));\n".format(
        ul4c._asjson(dump), ul4c._asjson(indent))
    f = sys._getframe(1)
    print("Testing UL4ON via Spidermonkey ({}, line {}):".format(
        f.f_code.co_filename, f.f_lineno))
    print(js)
    with tempfile.NamedTemporaryFile(mode="wb", suffix=".js") as f:
        f.write(js.encode("utf-8"))
        f.flush()
        dir = os.path.expanduser("~/checkouts/LivingLogic.Javascript.ul4")
        fmt = "js -f {dir}/ul4.js -f {fn}"
        result = subprocess.run(fmt.format(dir=dir, fn=f.name),
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                shell=True)
    stdout = result.stdout.decode("utf-8")
    stderr = result.stderr.decode("utf-8")
    # Check if we have an exception
    if result.returncode:
        print(stdout, file=sys.stdout)
        print(stderr, file=sys.stderr)
        raise RuntimeError((stderr or stdout).splitlines()[0])
    print("Got result {!r}".format(stdout))
    return ul4on.loads(json.loads(stdout))
def _transport_js_v8(obj, indent):
    """
	Generate Javascript source that loads the dump done by Python, dumps it
	again, and outputs this dump which is again loaded by Python.

	(this requires an installed ``d8`` shell from V8 (http://code.google.com/p/v8/))
	"""
    dump = ul4on.dumps(obj, indent=indent)
    js = f"obj = ul4on.loads({ul4c._asjson(dump)});\nprint(ul4on.dumps(obj, {ul4c._asjson(indent)}));\n"
    f = sys._getframe(1)
    print(
        f"Testing UL4ON via V8 ({f.f_code.co_filename}, line {f.f_lineno:,}):")
    print(js)
    with tempfile.NamedTemporaryFile(mode="wb", suffix=".js") as f:
        f.write(js.encode("utf-8"))
        f.flush()
        dir = os.path.expanduser("~/checkouts/LivingLogic.Javascript.ul4")
        cmd = f"d8 {dir}/ul4.js {f.name}"
        result = subprocess.run(cmd,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                shell=True)
    stdout = result.stdout.decode("utf-8")
    stderr = result.stderr.decode("utf-8")
    # Check if we have an exception
    if result.returncode:
        print(stdout, file=sys.stdout)
        print(stderr, file=sys.stderr)
        raise RuntimeError((stderr or stdout).splitlines()[0])
    output = stdout[:-1]  # Drop the "\n"
    print(f"Got result {output!r}")
    return ul4on.loads(output)
def _transport_js_node(obj, indent):
	"""
	Generate Javascript source that loads the dump done by Python, dumps it
	again, and outputs this dump which is again loaded by Python.

	(this requires an installed ``node`` command from Node
	"""
	dump = ul4on.dumps(obj, indent=indent)
	js = f"""
		const ll = require('{home}/checkouts/LivingLogic.Javascript.ul4/ul4.min');
		const ul4on = ll.ul4on;
		obj = ul4on.loads({ul4c._asjson(dump)});
		console.log(JSON.stringify(ul4on.dumps(obj, {ul4c._asjson(indent)})));
	"""
	f = sys._getframe(1)
	print(f"Testing UL4ON via Node ({f.f_code.co_filename}, line {f.f_lineno:,}):")
	print(js)
	with tempfile.NamedTemporaryFile(mode="wb", suffix=".js") as f:
		f.write(js.encode("utf-8"))
		f.flush()
		dir = os.path.expanduser("~/checkouts/LivingLogic.Javascript.ul4")
		cmd = f"node {f.name}"
		result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
	stdout = result.stdout.decode("utf-8")
	stderr = result.stderr.decode("utf-8")
	# Check if we have an exception
	if result.returncode:
		print(stdout, file=sys.stdout)
		print(stderr, file=sys.stderr)
		raise RuntimeError((stderr or stdout).splitlines()[0])
	print(f"Got result {stdout!r}")
	return ul4on.loads(json.loads(stdout))
def _transport_js_v8(obj, indent):
	"""
	Generate Javascript source that loads the dump done by Python, dumps it
	again, and outputs this dump which is again loaded by Python.

	(this requires an installed ``d8`` shell from V8 (http://code.google.com/p/v8/))
	"""
	dump = ul4on.dumps(obj, indent=indent)
	js = f"obj = ul4on.loads({ul4c._asjson(dump)});\nprint(ul4on.dumps(obj, {ul4c._asjson(indent)}));\n"
	f = sys._getframe(1)
	print(f"Testing UL4ON via V8 ({f.f_code.co_filename}, line {f.f_lineno:,}):")
	print(js)
	with tempfile.NamedTemporaryFile(mode="wb", suffix=".js") as f:
		f.write(js.encode("utf-8"))
		f.flush()
		dir = os.path.expanduser("~/checkouts/LivingLogic.Javascript.ul4")
		cmd = f"d8 {dir}/ul4.js {f.name}"
		result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
	stdout = result.stdout.decode("utf-8")
	stderr = result.stderr.decode("utf-8")
	# Check if we have an exception
	if result.returncode:
		print(stdout, file=sys.stdout)
		print(stderr, file=sys.stderr)
		raise RuntimeError((stderr or stdout).splitlines()[0])
	output = stdout[:-1] # Drop the "\n"
	print(f"Got result {output!r}")
	return ul4on.loads(output)
def test_template_from_source():
	t = ul4on.loads("o s'de.livinglogic.ul4.template' n s'test' s'<?print x + y?>' s'x, y=23' s'keep' n n )")

	assert t.name == "test"
	assert t.source == "<?ul4 test(x, y=23)?><?print x + y?>"
	assert t.whitespace == "keep"
	assert t.startdelim == "<?"
	assert t.enddelim == "?>"
	assert t.renders(17) == "40"
def test_template_from_source():
    t = ul4on.loads(
        "o s'de.livinglogic.ul4.template' n s'test' s'<?print x + y?>' s'x, y=23' s'keep' n n )"
    )

    assert t.name == "test"
    assert t.source == "<?ul4 test(x, y=23)?><?print x + y?>"
    assert t.whitespace == "keep"
    assert t.startdelim == "<?"
    assert t.enddelim == "?>"
    assert t.renders(17) == "40"
Example #8
0
        def run(code):
            cursor.execute("""
				create or replace function ul4ontest
				return clob
				as
					c_out clob;
				begin
					{}
					return c_out;
				end;
			""".format(code))
            cursor.execute("select ul4ontest from dual")
            dump = cursor.fetchone().ul4ontest
            return ul4on.loads(dump)
def oracle_ul4onbuffer(code):
    """
	A test fixture that will execute the PL/SQL code passed in as a parameter.
	This PL/SQL code must output an UL4ON dump into the PL/SQL variable ``c_out``
	by using the ``UL4ONBUFFER_PKG`` package. The package name is available as
	the function attribute ``pkg``.

	:func:`oracle_ul4onbuffer` returns the deserialized object dump as a Python
	object.

	For example::

		oracle('''
			{oracle.pkg}.begindict(c_out);
			{oracle.pkg}.enddict(c_out);
		''')

	should return a empty dictionary.

	Note that call to ``UL4ONBUFFER_PKG.INIT()`` and ``UL4ONBUFFER_PKG.FLUSH()``
	are not required in the code passed in (this makes it possible to call
	:func:`oracle_ul4on` and :func:`oracle_ul4onbuffer` with the code).
	"""
    connectstring = os.environ.get("LL_ORASQL_TEST_CONNECT")
    if connectstring:
        from ll import orasql
        db = orasql.connect(connectstring, readlobs=True)
        cursor = db.cursor()
        cursor.execute(f"""
			create or replace function ul4ontest
			return clob
			as
				c_out clob;
			begin
				ul4onbuffer_pkg.init(c_out);
				{code}
				ul4onbuffer_pkg.flush(c_out);
				return c_out;
			end;
		""")
        cursor.execute("select ul4ontest from dual")
        dump = cursor.fetchone().ul4ontest
        return ul4on.loads(dump)
    else:
        return None
def oracle_ul4onbuffer(code):
	"""
	A test fixture that will execute the PL/SQL code passed in as a parameter.
	This PL/SQL code must output an UL4ON dump into the PL/SQL variable ``c_out``
	by using the ``UL4ONBUFFER_PKG`` package. The package name is available as
	the function attribute ``pkg``.

	:func:`oracle_ul4onbuffer` returns the deserialized object dump as a Python
	object.

	For example::

		oracle('''
			{oracle.pkg}.begindict(c_out);
			{oracle.pkg}.enddict(c_out);
		''')

	should return a empty dictionary.

	Note that call to ``UL4ONBUFFER_PKG.INIT()`` and ``UL4ONBUFFER_PKG.FLUSH()``
	are not required in the code passed in (this makes it possible to call
	:func:`oracle_ul4on` and :func:`oracle_ul4onbuffer` with the code).
	"""
	connectstring = os.environ.get("LL_ORASQL_TEST_CONNECT")
	if connectstring:
		from ll import orasql
		db = orasql.connect(connectstring, readlobs=True)
		cursor = db.cursor()
		cursor.execute(f"""
			create or replace function ul4ontest
			return clob
			as
				c_out clob;
			begin
				ul4onbuffer_pkg.init(c_out);
				{code}
				ul4onbuffer_pkg.flush(c_out);
				return c_out;
			end;
		""")
		cursor.execute("select ul4ontest from dual")
		dump = cursor.fetchone().ul4ontest
		return ul4on.loads(dump)
	else:
		return None
def oracle_ul4on(code):
    """
	A test fixture that will execute the PL/SQL code passed in as a parameter.
	This PL/SQL code must output an UL4ON dump into the PL/SQL variable ``c_out``
	by using the ``UL4ON_PKG`` package. The package name is available as the
	function attribute ``pkg``.

	:func:`oracle_ul4on` returns the deserialized object dump as a Python object.

	For example::

		oracle('''
			{oracle.pkg}.begindict(c_out);
			{oracle.pkg}.enddict(c_out);
		''')

	should return a empty dictionary.
	"""
    connectstring = os.environ.get("LL_ORASQL_TEST_CONNECT")
    if connectstring:
        from ll import orasql
        db = orasql.connect(connectstring, readlobs=True)
        cursor = db.cursor()
        print(code)
        cursor.execute(f"""
			create or replace function ul4ontest
			return clob
			as
				c_out clob;
			begin
				{code}
				return c_out;
			end;
		""")
        cursor.execute("select ul4ontest from dual")
        dump = cursor.fetchone().ul4ontest
        return ul4on.loads(dump)
    else:
        return None
def oracle_ul4on(code):
	"""
	A test fixture that will execute the PL/SQL code passed in as a parameter.
	This PL/SQL code must output an UL4ON dump into the PL/SQL variable ``c_out``
	by using the ``UL4ON_PKG`` package. The package name is available as the
	function attribute ``pkg``.

	:func:`oracle_ul4on` returns the deserialized object dump as a Python object.

	For example::

		oracle('''
			{oracle.pkg}.begindict(c_out);
			{oracle.pkg}.enddict(c_out);
		''')

	should return a empty dictionary.
	"""
	connectstring = os.environ.get("LL_ORASQL_TEST_CONNECT")
	if connectstring:
		from ll import orasql
		db = orasql.connect(connectstring, readlobs=True)
		cursor = db.cursor()
		print(code)
		cursor.execute(f"""
			create or replace function ul4ontest
			return clob
			as
				c_out clob;
			begin
				{code}
				return c_out;
			end;
		""")
		cursor.execute("select ul4ontest from dual")
		dump = cursor.fetchone().ul4ontest
		return ul4on.loads(dump)
	else:
		return None
def _transport_js_node(obj, indent):
    """
	Generate Javascript source that loads the dump done by Python, dumps it
	again, and outputs this dump which is again loaded by Python.

	(this requires an installed ``node`` command from Node
	"""
    dump = ul4on.dumps(obj, indent=indent)
    js = f"""
		const ll = require('{home}/checkouts/LivingLogic.Javascript.ul4/ul4.min');
		const ul4on = ll.ul4on;
		obj = ul4on.loads({ul4c._asjson(dump)});
		console.log(JSON.stringify(ul4on.dumps(obj, {ul4c._asjson(indent)})));
	"""
    f = sys._getframe(1)
    print(
        f"Testing UL4ON via Node ({f.f_code.co_filename}, line {f.f_lineno:,}):"
    )
    print(js)
    with tempfile.NamedTemporaryFile(mode="wb", suffix=".js") as f:
        f.write(js.encode("utf-8"))
        f.flush()
        dir = os.path.expanduser("~/checkouts/LivingLogic.Javascript.ul4")
        cmd = f"node {f.name}"
        result = subprocess.run(cmd,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                shell=True)
    stdout = result.stdout.decode("utf-8")
    stderr = result.stderr.decode("utf-8")
    # Check if we have an exception
    if result.returncode:
        print(stdout, file=sys.stdout)
        print(stderr, file=sys.stderr)
        raise RuntimeError((stderr or stdout).splitlines()[0])
    print(f"Got result {stdout!r}")
    return ul4on.loads(json.loads(stdout))
def _transport_java(obj, indent):
	"""
	Generate Java source that loads the dump done by Python, dumps it again,
	and outputs this dump which is again loaded by Python.

	(this requires an installed Java compiler and the Java UL4 jar)
	"""

	f = sys._getframe(1)
	print(f"Testing UL4ON via Java ({f.f_code.co_filename}, line {f.f_lineno}):")

	dump = ul4on.dumps(obj, indent=indent)
	code = f"""
	String input = {misc.javaexpr(dump)};
	Object object = com.livinglogic.ul4on.Utils.loads(input, null);
	String output = com.livinglogic.ul4on.Utils.dumps(object, {misc.javaexpr(indent)});
	// We can't use ``System.out.print`` here, because this gives us no control over the encoding
	// Use ``System.out.write`` to make sure the output is in UTF-8
	byte[] outputBytes = output.getBytes("utf-8");
	System.out.write(outputBytes, 0, outputBytes.length);
	"""

	output = java_runsource(code)
	return ul4on.loads(output)
def _transport_python(obj, indent, registry):
    return ul4on.loads(ul4on.dumps(obj, indent=indent), registry=registry)
def _transport_python(obj, indent, registry):
	return ul4on.loads(ul4on.dumps(obj, indent=indent), registry=registry)