예제 #1
0
파일: utils.py 프로젝트: aghxjk/HttpRunner
def prettify_json_file(file_list):
    """ prettify JSON testcase format
    """
    for json_file in set(file_list):
        if not json_file.endswith(".json"):
            logger.log_warning(
                "Only JSON file format can be prettified, skip: {}".format(
                    json_file))
            continue

        logger.color_print("Start to prettify JSON file: {}".format(json_file),
                           "GREEN")

        dir_path = os.path.dirname(json_file)
        file_name, file_suffix = os.path.splitext(os.path.basename(json_file))
        outfile = os.path.join(dir_path, "{}.pretty.json".format(file_name))

        with io.open(json_file, 'r', encoding='utf-8') as stream:
            try:
                obj = json.load(stream)
            except ValueError as e:
                raise SystemExit(e)

        with io.open(outfile, 'w', encoding='utf-8') as out:
            json.dump(obj, out, indent=4, separators=(',', ': '))
            out.write('\n')

        print("success: {}".format(outfile))
예제 #2
0
파일: utils.py 프로젝트: aghxjk/HttpRunner
    def create_path(path, ptype):
        if ptype == "folder":
            os.makedirs(path)
        elif ptype == "file":
            open(path, 'w').close()

        msg = "created {}: {}".format(ptype, path)
        logger.color_print(msg, "BLUE")
예제 #3
0
def parse_locustfile(file_path):
    """ parse testcase file and return locustfile path.
        if file_path is a Python file, assume it is a locustfile
        if file_path is a YAML/JSON file, convert it to locustfile
    """
    if not os.path.isfile(file_path):
        color_print("file path invalid, exit.", "RED")
        sys.exit(1)

    file_suffix = os.path.splitext(file_path)[1]
    if file_suffix == ".py":
        locustfile_path = file_path
    elif file_suffix in ['.yaml', '.yml', '.json']:
        locustfile_path = gen_locustfile(file_path)
    else:
        # '' or other suffix
        color_print("file type should be YAML/JSON/Python, exit.", "RED")
        sys.exit(1)

    return locustfile_path
예제 #4
0
def validate_json_file(file_list):
    """ validate JSON testcase format
    """
    for json_file in set(file_list):
        if not json_file.endswith(".json"):
            logger.log_warning(
                "Only JSON file format can be validated, skip: {}".format(
                    json_file))
            continue

        logger.color_print("Start to validate JSON file: {}".format(json_file),
                           "GREEN")

        with io.open(json_file) as stream:
            try:
                json.load(stream)
            except ValueError as e:
                raise SystemExit(e)

        print("OK")
예제 #5
0
파일: utils.py 프로젝트: aghxjk/HttpRunner
def dump_json_file(json_data, pwd_dir_path, dump_file_name):
    """ dump json data to file
    """
    class PythonObjectEncoder(json.JSONEncoder):
        def default(self, obj):
            try:
                return super().default(self, obj)
            except TypeError:
                return str(obj)

    logs_dir_path = os.path.join(pwd_dir_path, "logs")
    if not os.path.isdir(logs_dir_path):
        os.makedirs(logs_dir_path)

    dump_file_path = os.path.join(logs_dir_path, dump_file_name)

    try:
        with io.open(dump_file_path, 'w', encoding='utf-8') as outfile:
            if is_py2:
                outfile.write(
                    unicode(
                        json.dumps(json_data,
                                   indent=4,
                                   separators=(',', ':'),
                                   ensure_ascii=False,
                                   cls=PythonObjectEncoder)))
            else:
                json.dump(json_data,
                          outfile,
                          indent=4,
                          separators=(',', ':'),
                          ensure_ascii=False,
                          cls=PythonObjectEncoder)

        msg = "dump file: {}".format(dump_file_path)
        logger.color_print(msg, "BLUE")

    except TypeError as ex:
        msg = "Failed to dump json file: {}\nReason: {}".format(
            dump_file_path, ex)
        logger.color_print(msg, "RED")
