async def test_startup_errors_should_halt_ready():
    """
    Ensure that a failure to connect aborts ready futures.
    """
    network = Network()
    network.set_config(url="http://nowhere.at.all.localdomain:6865/",
                       connect_timeout=1)

    client = network.aio_party("SillyParty")

    # place the ready() call BEFORE the run
    f = ensure_future(wait_for(client.ready(), 2))

    try:
        await network.aio_run(keep_open=False)
    except Exception:
        pass

    try:
        await f
        raise AssertionError(
            "client.ready() should not have ended because there is nothing to connect to"
        )
    except asyncio.TimeoutError:
        raise AssertionError(
            "client.ready() did not abort with an appropriate exception and was killed because "
            "it was taking too long")
    except CancelledError:
        LOG.info("Successfully terminated because ready() was cancelled.")
Example #2
0
def create_ssl_test_package(force=False) -> Tuple[SSLSettings, SSLSettings]:
    """
    Generate certs and scripts for running a Sandbox.

    The contents of the directory will be reused for no longer than 24 hours. If the test package is
    older than that or not present at all, it will be (re-)created.

    :return: A tuple of client/server SSL settings.
    """
    import time
    pkg_dir = Path(_DAZL_ROOT).resolve() / '.tmp' / 'ssl'
    pkg_dir.mkdir(parents=True, exist_ok=True)
    sandbox_script = pkg_dir / 'sandbox.sh'

    client_ssl_settings = SSLSettings(ca_file=str(pkg_dir / 'ca.crt'),
                                      cert_file=str(pkg_dir / 'server.crt'),
                                      cert_key_file=str(pkg_dir / 'server.key'))
    server_ssl_settings = SSLSettings(ca_file=str(pkg_dir / 'ca.crt'),
                                      cert_file=str(pkg_dir / 'server.crt'),
                                      cert_key_file=str(pkg_dir / 'server.pem'))
    if not force:
        if sandbox_script.exists():
            if (time.time() - sandbox_script.stat().st_mtime) < 86400:
                LOG.info('Skipping package creation because we already did it')
                return client_ssl_settings, server_ssl_settings

    # wipe out the package and start over
    for p in pkg_dir.glob('**'):
        if not p.is_dir():
            p.unlink()

    # create the certs
    run(args=[str(TLS_KEYGEN_SCRIPT), '--destination', str(pkg_dir), '--common-name', 'digitalasset.com.test'], check=True)
    return client_ssl_settings, server_ssl_settings
Example #3
0
def create_initial_state(event: "ReadyEvent"):
    try:
        LOG.info("Uploading our DAR...")
        event.client.ensure_dar(PostOffice)

        LOG.info("DAR uploaded. Creating the initial postman role contract...")
        return CreateCommand("Main:PostmanRole", dict(postman=event.party))
    except:
        LOG.exception("Failed to set up our initial state!")
def test_dar_version_compatibility(subtests):
    dars = list(ARCHIVES.glob('**/*.dar'))
    assert len(dars) > 0, f'Could not find any DARs in {ARCHIVES}'

    for dar in ARCHIVES.glob('**/*.dar'):
        short_dar = dar.relative_to(ARCHIVES)
        with subtests.test(str(short_dar)):
            dar_file = DarFile(dar)
            metadata = dar_file.read_metadata()
            LOG.info('Successfully read %s with package IDs %r.', short_dar,
                     metadata.package_ids())
def create_initial_state(event: 'ReadyEvent'):
    try:
        LOG.info('Uploading our DAR...')
        event.client.ensure_dar(PostOffice)
        while not event.package_store.resolve_template('Main:PostmanRole'):
            logging.info("Waiting for our DAR to be uploaded...")
            sleep(1)

        LOG.info('DAR uploaded. Creating the initial postman role contract...')
        return create('Main:PostmanRole', dict(postman=event.party))
    except:
        LOG.exception('Failed to set up our initial state!')
Example #6
0
def test_simple_client_api():
    party = 'abc'

    LOG.info('Creating sandbox...')
    with sandbox(daml_path=DAML_FILE) as proc:
        LOG.info('Creating client...')
        with simple_client(url=proc.url, party=party) as client:
            client.ready()
            LOG.info('Submitting...')
            client.submit_create('Main.PostmanRole', {'postman': party})
            LOG.info('getting contracts')
            contracts = client.find_active('*')
            LOG.info('got the contracts')

    assert 1 == len(contracts)
Example #7
0
def test_simple_flask_integration(sandbox):
    network = Network()
    network.set_config(url=sandbox)
    client = network.simple_new_party()

    # seed the ledger with some initial state
    client.add_ledger_ready(create_initial_state)

    network.start_in_background()

    LOG.info("Waiting for the client to be ready...")
    client.ready()

    # TODO: This is currently necessary because there is a bug that prevents ready() from waiting
    #  on ledger_ready events even when those callbacks are added at the appropriate time.
    sleep(10)

    LOG.info("Client is ready.")

    # now start a Flask app
    LOG.info("Starting up the flask app...")
    main_thread = Thread(target=run_flask_app, args=(client, 9999))
    main_thread.start()

    returned_data = run_flask_test(9999)
    assert returned_data == {"postman": client.party}

    network.shutdown()
    network.join(30)

    main_thread.join(30)
    if main_thread.is_alive():
        raise Exception(
            "The Flask thread should have terminated, but did not.")
Example #8
0
def test_simple_flask_integration():
    setup_default_logger(logging.INFO)
    with sandbox(daml_path=DAML_PATH) as proc:
        with simple_client(proc.url, SAMPLE_PARTY) as client:
            # seed the ledger with some initial state
            client.add_ledger_ready(create_initial_state)

            LOG.info('Waiting for the client to be ready...')
            client.ready()
            LOG.info('Client is ready.')

            # now start a Flask app
            LOG.info('Starting up the flask app...')
            main_thread = Thread(target=run_flask_app, args=(client, 9999))
            main_thread.start()

            returned_data = run_flask_test(9999)
            assert returned_data == {'postman': SAMPLE_PARTY}

            main_thread.join(30)
            if main_thread.is_alive():
                raise Exception(
                    'The Flask thread should have terminated, but did not.')
Example #9
0
def test_dar_version_compatibility(dar):
    short_dar = dar.relative_to(ARCHIVES)
    dar_file = DarFile(dar)
    archives = dar_file.archives()
    LOG.info("Successfully read %s with package IDs %r.", short_dar,
             [a.hash for a in archives])
def create_initial_state(_):
    LOG.info('Creating the initial postman role contract...')
    return create('Main.PostmanRole', dict(postman=SAMPLE_PARTY))
Example #11
0
 def print_create(event):
     LOG.info("Seen cid: %s, cdata: %s", event.cid, event.cdata)
     seen_contracts.append(event.cid)
Example #12
0
 def print_initial_state(event):
     LOG.info("Current ACS: %s", event.acs_find_active("*"))