Ejemplo n.º 1
0
def test_validate_env(mocker) -> None:
    from demisto_sdk.commands.lint import helpers
    mocker.patch.object(helpers, 'run_command_os')
    helpers.run_command_os.side_effect = [('python2', '', ''), ('flake8, mypy, vultue', '', '')]
    helpers.validate_env()

    assert helpers.run_command_os.call_count == 2
Ejemplo n.º 2
0
    def _gather_facts() -> Dict[str, Any]:
        """ Gather shared required facts for lint command execution - Also perform mandatory resource checkup.
            1. Content repo object.
            2. Requirements file for docker images.
            3. Mandatory test modules - demisto-mock.py etc
            3. Docker daemon check.

        Returns:
            dict: facts
        """
        facts = {
            "content_repo": None,
            "requirements_3": None,
            "requirements_2": None,
            "test_modules": None,
            "docker_engine": True
        }
        # Check env requirements satisfied - bootstrap in use
        validate_env()
        # Get content repo object
        is_external_repo = False
        try:
            git_repo = git.Repo(os.getcwd(), search_parent_directories=True)
            remote_url = git_repo.remote().urls.__next__()
            is_fork_repo = 'content' in remote_url
            is_external_repo = tools.is_external_repository()

            if not is_fork_repo and not is_external_repo:
                raise git.InvalidGitRepositoryError

            facts["content_repo"] = git_repo
            logger.debug(f"Content path {git_repo.working_dir}")
        except (git.InvalidGitRepositoryError, git.NoSuchPathError) as e:
            print_warning(
                "You are running demisto-sdk lint not in content repository!")
            logger.warning(f"can't locate content repo {e}")
        # Get global requirements file
        pipfile_dir = Path(__file__).parent / 'resources'
        try:
            for py_num in ['2', '3']:
                pipfile_lock_path = pipfile_dir / f'pipfile_python{py_num}/Pipfile.lock'
                with open(file=pipfile_lock_path) as f:
                    lock_file: dict = json.load(fp=f)["develop"]
                    facts[f"requirements_{py_num}"] = [
                        key + value["version"]
                        for key, value in  # type: ignore
                        lock_file.items()
                    ]
                    logger.debug(
                        f"Test requirements successfully collected for python {py_num}:\n"
                        f" {facts[f'requirements_{py_num}']}")
        except (json.JSONDecodeError, IOError, FileNotFoundError,
                KeyError) as e:
            print_error("Can't parse pipfile.lock - Aborting!")
            logger.critical(f"demisto-sdk-can't parse pipfile.lock {e}")
            sys.exit(1)
        # ￿Get mandatory modulestest modules and Internet connection for docker usage
        try:
            facts["test_modules"] = get_test_modules(
                content_repo=facts["content_repo"],  # type: ignore
                is_external_repo=is_external_repo)
            logger.debug("Test mandatory modules successfully collected")
        except git.GitCommandError as e:
            print_error(
                "Unable to get test-modules demisto-mock.py etc - Aborting! corrupt repository of pull from master"
            )
            logger.error(
                f"demisto-sdk-unable to get mandatory test-modules demisto-mock.py etc {e}"
            )
            sys.exit(1)
        except (requests.exceptions.ConnectionError,
                urllib3.exceptions.NewConnectionError) as e:
            print_error(
                "Unable to get mandatory test-modules demisto-mock.py etc - Aborting! (Check your internet "
                "connection)")
            logger.error(
                f"demisto-sdk-unable to get mandatory test-modules demisto-mock.py etc {e}"
            )
            sys.exit(1)
        # Validating docker engine connection
        docker_client: docker.DockerClient = docker.from_env()
        try:
            docker_client.ping()
        except (requests.exceptions.ConnectionError,
                urllib3.exceptions.ProtocolError, docker.errors.APIError):
            facts["docker_engine"] = False
            print_warning(
                "Can't communicate with Docker daemon - check your docker Engine is ON - Skipping lint, "
                "test which require docker!")
            logger.info("demisto-sdk-Can't communicate with Docker daemon")
        logger.debug("Docker daemon test passed")

        return facts