Beispiel #1
0
def _generate_full_mode(
    ctx: Context,
    protocol_generator: ProtocolGenerator,
    protocol_spec: ProtocolSpecification,
    existing_id_list: Set[PublicId],
    language: str,
) -> None:
    """Generate a protocol in 'full' mode, and add it to the configuration file and agent."""
    try:
        warning_message = protocol_generator.generate(protobuf_only=False,
                                                      language=language)
        if warning_message is not None:
            click.echo(warning_message)

        # Add the item to the configurations
        logger.debug("Registering the {} into {}".format(
            PROTOCOL, DEFAULT_AEA_CONFIG_FILE))
        existing_id_list.add(
            PublicId(protocol_spec.author, protocol_spec.name,
                     protocol_spec.version))
        ctx.agent_loader.dump(
            ctx.agent_config,
            open_file(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE), "w"),
        )
    except FileExistsError:
        raise click.ClickException(  # pragma: no cover
            "A {} with this name already exists. Please choose a different name and try again."
            .format(PROTOCOL))
    except Exception as e:
        raise click.ClickException(
            "Protocol is NOT generated. The following error happened while generating the protocol:\n"
            + str(e))
    fingerprint_item(ctx, PROTOCOL, protocol_spec.public_id)
Beispiel #2
0
def _generate_protobuf_mode(
    ctx: Context,  # pylint: disable=unused-argument
    protocol_generator: ProtocolGenerator,
    language: str,
) -> None:
    """Generate a protocol in 'protobuf' mode, and add it to the configuration file and agent."""
    try:
        warning_message = protocol_generator.generate(protobuf_only=True,
                                                      language=language)
        if warning_message is not None:
            click.echo(warning_message)
    except FileExistsError:  # pragma: no cover
        raise click.ClickException(  # pragma: no cover
            f"A {PROTOCOL} with this name already exists. Please choose a different name and try again."
        )
    except Exception as e:  # pragma: no cover
        raise click.ClickException(  # pragma: no cover
            "Protocol is NOT generated. The following error happened while generating the protocol:\n"
            + str(e))
Beispiel #3
0
def _generate_item(ctx: Context, item_type: str, specification_path: str):
    """Generate an item based on a specification and add it to the configuration file and agent."""
    # Get existing items
    existing_id_list = getattr(ctx.agent_config, "{}s".format(item_type))
    existing_item_list = [public_id.name for public_id in existing_id_list]

    item_type_plural = item_type + "s"

    # Load item specification yaml file
    try:
        protocol_spec = load_protocol_specification(specification_path)
    except Exception as e:
        raise click.ClickException(str(e))

    protocol_directory_path = os.path.join(
        ctx.cwd, item_type_plural, protocol_spec.name
    )

    # Check if we already have an item with the same name in the agent config
    logger.debug(
        "{} already supported by the agent: {}".format(
            item_type_plural, existing_item_list
        )
    )
    if protocol_spec.name in existing_item_list:
        raise click.ClickException(
            "A {} with name '{}' already exists. Aborting...".format(
                item_type, protocol_spec.name
            )
        )
    # Check if we already have a directory with the same name in the resource directory (e.g. protocols) of the agent's directory
    if os.path.exists(protocol_directory_path):
        raise click.ClickException(
            "A directory with name '{}' already exists. Aborting...".format(
                protocol_spec.name
            )
        )

    ctx.clean_paths.append(protocol_directory_path)
    try:
        agent_name = ctx.agent_config.agent_name
        click.echo(
            "Generating {} '{}' and adding it to the agent '{}'...".format(
                item_type, protocol_spec.name, agent_name
            )
        )

        output_path = os.path.join(ctx.cwd, item_type_plural)
        protocol_generator = ProtocolGenerator(specification_path, output_path)
        warning_message = protocol_generator.generate()
        if warning_message is not None:
            click.echo(warning_message)

        # Add the item to the configurations
        logger.debug(
            "Registering the {} into {}".format(item_type, DEFAULT_AEA_CONFIG_FILE)
        )
        existing_id_list.add(
            PublicId(protocol_spec.author, protocol_spec.name, protocol_spec.version)
        )
        ctx.agent_loader.dump(
            ctx.agent_config, open(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE), "w")
        )
    except FileExistsError:
        raise click.ClickException(  # pragma: no cover
            "A {} with this name already exists. Please choose a different name and try again.".format(
                item_type
            )
        )
    except ProtocolSpecificationParseError as e:
        raise click.ClickException(  # pragma: no cover
            "The following error happened while parsing the protocol specification: "
            + str(e)
        )
    except Exception as e:
        raise click.ClickException(
            "Protocol is NOT generated. The following error happened while generating the protocol:\n"
            + str(e)
        )

    fingerprint_item(ctx, PROTOCOL, protocol_spec.public_id)