예제 #6
0
파일: utils.py 프로젝트: aghxjk/HttpRunner
def create_scaffold(project_name):
    """ create scaffold with specified project name.
    """
    if os.path.isdir(project_name):
        logger.log_warning(
            u"Folder {} exists, please specify a new folder name.".format(
                project_name))
        return

    logger.color_print("Start to create new project: {}".format(project_name),
                       "GREEN")
    logger.color_print("CWD: {}\n".format(os.getcwd()), "BLUE")

    def create_path(path, ptype):
        if ptype == "folder":
            os.makedirs(path)
        elif ptype == "file":
            open(path, 'w').close()

        msg = "created {}: {}".format(ptype, path)
        logger.color_print(msg, "BLUE")

    path_list = [(project_name, "folder"),
                 (os.path.join(project_name, "api"), "folder"),
                 (os.path.join(project_name, "testcases"), "folder"),
                 (os.path.join(project_name, "testsuites"), "folder"),
                 (os.path.join(project_name, "reports"), "folder"),
                 (os.path.join(project_name, "debugtalk.py"), "file"),
                 (os.path.join(project_name, ".env"), "file")]
    [create_path(p[0], p[1]) for p in path_list]

    # create .gitignore file
    ignore_file = os.path.join(project_name, ".gitignore")
    ignore_content = ".env\nreports/*"
    with open(ignore_file, "w") as f:
        f.write(ignore_content)
예제 #7
0
def main_hrun():
    """ API test: parse command line options and run commands.
    """
    import argparse
    from apiautotest import logger
    from apiautotest.__about__ import __description__, __version__
    from apiautotest.api import apiautotest
    from apiautotest.compat import is_py2
    from apiautotest.validator import validate_json_file
    from apiautotest.utils import (create_scaffold, get_python2_retire_msg,
                                prettify_json_file)

    parser = argparse.ArgumentParser(description=__description__)
    parser.add_argument(
        '-V', '--version', dest='version', action='store_true',
        help="show version")
    parser.add_argument(
        'testcase_paths', nargs='*',
        help="testcase file path")
    parser.add_argument(
        '--log-level', default='INFO',
        help="Specify logging level, default is INFO.")
    parser.add_argument(
        '--log-file',
        help="Write logs to specified file path.")
    parser.add_argument(
        '--dot-env-path',
        help="Specify .env file path, which is useful for keeping sensitive data.")
    parser.add_argument(
        '--report-template',
        help="specify report template path.")
    parser.add_argument(
        '--report-dir',
        help="specify report save directory.")
    parser.add_argument(
        '--failfast', action='store_true', default=False,
        help="Stop the test run on the first error or failure.")
    parser.add_argument(
        '--save-tests', action='store_true', default=False,
        help="Save loaded tests and parsed tests to JSON file.")
    parser.add_argument(
        '--startproject',
        help="Specify new project name.")
    parser.add_argument(
        '--validate', nargs='*',
        help="Validate JSON testcase format.")
    parser.add_argument(
        '--prettify', nargs='*',
        help="Prettify JSON testcase format.")

    args = parser.parse_args()
    logger.setup_logger(args.log_level, args.log_file)

    if is_py2:
        logger.log_warning(get_python2_retire_msg())

    if args.version:
        logger.color_print("{}".format(__version__), "GREEN")
        exit(0)

    if args.validate:
        validate_json_file(args.validate)
        exit(0)
    if args.prettify:
        prettify_json_file(args.prettify)
        exit(0)

    project_name = args.startproject
    if project_name:
        create_scaffold(project_name)
        exit(0)

    runner = apiautotest(
        failfast=args.failfast,
        save_tests=args.save_tests,
        report_template=args.report_template,
        report_dir=args.report_dir
    )
    try:
        for path in args.testcase_paths:
            runner.run(path, dot_env_path=args.dot_env_path)
    except Exception:
        logger.log_error("!!!!!!!!!! exception stage: {} !!!!!!!!!!".format(runner.exception_stage))
        raise

    return 0
예제 #8
0
import sys

from apiautotest.cli import main_hrun, main_locust
from apiautotest.logger import color_print

cmd = sys.argv.pop(1)

if cmd in ["hrun", "apiautotest", "ate"]:
    main_hrun()
elif cmd in ["locust", "locusts"]:
    main_locust()
else:
    color_print("Miss debugging type.", "RED")
    example = "\n".join([
        "e.g.",
        "python main-debug.py hrun /path/to/testcase_file",
        "python main-debug.py locusts -f /path/to/testcase_file"
    ])
    color_print(example, "yellow")
예제 #9
0
 def startTest(self, test):
     """ add start test time """
     super(HtmlTestResult, self).startTest(test)
     logger.color_print(test.shortDescription(), "yellow")