refactor: ensure_file_path_valid

This commit is contained in:
debugtalk
2020-06-06 00:32:38 +08:00
parent 98a787d787
commit 91a8bcc78c
13 changed files with 168 additions and 256 deletions

View File

@@ -57,17 +57,6 @@ if __name__ == "__main__":
)
def __ensure_file_name(path: Text) -> Text:
""" ensure file name not startswith digit
testcases/19.json => testcases/T19.json
"""
filename = os.path.basename(path)
if filename[0] in string.digits:
path = os.path.join(os.path.dirname(path), f"T{filename}")
return path
def __ensure_absolute(path: Text) -> Text:
project_meta = load_project_meta(path)
@@ -108,32 +97,53 @@ def __ensure_testcase_module(path: Text) -> NoReturn:
f.write("# NOTICE: Generated By HttpRunner. DO NOT EDIT!\n")
def __ensure_dir_path_valid(dir_path: Text) -> Text:
# handle cases when parent directory name includes dot/hyphen/space
relative_dir_path = dir_path[len(os.getcwd()) + 1:]
relative_dir_path = (
relative_dir_path.replace(" ", "_").replace(".", "_").replace("-", "_")
)
dir_path = os.path.join(os.getcwd(), relative_dir_path)
os.makedirs(dir_path, exist_ok=True)
return dir_path
def ensure_file_path_valid(file_path: Text) -> Text:
""" ensure file path valid for pytest
Args:
file_path: absolute or relative file path
def convert_testcase_path(testcase_path: Text) -> Tuple[Text, Text]:
"""convert single YAML/JSON testcase path to python file"""
testcase_path = __ensure_file_name(testcase_path)
raw_file_name, file_suffix = os.path.splitext(os.path.basename(testcase_path))
Returns:
ensured valid absolute file path
"""
raw_file_name, file_suffix = os.path.splitext(file_path)
file_suffix = file_suffix.lower()
if file_suffix not in [".json", ".yml", ".yaml", ".har"]:
raise exceptions.ParamsError(
"testcase file should have .yaml/.yml/.json suffix"
"testcase/testsuite file should have .yaml/.yml/.json/.har suffix"
)
file_name = raw_file_name.replace(" ", "_").replace(".", "_").replace("-", "_")
testcase_dir = os.path.dirname(testcase_path)
testcase_dir = __ensure_dir_path_valid(testcase_dir)
testcase_python_path = os.path.join(testcase_dir, f"{file_name}_test.py")
if os.path.isabs(file_path):
raw_file_relative_name = raw_file_name[len(os.getcwd()) + 1 :]
else:
raw_file_relative_name = raw_file_name
path_names = []
for name in raw_file_relative_name.split(os.sep):
if name[0] in string.digits:
# ensure file name not startswith digit
# 19 => T19, 2C => T2C
name = f"T{name}"
# handle cases when directory name includes dot/hyphen/space
name = name.replace(" ", "_").replace(".", "_").replace("-", "_")
path_names.append(name)
new_file_path = os.path.join(os.getcwd(), f"{os.sep.join(path_names)}{file_suffix}")
return new_file_path
def convert_testcase_path(testcase_path: Text) -> Tuple[Text, Text]:
"""convert single YAML/JSON testcase path to python file"""
testcase_new_path = ensure_file_path_valid(testcase_path)
dir_path = os.path.dirname(testcase_new_path)
file_name, _ = os.path.splitext(os.path.basename(testcase_new_path))
testcase_python_path = os.path.join(dir_path, f"{file_name}_test.py")
# convert title case, e.g. request_with_variables => RequestWithVariables
name_in_title_case = file_name.title().replace("_", "")
@@ -273,10 +283,10 @@ def make_testcase(testcase: Dict, dir_path: Text = None) -> Text:
# validate testcase format
load_testcase(testcase)
testcase_path = __ensure_absolute(testcase["config"]["path"])
logger.info(f"start to make testcase: {testcase_path}")
testcase_abs_path = __ensure_absolute(testcase["config"]["path"])
logger.info(f"start to make testcase: {testcase_abs_path}")
testcase_python_path, testcase_cls_name = convert_testcase_path(testcase_path)
testcase_python_path, testcase_cls_name = convert_testcase_path(testcase_abs_path)
if dir_path:
testcase_python_path = os.path.join(
dir_path, os.path.basename(testcase_python_path)
@@ -293,7 +303,7 @@ def make_testcase(testcase: Dict, dir_path: Text = None) -> Text:
config.setdefault("variables", {})
if isinstance(config["variables"], Text):
# get variables by function, e.g. ${get_variables()}
project_meta = load_project_meta(testcase_path)
project_meta = load_project_meta(testcase_abs_path)
config["variables"] = parse_data(
config["variables"], {}, project_meta.functions
)
@@ -327,7 +337,7 @@ def make_testcase(testcase: Dict, dir_path: Text = None) -> Text:
data = {
"version": __version__,
"testcase_path": __ensure_cwd_relative(testcase_path),
"testcase_path": __ensure_cwd_relative(testcase_abs_path),
"class_name": f"TestCase{testcase_cls_name}",
"imports_list": imports_list,
"config_chain_style": make_config_chain_style(config),
@@ -337,6 +347,10 @@ def make_testcase(testcase: Dict, dir_path: Text = None) -> Text:
}
content = __TEMPLATE__.render(data)
# ensure new file's directory exists
dir_path = os.path.dirname(testcase_python_path)
os.makedirs(dir_path, exist_ok=True)
with open(testcase_python_path, "w", encoding="utf-8") as f:
f.write(content)
@@ -354,7 +368,7 @@ def make_testsuite(testsuite: Dict) -> NoReturn:
load_testsuite(testsuite)
testsuite_config = testsuite["config"]
testsuite_path = __ensure_absolute(testsuite_config["path"])
testsuite_path = testsuite_config["path"]
testsuite_variables = testsuite_config.get("variables", {})
if isinstance(testsuite_variables, Text):
@@ -367,15 +381,10 @@ def make_testsuite(testsuite: Dict) -> NoReturn:
logger.info(f"start to make testsuite: {testsuite_path}")
# create directory with testsuite file name, put its testcases under this directory
testsuite_file_name, file_suffix = os.path.splitext(testsuite_path)
file_suffix = file_suffix.lower()
if file_suffix not in [".json", ".yml", ".yaml", ".har"]:
raise exceptions.ParamsError(
"testsuite file should have .yaml/.yml/.json suffix"
)
testsuite_dir = __ensure_dir_path_valid(testsuite_file_name)
testsuite_path = ensure_file_path_valid(testsuite_path)
testsuite_dir, file_suffix = os.path.splitext(testsuite_path)
# demo_testsuite.yml => demo_testsuite_yml
testsuite_dir = f"{testsuite_dir}_{file_suffix.lstrip('.')}"
for testcase in testsuite["testcases"]:
# get referenced testcase content