Beispiel #4
0
    def test_compare_latest_generator_output_with_test_protocol(self):
        """Test that the "t_protocol" test protocol matches with what the latest generator generates based on the specification."""
        # Skip if prerequisite applications are not installed
        try:
            check_prerequisites()
        except FileNotFoundError:
            pytest.skip(
                "Some prerequisite applications are not installed. Skipping this test."
            )

        # Specification
        # protocol_name = "t_protocol"
        path_to_specification = os.path.join(ROOT_DIR, "tests", "data",
                                             "sample_specification.yaml")
        path_to_generated_protocol = self.t
        # path_to_original_protocol = os.path.join(
        #     ROOT_DIR, "tests", "data", "generator", protocol_name
        # )
        path_to_package = "tests.data.generator."

        # Generate the protocol
        protocol_generator = ProtocolGenerator(
            path_to_specification,
            path_to_generated_protocol,
            path_to_protocol_package=path_to_package,
        )
        protocol_generator.generate()

        # # compare __init__.py
        # init_file_generated = Path(self.t, protocol_name, "__init__.py")
        # init_file_original = Path(path_to_original_protocol, "__init__.py",)
        # assert filecmp.cmp(init_file_generated, init_file_original)

        # # compare protocol.yaml
        # protocol_yaml_file_generated = Path(self.t, protocol_name, "protocol.yaml")
        # protocol_yaml_file_original = Path(path_to_original_protocol, "protocol.yaml",)
        # assert filecmp.cmp(protocol_yaml_file_generated, protocol_yaml_file_original)

        # # compare message.py
        # message_file_generated = Path(self.t, protocol_name, "message.py")
        # message_file_original = Path(path_to_original_protocol, "message.py",)
        # assert filecmp.cmp(message_file_generated, message_file_original)

        # # compare serialization.py
        # serialization_file_generated = Path(self.t, protocol_name, "serialization.py")
        # serialization_file_original = Path(
        #     path_to_original_protocol, "serialization.py",
        # )
        # assert filecmp.cmp(serialization_file_generated, serialization_file_original)

        # # compare .proto
        # proto_file_generated = Path(
        #     self.t, protocol_name, "{}.proto".format(protocol_name)
        # )
        # proto_file_original = Path(
        #     path_to_original_protocol, "{}.proto".format(protocol_name),
        # )
        # assert filecmp.cmp(proto_file_generated, proto_file_original)

        # # compare _pb2.py
        # pb2_file_generated = Path(
        #     self.t, protocol_name, "{}_pb2.py".format(protocol_name)
        # )
        # with open(ROOT_DIR + "/x_pb2.py", "w") as fp:
        #     fp.write(pb2_file_generated.read_text())
        # pb2_file_original = Path(
        #     path_to_original_protocol, "{}_pb2.py".format(protocol_name),
        # )
        # assert filecmp.cmp(pb2_file_generated, pb2_file_original)
        assert True
Beispiel #5
0
def _generate_protocol(ctx: Context, protocol_specification_path: str) -> None:
    """Generate a protocol based on a specification and add it to the configuration file and agent."""
    protocol_plural = PROTOCOL + "s"

    # Create protocol generator (load, validate,
    # extract fields from protocol specification yaml file)
    try:
        output_path = os.path.join(ctx.cwd, protocol_plural)
        protocol_generator = ProtocolGenerator(protocol_specification_path,
                                               output_path)
    except FileNotFoundError as e:
        raise click.ClickException(  # pragma: no cover
            "Protocol is NOT generated. The following error happened while generating the protocol:\n"
            + str(e))
    except yaml.YAMLError as e:
        raise click.ClickException(  # pragma: no cover
            "Protocol is NOT generated. The following error happened while generating the protocol:\n"
            + "Yaml error in the protocol specification file:" + str(e))
    except ProtocolSpecificationParseError as e:
        raise click.ClickException(  # pragma: no cover
            "Protocol is NOT generated. The following error happened while generating the protocol:\n"
            + "Error while parsing the protocol specification: " + str(e))
    except Exception as e:  # pragma: no cover
        raise click.ClickException(  # pragma: no cover
            "Protocol is NOT generated. The following error happened while generating the protocol:\n"
            + str(e))

    # helpers
    language = ctx.config.get("language")
    existing_protocol_ids_list = getattr(ctx.agent_config,
                                         "{}s".format(PROTOCOL))
    existing_protocol_name_list = [
        public_id.name for public_id in existing_protocol_ids_list
    ]
    protocol_spec = protocol_generator.protocol_specification
    protocol_directory_path = os.path.join(ctx.cwd, protocol_plural,
                                           protocol_spec.name)

    # Check if a protocol with the same name exists in the agent config
    if protocol_spec.name in existing_protocol_name_list:
        raise click.ClickException(
            "Protocol is NOT generated. The following error happened while generating the protocol:\n"
            +
            f"A {PROTOCOL} with name '{protocol_spec.name}' already exists. Aborting..."
        )

    # Check if a directory with the same name as the protocol's exists
    # in the protocols directory of the agent's directory
    if os.path.exists(protocol_directory_path):
        raise click.ClickException(
            "Protocol is NOT generated. The following error happened while generating the protocol:\n"
            +
            f"A directory with name '{protocol_spec.name}' already exists. Aborting..."
        )

    ctx.clean_paths.append(protocol_directory_path)
    agent_name = ctx.agent_config.agent_name
    click.echo("Generating {} '{}' and adding it to the agent '{}'...".format(
        PROTOCOL, protocol_spec.name, agent_name))

    if language == PROTOCOL_LANGUAGE_PYTHON:
        _generate_full_mode(ctx, protocol_generator, protocol_spec,
                            existing_protocol_ids_list, language)
    else:
        _generate_protobuf_mode(ctx, protocol_generator, language)