Exemple #1
0
    def execute_preparation_steps(self, iut, preparation_steps):
        """Execute the preparation steps for the environment provider on an IUT.

        :param iut: IUT to prepare for execution.
        :type iut: :obj:`environment_provider.lib.iut.Iut`
        :param preparation_steps: Steps to execute to prepare an IUT.
        :type preparation_steps: dict
        """
        FORMAT_CONFIG.identifier = self.config.get("SUITE_ID")
        try:
            with self.lock:
                dataset = self.dataset.copy()
                dataset.add("config", self.config)
            jsontas = JsonTas(dataset=dataset)
            steps = {}
            dataset.add("iut", iut)
            dataset.add("steps", steps)
            for step, definition in preparation_steps.items():
                definition = OrderedDict(**definition)
                self.logger.info("Executing step %r", step)
                step_result = jsontas.run(json_data=definition)
                self.logger.info("%r", step_result)
                if not step_result:
                    self.logger.error("Failed to execute step %r", step)
                    return False, iut
                steps[step] = step_result
        except Exception as exception:  # pylint:disable=broad-except
            self.logger.error("Failure when preparing IUT %r", iut)
            self.logger.error("%r", exception)
            return False, iut
        return True, iut
Exemple #2
0
def main(args):
    """Entry point allowing external calls.

    Args:
      args ([str]): command line parameter list
    """
    args = parse_args(args)
    setup_logging(args.loglevel)
    jsontas = JsonTas()
    if args.dataset:
        with open(args.dataset) as json_file:
            dataset = json.load(json_file)
        jsontas.dataset.merge(dataset)

    data = jsontas.run(json_file=args.json_file)
    if args.output:
        with open(args.output, "w") as output_file:
            json.dump(data, output_file)
    else:
        pprint(data)
Exemple #3
0
class Iut:  # pylint: disable=too-few-public-methods
    """Data object for IUTs."""

    logger = logging.getLogger(__name__)

    def __init__(self, product):
        """Initialize.

        :param product: Dictionary to set attributes from.
                        Should be the response from pool plugin list.
        :type product: dict
        """
        self.test_runner = {}
        self.config = Config()
        self.config.set("scripts", [])
        self.steps = {
            "environment": self.load_environment,
            "commands": self.commands
        }

        product["identity"] = PackageURL.from_string(product["identity"])
        for key, value in product.items():
            setattr(self, key, value)
        self._product_dict = product
        self.jsontas = JsonTas()
        self.jsontas.dataset.add("iut", self._product_dict)
        self.prepare()

    def prepare(self):
        """Prepare IUT for testing."""
        self.logger.info("Preparing IUT %r", self)
        for step, definition in self.test_runner.get("steps", {}).items():
            step_method = self.steps.get(step)
            if step_method is None:
                self.logger.error("Step %r does not exist. Available %r", step,
                                  self.steps)
                continue
            self.logger.info("Executing step %r", step)
            self.logger.info("Definition: %r", definition)
            if isinstance(definition, list):
                for sub_definition in definition:
                    sub_definition = OrderedDict(**sub_definition)
                    step_result = self.jsontas.run(json_data=sub_definition)
                    step_method(step_result)
            else:
                definition = OrderedDict(**definition)
                step_result = self.jsontas.run(json_data=definition)
                step_method(step_result)

    @staticmethod
    def load_environment(environment):
        """Load and set environment variables from IUT definition.

        :param environment: Environment variables to set.
        :type environment: dict
        """
        for key, value in environment.items():
            os.environ[key] = value

    def commands(self, command):
        """Create scripts from commands and add them to IUT monitoring.

        :param command: A command dictionary to prepare.
        :type command: dict
        """
        script_name = str(Path.cwd().joinpath(command.get("name")))
        parameters = command.get("parameters", [])
        with open(script_name, "w", encoding="utf-8") as script:
            for line in command.get("script"):
                script.write(f"{line}\n")
        self.config.get("scripts").append({
            "name": script_name,
            "parameters": parameters
        })

    @property
    def as_dict(self):
        """Return IUT as a dictionary."""
        return self._product_dict

    def __repr__(self):
        """Represent IUT as string."""
        try:
            return self._product_dict.get("identity").to_string()
        except:  # noqa pylint:disable=bare-except
            return "Unknown"