Skip to content

Commit

Permalink
feature: #1160 add support for pytest fixture as param
Browse files Browse the repository at this point in the history
  • Loading branch information
zhengtong0898 committed Feb 7, 2022
1 parent 401aaf6 commit ce9d761
Show file tree
Hide file tree
Showing 7 changed files with 107 additions and 10 deletions.
4 changes: 4 additions & 0 deletions examples/postman_echo/debugtalk.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,7 @@ def get_app_version():

def calculate_two_nums(a, b=1):
return [a + b, b - a]


def get_session_fixture(session_fixture):
return session_fixture[0]["name"]
2 changes: 1 addition & 1 deletion examples/postman_echo/request_methods/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def session_fixture(request):

logger.debug(f"collected {total_testcases_num} testcases: {testcases}")

yield
yield testcases

logger.debug(f"teardown task fixture")

Expand Down
15 changes: 15 additions & 0 deletions examples/postman_echo/request_methods/request_with_fixtures.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
config:
name: "request with fixture: session fixture"
base_url: "https://postman-echo.com"
fixture_as_param: ["session_fixture"]

teststeps:
-
name: get with params
request:
method: GET
url: /get
params:
info: "ip"
headers:
User-Agent: HttpRunner/${get_httprunner_version()}/${get_session_fixture($session_fixture)}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# NOTE: Generated By HttpRunner v3.1.6
# FROM: request_methods/request_with_fixtures.yml


import debugtalk
import pytest


import allure


from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase


class TestCaseRequestWithFixtures(HttpRunner):
@allure.title("request teststep: with error retry")
def test_start(self, session_fixture):
scope, fixtures = locals(), ["session_fixture"]
values = map(lambda x: scope.get(x), fixtures)
super().test_start(fixtures=dict(zip(fixtures, values)))

config = Config("request teststep: with error retry").base_url(
"https://postman-echo.com"
)

teststeps = [
Step(
RunRequest("get with params")
.get("/get")
.with_params(**{"info": "ip"})
.with_headers(
**{
"User-Agent": "HttpRunner/${get_httprunner_version()}/${get_session_fixture($session_fixture)}"
}
)
),
]


if __name__ == "__main__":
TestCaseRequestWithFixtures().test_start()
42 changes: 39 additions & 3 deletions httprunner/make.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,16 +523,42 @@ def make_pytest_marks(config: Dict) -> (Text, Text):
# https://docs.pytest.org/en/6.2.x/mark.html
# https://docs.pytest.org/en/6.2.x/reference.html
result = ""
default_test_start = " def test_start(self): \n super().test_start()\n"
parameters_test_start = " def test_start(self, param): \n super().test_start(param)\n"
default_test_start = (
" def test_start(self): \n"
" super().test_start() \n"
)
fixtures_test_start = (
" def test_start(self, {fixture_str}): \n"
" scope, fixtures = locals(), {fixture_list} \n"
" values = map(lambda x: scope.get(x), fixtures) \n"
" super().test_start(fixtures=dict(zip(fixtures, values))) \n"
)
parameters_test_start = (
" def test_start(self, param): \n"
" super().test_start(param=param) \n"
)
both_test_start = (
" def test_start(self, {fixture_str}, param): \n"
" scope, fixtures = locals(), {fixture_list} \n"
" values = map(lambda x: scope.get(x), fixtures) \n"
" super().test_start(fixtures=dict(zip({fixtures}, values)), param=param) \n"
)

# marks
# keep yaml load order, refer:
# https://stackoverflow.com/a/47881325
# https://mail.python.org/pipermail/python-dev/2016-September/146327.html
fixture_list = []
fixtures_exist = False
parameters_exist = False
for key, param in config.items():

if key == "fixture_as_param":
errmsg = f"fixture_as_param type should be List[str], got ({type(param)}, {param})"
assert isinstance(param, list), errmsg
fixture_list.extend(param)
fixtures_exist = True

if key == "filterwarnings":
result += f" @pytest.mark.filterwarnings({param})\n"

Expand Down Expand Up @@ -597,7 +623,17 @@ def make_pytest_marks(config: Dict) -> (Text, Text):
return result

# test_start
if parameters_exist:
if parameters_exist and fixtures_exist:
result += both_test_start.format(
fixture_str=", ".join(fixture_list),
fixture_list=fixture_list
)
elif fixtures_exist:
result += fixtures_test_start.format(
fixture_str=", ".join(fixture_list),
fixture_list=fixture_list
)
elif parameters_exist:
result += parameters_test_start
else:
result += default_test_start
Expand Down
2 changes: 2 additions & 0 deletions httprunner/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ class TConfig(BaseModel):
description: Text = "" # allure description
links: List[Dict] = [] # allure links

fixture_as_param: List[Text] = [] # pytest fixture as param


class TRequest(BaseModel):
"""requests.Request model"""
Expand Down
11 changes: 5 additions & 6 deletions httprunner/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ def get_summary(self) -> TestCaseSummary:
step_datas=self.__step_datas,
)

def test_start(self, param: Dict = None) -> "HttpRunner":
def test_start(self, fixtures: Dict = None, param: Dict = None) -> "HttpRunner":
"""main entrance, discovered by pytest"""
self.__init_tests__()
self.__project_meta = self.__project_meta or load_project_meta(
Expand All @@ -469,12 +469,11 @@ def test_start(self, param: Dict = None) -> "HttpRunner":
log_handler = logger.add(self.__log_path, level="DEBUG")

# parse config name
config_variables = self.__config.variables
if param:
config_variables.update(param)
config_variables.update(self.__session_variables)
self.__config.variables.update(self.__session_variables)
self.__config.variables.update(param or {})
self.__config.variables.update(fixtures or {})
self.__config.name = parse_data(
self.__config.name, config_variables, self.__project_meta.functions
self.__config.name, self.__config.variables, self.__project_meta.functions
)

logger.info(
Expand Down

0 comments on commit ce9d761

Please sign in to comment.