예제 #1
0
def cli(arghandling=ArgHandling(), argparser=ArgumentParser(prog=__app_name__,
                                                            description="BDD Test Framework for Hashicorp terraform")):
    args = arghandling
    parser = argparser
    parser.add_argument("--terraform", "-t", dest="terraform_file", metavar='terraform_file', type=str, nargs='?',
                        help="The absolute path to the terraform executable.", required=False)
    _, radish_arguments = parser.parse_known_args(namespace=args)

    # TODO: Create a custom usage() since it just shows -t right now

    parser.add_argument("--features", "-f", dest="features", metavar='feature directory', action=ReadableDir,
                        help="Directory (or git repository with 'git:' prefix) consists of BDD features", required=True)
    parser.add_argument("--planfile", "-p", dest="plan_file", metavar='plan_file', action=ReadablePlan,
                        help="Plan output file generated by Terraform", required=True)
    parser.add_argument("--identity", "-i", dest="ssh_key", metavar='ssh private key', type=str, nargs='?',
                        help="SSH Private key that will be use on git authentication.", required=False)
    parser.add_argument("--version", "-v", action="version", version=__version__)

    _, radish_arguments = parser.parse_known_args(namespace=args)

    steps_directory = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'steps')

    # SSH Key is given for git authentication
    ssh_cmd = {}
    if args.ssh_key:
        ssh_cmd = {"GIT_SSH_COMMAND": "ssh -l {} -i {}".format('git', args.ssh_key)}

    # A remote repository used here
    if args.features.startswith(('http', 'https', 'ssh')):
        features_git_repo = args.features
        args.features = mkdtemp()

        Repo.clone_from(url=features_git_repo, to_path=args.features, env=ssh_cmd)

    features_directory = os.path.join(os.path.abspath(args.features))
    print('* Features  : {}{}'.format(features_directory,
                                     (' ({})'.format(features_git_repo) if 'features_git_repo' in locals() else '')))

    print('* Plan File : {}'.format(args.plan_file))
    commands = ['radish',
                '--write-steps-once',
                features_directory,
                '--basedir', steps_directory,
                '--user-data=plan_file={}'.format(args.plan_file)]
    commands.extend(radish_arguments)

    print('\n. Running tests.')
    result = call_radish(args=commands[1:])

    return result
예제 #2
0
def cli():
    argument = ArgHandling()
    parser = ArgumentParser(prog=__app_name__,
                            description="BDD Test Framework for Hashicorp terraform")
    try:
        parser.add_argument("--features", "-f", dest="features", metavar='feature_directory', action=readable_dir,
                        help="Directory consists of BDD features", required=True)
        parser.add_argument("--tfdir", "-t", dest="tf_dir", metavar='terraform_directory', action=readable_dir,
                        help="Directory consists of Terraform Files", required=True)
    except argparse.ArgumentTypeError:
        print('Invalid use or arguments: {}'.format(sys.exc_info()[1]))
        sys.exit(1)

    # parser.parse_args(namespace=argument)
    _, radish_arguments = parser.parse_known_args(namespace=argument)

    print('{} v{} initiated'.format(__app_name__, __version__))

    features_directory = os.path.join(os.path.abspath(argument.features))
    steps_directory = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'steps')
    tf_directory = os.path.join(os.path.abspath(argument.tf_dir))

    print('Features : {}'.format(features_directory))
    print('Steps    : {}'.format(steps_directory))
    print('TF Files : {}'.format(tf_directory))

    commands = ['radish',
                features_directory,
                '--basedir', steps_directory,
                '--user-data=tf_dir={}'.format(tf_directory)]
    commands.extend(radish_arguments)

    try:
        print('Validating terraform files.')
        Validator(tf_directory)
        print('All HCL files look good.')

    except ValueError:
        print('Unable to validate Terraform Files.')
        print('ERROR: {}'.format(sys.exc_info()[1]))
        sys.exit(1)

    print('Running tests.')
    return call_radish(args=commands[1:])
