change: har2case generate pytest file by default

This commit is contained in:
debugtalk
2020-06-03 20:00:47 +08:00
parent 855edcb205
commit 0e9513afa0
4 changed files with 34 additions and 12 deletions

View File

@@ -16,7 +16,7 @@
**Changed** **Changed**
- change: generate pytest in chain style by default - change: har2case generate pytest file by default
- docs: update sponsor info - docs: update sponsor info
## 3.0.6 (2020-05-29) ## 3.0.6 (2020-05-29)

View File

@@ -30,7 +30,14 @@ def init_har2case_parser(subparsers):
"--to-yaml", "--to-yaml",
dest="to_yaml", dest="to_yaml",
action="store_true", action="store_true",
help="Convert to YAML format, if not specified, convert to JSON format by default.", help="Convert to YAML format, if not specified, convert to pytest format by default.",
)
parser.add_argument(
"-2j",
"--to-json",
dest="to_json",
action="store_true",
help="Convert to JSON format, if not specified, convert to pytest format by default.",
) )
parser.add_argument( parser.add_argument(
"--filter", "--filter",
@@ -55,7 +62,13 @@ def main_har2case(args):
logger.error(f"HAR file not exists: {har_source_file}") logger.error(f"HAR file not exists: {har_source_file}")
sys.exit(1) sys.exit(1)
output_file_type = "YML" if args.to_yaml else "JSON" if args.to_yaml:
output_file_type = "YAML"
elif args.to_yaml:
output_file_type = "JSON"
else:
output_file_type = "pytest"
HarParser(har_source_file, args.filter, args.exclude).gen_testcase(output_file_type) HarParser(har_source_file, args.filter, args.exclude).gen_testcase(output_file_type)
return 0 return 0

View File

@@ -7,6 +7,7 @@ import urllib.parse as urlparse
from loguru import logger from loguru import logger
from httprunner.ext.har2case import utils from httprunner.ext.har2case import utils
from httprunner.make import make_testcase, format_pytest_with_black
try: try:
from json.decoder import JSONDecodeError from json.decoder import JSONDecodeError
@@ -329,17 +330,23 @@ class HarParser(object):
testcase = {"config": config, "teststeps": teststeps} testcase = {"config": config, "teststeps": teststeps}
return testcase return testcase
def gen_testcase(self, file_type="JSON"): def gen_testcase(self, file_type="pytest"):
logger.info(f"Start to generate testcase from {self.har_file_path}") logger.info(f"Start to generate testcase from {self.har_file_path}")
harfile = os.path.splitext(self.har_file_path)[0] harfile = os.path.splitext(self.har_file_path)[0]
output_testcase_file = "{}.{}".format(harfile, file_type.lower())
testcase = self._make_testcase() testcase = self._make_testcase()
logger.debug("prepared testcase: {}".format(testcase)) logger.debug("prepared testcase: {}".format(testcase))
if file_type == "JSON": if file_type == "JSON":
output_testcase_file = f"{harfile}.json"
utils.dump_json(testcase, output_testcase_file) utils.dump_json(testcase, output_testcase_file)
else: elif file_type == "YAML":
output_testcase_file = f"{harfile}.yml"
utils.dump_yaml(testcase, output_testcase_file) utils.dump_yaml(testcase, output_testcase_file)
else:
# default to generate pytest file
testcase["config"]["path"] = self.har_file_path
output_testcase_file = make_testcase(testcase)
format_pytest_with_black(output_testcase_file)
logger.info(f"generated testcase: {output_testcase_file}") logger.info(f"generated testcase: {output_testcase_file}")

View File

@@ -110,7 +110,7 @@ def convert_testcase_path(testcase_path: Text) -> Tuple[Text, Text]:
raw_file_name, file_suffix = os.path.splitext(os.path.basename(testcase_path)) raw_file_name, file_suffix = os.path.splitext(os.path.basename(testcase_path))
file_suffix = file_suffix.lower() file_suffix = file_suffix.lower()
if file_suffix not in [".json", ".yml", ".yaml"]: if file_suffix not in [".json", ".yml", ".yaml", ".har"]:
raise exceptions.ParamsError( raise exceptions.ParamsError(
"testcase file should have .yaml/.yml/.json suffix" "testcase file should have .yaml/.yml/.json suffix"
) )
@@ -125,7 +125,7 @@ def convert_testcase_path(testcase_path: Text) -> Tuple[Text, Text]:
return testcase_python_path, name_in_title_case return testcase_python_path, name_in_title_case
def format_pytest_with_black(python_paths: List[Text]) -> NoReturn: def format_pytest_with_black(*python_paths: Text) -> NoReturn:
logger.info("format pytest cases with black ...") logger.info("format pytest cases with black ...")
try: try:
subprocess.run(["black", *python_paths]) subprocess.run(["black", *python_paths])
@@ -231,14 +231,14 @@ def make_teststep_chain_style(teststep: Dict) -> Text:
expect = validator["expect"] expect = validator["expect"]
if isinstance(expect, Text): if isinstance(expect, Text):
expect = f'"{expect}"' expect = f'"{expect}"'
step_info += f'.assert_{assert_method}({check}, {expect})' step_info += f".assert_{assert_method}({check}, {expect})"
return f"Step({step_info})" return f"Step({step_info})"
def make_testcase( def make_testcase(
testcase: Dict, dir_path: Text = None, ref_flag: bool = False, testcase: Dict, dir_path: Text = None, ref_flag: bool = False,
) -> NoReturn: ) -> Text:
"""convert valid testcase dict to pytest file path""" """convert valid testcase dict to pytest file path"""
# ensure compatibility with testcase format v2 # ensure compatibility with testcase format v2
testcase = ensure_testcase_v3(testcase) testcase = ensure_testcase_v3(testcase)
@@ -257,7 +257,7 @@ def make_testcase(
global make_files_cache_set global make_files_cache_set
if testcase_python_path in make_files_cache_set: if testcase_python_path in make_files_cache_set:
return return testcase_python_path
config = testcase["config"] config = testcase["config"]
config["path"] = __ensure_cwd_relative(testcase_python_path) config["path"] = __ensure_cwd_relative(testcase_python_path)
@@ -317,6 +317,8 @@ def make_testcase(
if not ref_flag: if not ref_flag:
make_files_cache_set.add(__ensure_cwd_relative(testcase_python_path)) make_files_cache_set.add(__ensure_cwd_relative(testcase_python_path))
return testcase_python_path
def make_testsuite(testsuite: Dict) -> NoReturn: def make_testsuite(testsuite: Dict) -> NoReturn:
"""convert valid testsuite dict to pytest folder with testcases""" """convert valid testsuite dict to pytest folder with testcases"""
@@ -424,7 +426,7 @@ def main_make(tests_paths: List[Text]) -> List[Text]:
__make(tests_path) __make(tests_path)
testcase_path_list = list(make_files_cache_set) testcase_path_list = list(make_files_cache_set)
format_pytest_with_black(testcase_path_list) format_pytest_with_black(*testcase_path_list)
return testcase_path_list return testcase_path_list