feat: step setup hook

This commit is contained in:
debugtalk
2020-06-07 18:06:42 +08:00
parent 2a81937bc8
commit d991708439
5 changed files with 41 additions and 18 deletions

View File

@@ -1,4 +1,4 @@
# NOTE: Generated By HttpRunner v3.0.9 # NOTE: Generated By HttpRunner v3.0.10
# FROM: examples/httpbin/hooks.yml # FROM: examples/httpbin/hooks.yml
from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase
@@ -11,6 +11,8 @@ class TestCaseHooks(HttpRunner):
Step( Step(
RunRequest("headers") RunRequest("headers")
.with_variables(**{"a": 123}) .with_variables(**{"a": 123})
.setup_hook("${setup_hook_add_kwargs($request)}")
.setup_hook("${setup_hook_remove_kwargs($request)}")
.get("/headers") .get("/headers")
.validate() .validate()
.assert_equal("status_code", 200) .assert_equal("status_code", 200)

View File

@@ -228,6 +228,17 @@ def make_teststep_chain_style(teststep: Dict) -> Text:
variables = teststep["variables"] variables = teststep["variables"]
step_info += f".with_variables(**{variables})" step_info += f".with_variables(**{variables})"
if "setup_hooks" in teststep:
setup_hooks = teststep["setup_hooks"]
for hook in setup_hooks:
if isinstance(hook, Text):
step_info += f'.setup_hook("{hook}")'
elif isinstance(hook, Dict) and len(hook) == 1:
assign_var_name, hook_content = list(hook.items())[0]
step_info += f'.setup_hook("{hook}", "{assign_var_name}")'
else:
raise exceptions.TestCaseFormatError(f"Invalid setup hook: {hook}")
if teststep.get("request"): if teststep.get("request"):
step_info += make_request_chain_style(teststep["request"]) step_info += make_request_chain_style(teststep["request"])
elif teststep.get("testcase"): elif teststep.get("testcase"):

View File

@@ -15,7 +15,7 @@ FunctionsMapping = Dict[Text, Callable]
Headers = Dict[Text, Text] Headers = Dict[Text, Text]
Cookies = Dict[Text, Text] Cookies = Dict[Text, Text]
Verify = bool Verify = bool
Hooks = Union[List[Text], Dict[Text, Text]] Hooks = List[Union[Text, Dict[Text, Text]]]
Export = List[Text] Export = List[Text]
Validators = List[Dict] Validators = List[Dict]
Env = Dict[Text, Any] Env = Dict[Text, Any]

View File

@@ -93,12 +93,12 @@ class HttpRunner(object):
""" call hook actions. """ call hook actions.
Args: Args:
hooks: each action in actions list maybe in two format. hooks (list): each hook in hooks list maybe in two format.
format1 (dict): assignment, the value returned by hook function will be assigned to variable. format1 (str): only call hook functions.
{"var": "${func()}"}
format2 (str): only call hook functions.
${func()} ${func()}
format2 (dict): assignment, the value returned by hook function will be assigned to variable.
{"var": "${func()}"}
step_variables: current step variables to call hook, include two special variables step_variables: current step variables to call hook, include two special variables
@@ -110,9 +110,18 @@ class HttpRunner(object):
""" """
logger.debug(f"call {hook_type} hook actions.") logger.debug(f"call {hook_type} hook actions.")
if isinstance(hooks, Dict): if not isinstance(hooks, List):
# format 1: {"var": "${func()}"} logger.error(f"Invalid hooks format: {hooks}")
for var_name, hook_content in hooks.items(): return
for hook in hooks:
if isinstance(hook, Text):
# format 1: ["${func()}"]
logger.debug(f"call hook function: {hook}")
parse_data(hook, step_variables, self.__project_meta.functions)
elif isinstance(hook, Dict) and len(hook) == 1:
# format 2: {"var": "${func()}"}
var_name, hook_content = list(hook.items())[0]
hook_content_eval = parse_data( hook_content_eval = parse_data(
hook_content, step_variables, self.__project_meta.functions hook_content, step_variables, self.__project_meta.functions
) )
@@ -121,15 +130,8 @@ class HttpRunner(object):
) )
logger.debug(f"assign variable: {var_name} = {hook_content_eval}") logger.debug(f"assign variable: {var_name} = {hook_content_eval}")
step_variables[var_name] = hook_content_eval step_variables[var_name] = hook_content_eval
else:
elif isinstance(hooks, List): logger.error(f"Invalid hook format: {hook}")
# format 2: ["${func()}"]
for hook in hooks:
logger.debug(f"call hook function: {hook}")
parse_data(hook, step_variables, self.__project_meta.functions)
else:
logger.warning(f"Invalid hooks format: {hooks}")
def __run_step_request(self, step: TStep) -> StepData: def __run_step_request(self, step: TStep) -> StepData:
"""run teststep: request""" """run teststep: request"""

View File

@@ -286,6 +286,14 @@ class RunRequest(object):
self.__step_context.variables.update(variables) self.__step_context.variables.update(variables)
return self return self
def setup_hook(self, hook: Text, assign_var_name: Text = None) -> "RunRequest":
if assign_var_name:
self.__step_context.setup_hooks.append({assign_var_name: hook})
else:
self.__step_context.setup_hooks.append(hook)
return self
def get(self, url: Text) -> RequestWithOptionalArgs: def get(self, url: Text) -> RequestWithOptionalArgs:
self.__step_context.request = TRequest(method=MethodEnum.GET, url=url) self.__step_context.request = TRequest(method=MethodEnum.GET, url=url)
return RequestWithOptionalArgs(self.__step_context) return RequestWithOptionalArgs(self.__step_context)