예제 #3
0
def cli(arghandling=ArgHandling(),
        argparser=ArgumentParser(
            prog=__app_name__,
            description="BDD Test Framework for Hashicorp terraform")):
    args = arghandling
    parser = argparser
    parser.add_argument("--features",
                        "-f",
                        dest="features",
                        metavar='feature_directory',
                        action=ReadableDir,
                        help="Directory consists of BDD features",
                        required=True)
    parser.add_argument(
        "--tfdir",
        "-t",
        dest="tf_dir",
        metavar='terraform_directory',
        action=ReadableDir,
        help=
        "Directory (or git repository with 'git:' prefix) consists of Terraform Files",
        required=True)
    parser.add_argument(
        "--identity",
        "-i",
        dest="ssh_key",
        metavar='ssh_private_key',
        type=str,
        nargs='?',
        help="SSH Private key that will be use on git authentication.",
        required=False)
    parser.add_argument("--version",
                        "-v",
                        action="version",
                        version=__version__)

    _, radish_arguments = parser.parse_known_args(namespace=args)

    print('{} v{} initiated'.format(__app_name__, __version__))

    steps_directory = os.path.join(
        os.path.split(os.path.abspath(__file__))[0], 'steps')
    print('Steps    : {}'.format(steps_directory))

    # SSH Key is given for git authentication
    ssh_cmd = {}
    if args.ssh_key:
        ssh_cmd = {
            "GIT_SSH_COMMAND": "ssh -l {} -i {}".format('git', args.ssh_key)
        }

    # A remote repository used here
    if args.features.startswith(('http', 'https', 'ssh')):
        features_git_repo = args.features
        args.features = mkdtemp()

        Repo.clone_from(url=features_git_repo,
                        to_path=args.features,
                        env=ssh_cmd)
    features_directory = os.path.join(os.path.abspath(args.features))
    print('Features : {}{}'.format(features_directory,
                                   (' ({})'.format(features_git_repo) if
                                    'features_git_repo' in locals() else '')))

    tf_tmp_dir = mkdtemp()

    # A remote repository is used here.
    if args.tf_dir.startswith(('http', 'https', 'ssh')):
        tf_git_repo = args.tf_dir
        Repo.clone_from(url=tf_git_repo, to_path=tf_tmp_dir, env=ssh_cmd)

    # A local directory is used here
    else:
        # Copy the given local directory to another place, since we may change some tf files for compatibility.
        copy_tree(args.tf_dir, tf_tmp_dir)

    tf_directory = os.path.join(os.path.abspath(tf_tmp_dir))
    print('TF Files : {} ({})'.format(tf_directory, args.tf_dir))

    commands = [
        'radish', '--write-steps-once', features_directory, '--basedir',
        steps_directory, '--user-data=tf_dir={}'.format(tf_directory)
    ]
    commands.extend(radish_arguments)

    try:
        load_tf_files(tf_directory)
    except TerraformComplianceInvalidConfig:
        print exc_info()[1]
        exit(1)

    print('Running tests.')
    result = call_radish(args=commands[1:])

    # Delete temporary directory we created
    print('Cleaning up.')
    rmtree(tf_directory)

    return result
예제 #4
0
def cli():
    args = ArgHandling()
    parser = ArgumentParser(
        prog=__app_name__,
        description="BDD Test Framework for Hashicorp terraform")
    parser.add_argument("--features",
                        "-f",
                        dest="features",
                        metavar='feature_directory',
                        action=ReadableDir,
                        help="Directory consists of BDD features",
                        required=True)
    parser.add_argument(
        "--tfdir",
        "-t",
        dest="tf_dir",
        metavar='terraform_directory',
        action=ReadableDir,
        help=
        "Directory (or git repository with 'git:' prefix) consists of Terraform Files",
        required=True)
    parser.add_argument("--version",
                        "-v",
                        action="version",
                        version=__version__)

    _, radish_arguments = parser.parse_known_args(namespace=args)

    print('{} v{} initiated'.format(__app_name__, __version__))

    steps_directory = os.path.join(
        os.path.split(os.path.abspath(__file__))[0], 'steps')
    print('Steps    : {}'.format(steps_directory))

    # A remote repository used here
    if args.features.startswith('http'):
        features_git_repo = args.features
        args.features = mkdtemp()
        Repo.clone_from(features_git_repo, args.features)
    features_directory = os.path.join(os.path.abspath(args.features))
    print('Features : {}{}'.format(features_directory,
                                   (' ({})'.format(features_git_repo) if
                                    'features_git_repo' in locals() else '')))

    tf_tmp_dir = mkdtemp()

    # A remote repository is used here.
    if args.tf_dir.startswith('http'):
        tf_git_repo = args.tf_dir
        Repo.clone_from(tf_git_repo, tf_tmp_dir)

    # A local directory is used here
    else:
        # Copy the given local directory to another place, since we may change some tf files for compatibility.
        copy_tree(args.tf_dir, tf_tmp_dir)

    tf_directory = os.path.join(os.path.abspath(tf_tmp_dir))
    print('TF Files : {} ({})'.format(tf_directory, args.tf_dir))

    commands = [
        'radish', '--write-steps-once', features_directory, '--basedir',
        steps_directory, '--user-data=tf_dir={}'.format(tf_directory)
    ]
    commands.extend(radish_arguments)

    load_tf_files(tf_directory)
    print('Running tests.')
    result = call_radish(args=commands[1:])

    # Delete temporary directory we created
    print('Cleaning up.')
    rmtree(tf_directory)
