dazl

Testing

Code that you write against the Daml Python bindings will typically need a Sandbox to be running. You can use a setup similar to what the Daml Python bingings do for their own tests.

The Daml Python bindings start a single Sandbox process for all of their tests, because starting and stopping Sandbox instances repeatedly can greatly slow down the test suite. To achieve good isolation between tests, use freshly-allocated Party in instances instead. Because of DAML’s privacy model, islands of Party s that are mutually unaware of each other are guaranteed to never see unintended contracts.

unittest

You can use a module-based setup fixture in unittest:

# Change this to point to your DAML project directory.
# daml_project_root = "<path to directory containing daml.yaml>"

import unittest

from dazl import Network, testing

sandbox_proc = testing.sandbox(project_root=daml_project_root)


def setUpModule():
    """
    Called by ``unittest`` before the tests in this module are going to be run.
    """
    global sandbox_proc
    sandbox_proc.start()


def tearDownModule():
    if sandbox_proc is not None:
        sandbox_proc.stop()


class ExampleTest(unittest.TestCase):
    def setUp(self) -> None:
        self.network = Network()
        self.network.set_config(url=sandbox_proc.url)
        self.network.start_in_background()

    def tearDown(self) -> None:
        self.network.shutdown()
        self.network.join()

    def test_something(self):
        client = self.network.simple_new_party()
        client.ready()

        client.create("Main:PostmanRole", {"postman": client.party})
        self.assertEqual(len(client.find_active("Main:PostmanRole")), 1)


pytest

The Daml Python bindings use pytest internally, which supports session-scoped fixtures and avoids the need for globals:

import dazl
import pytest

# Change this to point to your DAML project directory.
# daml_project_root = "<path to directory containing daml.yaml>"

@pytest.fixture(scope="session")
def sandbox():
    with dazl.testing.sandbox(project_root=daml_project_root) as sandbox_proc:
        yield sandbox_proc


def test_something(sandbox):
    network = dazl.Network()
    network.set_config(url=sandbox.url)
    network.start_in_background()
    try:
        client = self.network.simple_new_party()
        client.ready()

        client.create('Main:PostmanRole', {'postman': client.party})
        assert len(client.find_active('Main:PostmanRole') == 1

    finally:
        network.shutdown()
        network.join()