예제 #5
0
def cli(arghandling=ArgHandling(), argparser=ArgumentParser(prog=__app_name__,
                                                            description='BDD Test Framework for Hashicorp terraform')):
    args = arghandling
    parser = argparser
    parser.add_argument('--terraform', '-t', dest='terraform_file', metavar='terraform_file', type=str, nargs='?',
                        help='The absolute path to the terraform executable.', required=False)
    parser.add_argument('--features', '-f', dest='features', metavar='feature directory', action=ReadableDir,
                        help='Directory (or git repository with "git:" prefix) consists of BDD features', required=True)
    parser.add_argument('--planfile', '-p', dest='plan_file', metavar='plan_file', action=ReadablePlan,
                        help='Plan output file generated by Terraform', required=True)
    parser.add_argument('--quit-early', '-q', dest='exit_on_failure', action='store_true',
                        help='Stops executing any more steps in a scenario on first failure.', required=False)
    parser.add_argument('--no-failure', '-n', dest='no_failure', action='store_true',
                        help='Skip all the tests that is failed, but giving proper failure message', required=False)
    parser.add_argument('--silent', '-S', dest='silence', action='store_true',
                        help='Do not output any scenarios, just write results or failures', required=False)
    parser.add_argument('--identity', '-i', dest='ssh_key', metavar='ssh private key', type=str, nargs='?',
                        help='SSH Private key that will be use on git authentication.', required=False)

    parser.add_argument('--version', '-v', action='version', version=__version__)

    _, radish_arguments = parser.parse_known_args(namespace=args)

    steps_directory = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'steps')

    # SSH Key is given for git authentication
    ssh_cmd = {}
    if args.ssh_key:
        ssh_cmd = {'GIT_SSH_COMMAND': 'ssh -l {} -i {}'.format('git', args.ssh_key)}

    features_dir = '/'
    # A remote repository used here
    if args.features.startswith(('http', 'https', 'ssh')):
        # Default to master branch and full repository
        if args.features.endswith('.git'):
            features_git_repo = args.features
            features_git_branch = 'master'

        # Optionally allow for directory and branch
        elif '.git//' in args.features and '?ref=' in args.features:
            # Split on .git/
            features_git_list = args.features.split('.git/', 1)
            # Everything up to .git is the repository
            features_git_repo = features_git_list[0] + '.git'

            # Split the directory and branch ref
            features_git_list = features_git_list[1].split('?ref=', 1)
            features_dir = features_git_list[0]
            features_git_branch = features_git_list[1]

        else:  # invalid
            raise ValueError("Bad feature directory:" + args.features)

        # Clone repository
        args.features = mkdtemp()
        Repo.clone_from(url=features_git_repo, to_path=args.features, env=ssh_cmd, depth=1, branch=features_git_branch)

    features_directory = os.path.join(os.path.abspath(args.features) + features_dir)

    commands = ['radish',
                '--write-steps-once',
                features_directory,
                '--basedir', steps_directory,
                '--user-data=plan_file={}'.format(args.plan_file),
                '--user-data=exit_on_failure={}'.format(args.exit_on_failure),
                '--user-data=terraform_executable={}'.format(args.terraform_file),
                '--user-data=no_failure={}'.format(args.no_failure),
                '--user-data=silence_mode_enabled={}'.format(args.silence)]
    commands.extend(radish_arguments)

    console_write('{} {} {}{}'.format(Defaults().icon,
                                      Defaults().yellow('Features\t:'),
                                      features_directory,
                                       (' ({})'.format(features_git_repo) if 'features_git_repo' in locals() else '')))

    console_write('{} {} {}'.format(Defaults().icon,
                                    Defaults().green('Plan File\t:'),
                                    args.plan_file))

    if args.silence is True:
        console_write('{} Suppressing output enabled.'.format(Defaults().icon))
        commands.append('--formatter=dotter')

    if args.exit_on_failure is True:
        console_write('{} {}\t\t: Scenario executions will stop on first step {}.'.format(Defaults().info_icon,
                                                                                          Defaults().info_colour('INFO'),
                                                                                          Defaults().failure_colour('failure')))

    if args.no_failure is True:
        console_write('{} {}\t: {}ping all {} steps, exit code will always be {}.'.format(Defaults().warning_icon,
                                                                                          Defaults().warning_colour('WARNING'),
                                                                                          Defaults().skip_colour('SKIP'),
                                                                                          Defaults().failure_colour('failure'),
                                                                                          Defaults().info_colour(0)))

    if Defaults().interactive_mode is False:
        console_write('{} Running in non-interactive mode.'.format(Defaults().info_icon))

    if args.silence is False:
        console_write('\n{} Running tests. {}\n'.format(Defaults().icon,
                                                        Defaults().tada))

    try:
        result = call_radish(args=commands[1:])
    except IndexError as e:
        print(e)

    return result