rename excpetion module to exceptions

This commit is contained in:
httprunner
2018-07-25 10:52:16 +08:00
parent e6a834c6c6
commit 3c17aa649c
15 changed files with 94 additions and 94 deletions

View File

@@ -13,7 +13,7 @@ import string
import time import time
from httprunner.compat import basestring, builtin_str, integer_types, str from httprunner.compat import basestring, builtin_str, integer_types, str
from httprunner.exception import ParamsError from httprunner.exceptions import ParamsError
from requests_toolbelt import MultipartEncoder from requests_toolbelt import MultipartEncoder

View File

@@ -6,7 +6,7 @@ import time
import requests import requests
import urllib3 import urllib3
from httprunner import logger from httprunner import logger
from httprunner.exception import ParamsError from httprunner.exceptions import ParamsError
from requests import Request, Response from requests import Request, Response
from requests.exceptions import (InvalidSchema, InvalidURL, MissingSchema, from requests.exceptions import (InvalidSchema, InvalidURL, MissingSchema,
RequestException) RequestException)

View File

@@ -5,7 +5,7 @@ import os
import re import re
import sys import sys
from httprunner import exception, logger, testcase, utils from httprunner import exceptions, logger, testcase, utils
from httprunner.compat import OrderedDict from httprunner.compat import OrderedDict
@@ -204,10 +204,10 @@ class Context(object):
try: try:
# format 4/5 # format 4/5
check_value = resp_obj.extract_field(check_item) check_value = resp_obj.extract_field(check_item)
except exception.ParseResponseFailure: except exceptions.ParseResponseFailure:
msg = "failed to extract check item from response!\n" msg = "failed to extract check item from response!\n"
msg += "response content: {}".format(resp_obj.content) msg += "response content: {}".format(resp_obj.content)
raise exception.ParseResponseFailure(msg) raise exceptions.ParseResponseFailure(msg)
validator["check_value"] = check_value validator["check_value"] = check_value
@@ -227,7 +227,7 @@ class Context(object):
validate_func = self.testcase_parser.get_bind_function(comparator) validate_func = self.testcase_parser.get_bind_function(comparator)
if not validate_func: if not validate_func:
raise exception.FunctionNotFound("comparator not found: {}".format(comparator)) raise exceptions.FunctionNotFound("comparator not found: {}".format(comparator))
check_item = validator_dict["check"] check_item = validator_dict["check"]
check_value = validator_dict["check_value"] check_value = validator_dict["check_value"]
@@ -235,7 +235,7 @@ class Context(object):
if (check_value is None or expect_value is None) \ if (check_value is None or expect_value is None) \
and comparator not in ["is", "eq", "equals", "=="]: and comparator not in ["is", "eq", "equals", "=="]:
raise exception.ParamsError("Null value can only be compared with comparator: eq/equals/==") raise exceptions.ParamsError("Null value can only be compared with comparator: eq/equals/==")
validate_msg = "validate: {} {} {}({})".format( validate_msg = "validate: {} {} {}({})".format(
check_item, check_item,
@@ -260,7 +260,7 @@ class Context(object):
) )
logger.log_error(validate_msg) logger.log_error(validate_msg)
validator_dict["check_result"] = "fail" validator_dict["check_result"] = "fail"
raise exception.ValidationFailure(validate_msg) raise exceptions.ValidationFailure(validate_msg)
def validate(self, validators, resp_obj): def validate(self, validators, resp_obj):
""" make validations """ make validations
@@ -277,10 +277,10 @@ class Context(object):
try: try:
self.do_validation(evaluated_validator) self.do_validation(evaluated_validator)
except exception.ValidationFailure: except exceptions.ValidationFailure:
validate_pass = False validate_pass = False
self.evaluated_validators.append(evaluated_validator) self.evaluated_validators.append(evaluated_validator)
if not validate_pass: if not validate_pass:
raise exception.ValidationFailure raise exceptions.ValidationFailure

View File

@@ -3,7 +3,7 @@
import json import json
import re import re
from httprunner import exception, logger, testcase, utils from httprunner import exceptions, logger, testcase, utils
from httprunner.compat import OrderedDict, basestring from httprunner.compat import OrderedDict, basestring
from requests.structures import CaseInsensitiveDict from requests.structures import CaseInsensitiveDict
from requests.models import PreparedRequest from requests.models import PreparedRequest
@@ -31,7 +31,7 @@ class ResponseObject(object):
except AttributeError: except AttributeError:
err_msg = "ResponseObject does not have attribute: {}".format(key) err_msg = "ResponseObject does not have attribute: {}".format(key)
logger.log_error(err_msg) logger.log_error(err_msg)
raise exception.ParamsError(err_msg) raise exceptions.ParamsError(err_msg)
def _extract_field_with_regex(self, field): def _extract_field_with_regex(self, field):
""" extract field from response content with regex. """ extract field from response content with regex.
@@ -48,7 +48,7 @@ class ResponseObject(object):
err_msg += u"response content: {}\n".format(self.content) err_msg += u"response content: {}\n".format(self.content)
err_msg += u"regex: {}\n".format(field) err_msg += u"regex: {}\n".format(field)
logger.log_error(err_msg) logger.log_error(err_msg)
raise exception.ParamsError(err_msg) raise exceptions.ParamsError(err_msg)
return matched.group(1) return matched.group(1)
@@ -81,7 +81,7 @@ class ResponseObject(object):
err_msg += u"cookies: {}\n".format(cookies) err_msg += u"cookies: {}\n".format(cookies)
err_msg += u"attribute: {}".format(sub_query) err_msg += u"attribute: {}".format(sub_query)
logger.log_error(err_msg) logger.log_error(err_msg)
raise exception.ParamsError(err_msg) raise exceptions.ParamsError(err_msg)
elif top_query == "elapsed": elif top_query == "elapsed":
if sub_query in ["days", "seconds", "microseconds"]: if sub_query in ["days", "seconds", "microseconds"]:
return getattr(self.elapsed, sub_query) return getattr(self.elapsed, sub_query)
@@ -91,14 +91,14 @@ class ResponseObject(object):
err_msg = "{}: {} is not valid timedelta attribute.\n".format(field, sub_query) err_msg = "{}: {} is not valid timedelta attribute.\n".format(field, sub_query)
err_msg += "elapsed only support attributes: days, seconds, microseconds, total_seconds.\n" err_msg += "elapsed only support attributes: days, seconds, microseconds, total_seconds.\n"
logger.log_error(err_msg) logger.log_error(err_msg)
raise exception.ParamsError(err_msg) raise exceptions.ParamsError(err_msg)
try: try:
top_query_content = getattr(self, top_query) top_query_content = getattr(self, top_query)
except AttributeError: except AttributeError:
err_msg = u"Failed to extract attribute from response object: resp_obj.{}".format(top_query) err_msg = u"Failed to extract attribute from response object: resp_obj.{}".format(top_query)
logger.log_error(err_msg) logger.log_error(err_msg)
raise exception.ParamsError(err_msg) raise exceptions.ParamsError(err_msg)
if sub_query: if sub_query:
if not isinstance(top_query_content, (dict, CaseInsensitiveDict, list)): if not isinstance(top_query_content, (dict, CaseInsensitiveDict, list)):
@@ -111,12 +111,12 @@ class ResponseObject(object):
top_query_content = top_query_content.__dict__ top_query_content = top_query_content.__dict__
else: else:
top_query_content = json.loads(top_query_content) top_query_content = json.loads(top_query_content)
except exception.JSONDecodeError: except exceptions.JSONDecodeError:
err_msg = u"Failed to extract data with delimiter!\n" err_msg = u"Failed to extract data with delimiter!\n"
err_msg += u"response content: {}\n".format(self.content) err_msg += u"response content: {}\n".format(self.content)
err_msg += u"regex: {}\n".format(field) err_msg += u"regex: {}\n".format(field)
logger.log_error(err_msg) logger.log_error(err_msg)
raise exception.ParamsError(err_msg) raise exceptions.ParamsError(err_msg)
# e.g. key: resp_headers_content_type, sub_query = "content-type" # e.g. key: resp_headers_content_type, sub_query = "content-type"
return utils.query_json(top_query_content, sub_query) return utils.query_json(top_query_content, sub_query)
@@ -129,7 +129,7 @@ class ResponseObject(object):
err_msg += u"response content: {}\n".format(self.content) err_msg += u"response content: {}\n".format(self.content)
err_msg += u"extract: {}\n".format(field) err_msg += u"extract: {}\n".format(field)
logger.log_error(err_msg) logger.log_error(err_msg)
raise exception.ParamsError(err_msg) raise exceptions.ParamsError(err_msg)
def extract_field(self, field): def extract_field(self, field):
""" extract value from requests.Response. """ extract value from requests.Response.
@@ -146,7 +146,7 @@ class ResponseObject(object):
logger.log_debug(msg) logger.log_debug(msg)
# TODO: unify ParseResponseFailure type # TODO: unify ParseResponseFailure type
except (exception.ParseResponseFailure, TypeError): except (exceptions.ParseResponseFailure, TypeError):
logger.log_error("failed to extract field: {}".format(field)) logger.log_error("failed to extract field: {}".format(field))
raise raise
@@ -172,7 +172,7 @@ class ResponseObject(object):
for key, field in extract_binds_order_dict.items(): for key, field in extract_binds_order_dict.items():
if not isinstance(field, basestring): if not isinstance(field, basestring):
raise exception.ParamsError("invalid extractors in testcase!") raise exceptions.ParamsError("invalid extractors in testcase!")
extracted_variables_mapping[key] = self.extract_field(field) extracted_variables_mapping[key] = self.extract_field(field)

View File

@@ -2,7 +2,7 @@
from unittest.case import SkipTest from unittest.case import SkipTest
from httprunner import exception, logger, response, utils from httprunner import exceptions, logger, response, utils
from httprunner.client import HttpSession from httprunner.client import HttpSession
from httprunner.context import Context from httprunner.context import Context
@@ -154,7 +154,7 @@ class Runner(object):
method = parsed_request.pop('method') method = parsed_request.pop('method')
group_name = parsed_request.pop("group", None) group_name = parsed_request.pop("group", None)
except KeyError: except KeyError:
raise exception.ParamsError("URL or METHOD missed!") raise exceptions.ParamsError("URL or METHOD missed!")
logger.log_info("{method} {url}".format(method=method, url=url)) logger.log_info("{method} {url}".format(method=method, url=url))
logger.log_debug("request kwargs(raw): {kwargs}".format(kwargs=parsed_request)) logger.log_debug("request kwargs(raw): {kwargs}".format(kwargs=parsed_request))
@@ -183,8 +183,8 @@ class Runner(object):
validators = testcase_dict.get("validate", []) or testcase_dict.get("validators", []) validators = testcase_dict.get("validate", []) or testcase_dict.get("validators", [])
try: try:
self.context.validate(validators, resp_obj) self.context.validate(validators, resp_obj)
except (exception.ParamsError, exception.ResponseFailure, \ except (exceptions.ParamsError, exceptions.ResponseFailure, \
exception.ValidationFailure, exception.ParseResponseFailure): exceptions.ValidationFailure, exceptions.ParseResponseFailure):
# log request # log request
err_req_msg = "request: \n" err_req_msg = "request: \n"
err_req_msg += "headers: {}\n".format(parsed_request.pop("headers", {})) err_req_msg += "headers: {}\n".format(parsed_request.pop("headers", {}))

View File

@@ -4,7 +4,7 @@ import copy
import sys import sys
import unittest import unittest
from httprunner import exception, logger, runner, testcase, utils from httprunner import exceptions, logger, runner, testcase, utils
from httprunner.compat import is_py3 from httprunner.compat import is_py3
from httprunner.report import (HtmlTestResult, get_platform, get_summary, from httprunner.report import (HtmlTestResult, get_platform, get_summary,
render_html_report) render_html_report)
@@ -106,7 +106,7 @@ class TestSuite(unittest.TestSuite):
self.testcase_parser.update_binded_variables(variables) self.testcase_parser.update_binded_variables(variables)
try: try:
testcase_name = self.testcase_parser.eval_content_with_bindings(testcase_dict["name"]) testcase_name = self.testcase_parser.eval_content_with_bindings(testcase_dict["name"])
except (AssertionError, exception.ParamsError): except (AssertionError, exceptions.ParamsError):
logger.log_warning("failed to eval testcase name: {}".format(testcase_dict["name"])) logger.log_warning("failed to eval testcase name: {}".format(testcase_dict["name"]))
testcase_name = testcase_dict["name"] testcase_name = testcase_dict["name"]
self.test_runner_list.append((test_runner, variables)) self.test_runner_list.append((test_runner, variables))
@@ -189,7 +189,7 @@ def init_test_suites(path_or_testsets, mapping=None, http_client_session=None):
mapping = mapping or {} mapping = mapping or {}
if not testsets: if not testsets:
raise exception.TestcaseNotFound raise exceptions.TestcaseNotFound
if isinstance(testsets, dict): if isinstance(testsets, dict):
testsets = [testsets] testsets = [testsets]
@@ -236,7 +236,7 @@ class HttpRunner(object):
""" """
try: try:
test_suite_list = init_test_suites(path_or_testsets, mapping) test_suite_list = init_test_suites(path_or_testsets, mapping)
except exception.TestcaseNotFound: except exceptions.TestcaseNotFound:
logger.log_error("Testcases not found in {}".format(path_or_testsets)) logger.log_error("Testcases not found in {}".format(path_or_testsets))
sys.exit(1) sys.exit(1)
@@ -301,7 +301,7 @@ class LocustTask(object):
for test in test_suite: for test in test_suite:
try: try:
test.runTest() test.runTest()
except exception.MyBaseError as ex: except exceptions.MyBaseError as ex:
from locust.events import request_failure from locust.events import request_failure
request_failure.fire( request_failure.fire(
request_type=test.testcase_dict.get("request", {}).get("method"), request_type=test.testcase_dict.get("request", {}).get("method"),

View File

@@ -9,7 +9,7 @@ import os
import random import random
import re import re
from httprunner import exception, logger, utils from httprunner import exceptions, logger, utils
from httprunner.compat import OrderedDict, basestring, numeric_types from httprunner.compat import OrderedDict, basestring, numeric_types
from httprunner.utils import FileUtils from httprunner.utils import FileUtils
@@ -77,7 +77,7 @@ def parse_function(content):
""" """
matched = function_regexp_compile.match(content) matched = function_regexp_compile.match(content)
if not matched: if not matched:
raise exception.FunctionNotFound("{} not found!".format(content)) raise exceptions.FunctionNotFound("{} not found!".format(content))
function_meta = { function_meta = {
"func_name": matched.group(1), "func_name": matched.group(1),
@@ -126,7 +126,7 @@ class TestcaseLoader(object):
for suite_file in FileUtils.load_folder_files(suite_def_folder): for suite_file in FileUtils.load_folder_files(suite_def_folder):
suite = TestcaseLoader.load_test_file(suite_file) suite = TestcaseLoader.load_test_file(suite_file)
if "def" not in suite["config"]: if "def" not in suite["config"]:
raise exception.ParamsError("def missed in suite file: {}!".format(suite_file)) raise exceptions.ParamsError("def missed in suite file: {}!".format(suite_file))
call_func = suite["config"]["def"] call_func = suite["config"]["def"]
function_meta = parse_function(call_func) function_meta = parse_function(call_func)
@@ -156,15 +156,15 @@ class TestcaseLoader(object):
""" """
api_items = FileUtils.load_file(file_path) api_items = FileUtils.load_file(file_path)
if not isinstance(api_items, list): if not isinstance(api_items, list):
raise exception.FileFormatError("API format error: {}".format(file_path)) raise exceptions.FileFormatError("API format error: {}".format(file_path))
for api_item in api_items: for api_item in api_items:
if not isinstance(api_item, dict) or len(api_item) != 1: if not isinstance(api_item, dict) or len(api_item) != 1:
raise exception.FileFormatError("API format error: {}".format(file_path)) raise exceptions.FileFormatError("API format error: {}".format(file_path))
key, api_dict = api_item.popitem() key, api_dict = api_item.popitem()
if key != "api" or not isinstance(api_dict, dict) or "def" not in api_dict: if key != "api" or not isinstance(api_dict, dict) or "def" not in api_dict:
raise exception.FileFormatError("API format error: {}".format(file_path)) raise exceptions.FileFormatError("API format error: {}".format(file_path))
api_def = api_dict.pop("def") api_def = api_dict.pop("def")
function_meta = parse_function(api_def) function_meta = parse_function(api_def)
@@ -218,11 +218,11 @@ class TestcaseLoader(object):
} }
for item in FileUtils.load_file(file_path): for item in FileUtils.load_file(file_path):
if not isinstance(item, dict) or len(item) != 1: if not isinstance(item, dict) or len(item) != 1:
raise exception.FileFormatError("Testcase format error: {}".format(file_path)) raise exceptions.FileFormatError("Testcase format error: {}".format(file_path))
key, test_block = item.popitem() key, test_block = item.popitem()
if not isinstance(test_block, dict): if not isinstance(test_block, dict):
raise exception.FileFormatError("Testcase format error: {}".format(file_path)) raise exceptions.FileFormatError("Testcase format error: {}".format(file_path))
if key == "config": if key == "config":
testset["config"].update(test_block) testset["config"].update(test_block)
@@ -261,7 +261,7 @@ class TestcaseLoader(object):
def_args = block.get("function_meta").get("args", []) def_args = block.get("function_meta").get("args", [])
if len(call_args) != len(def_args): if len(call_args) != len(def_args):
raise exception.ParamsError("call args mismatch defined args!") raise exceptions.ParamsError("call args mismatch defined args!")
args_mapping = {} args_mapping = {}
for index, item in enumerate(def_args): for index, item in enumerate(def_args):
@@ -289,10 +289,10 @@ class TestcaseLoader(object):
if not block: if not block:
err_msg = "{} not found!".format(name) err_msg = "{} not found!".format(name)
if ref_type == "api": if ref_type == "api":
raise exception.ApiNotFound(err_msg) raise exceptions.ApiNotFound(err_msg)
else: else:
# ref_type == "suite": # ref_type == "suite":
raise exception.SuiteNotFound(err_msg) raise exceptions.SuiteNotFound(err_msg)
return block return block
@@ -380,7 +380,7 @@ class TestcaseLoader(object):
testcases_list = [testset] testcases_list = [testset]
else: else:
testcases_list = [] testcases_list = []
except exception.FileFormatError: except exceptions.FileFormatError:
testcases_list = [] testcases_list = []
else: else:
@@ -407,7 +407,7 @@ def parse_validator(validator):
} }
""" """
if not isinstance(validator, dict): if not isinstance(validator, dict):
raise exception.ParamsError("invalid validator: {}".format(validator)) raise exceptions.ParamsError("invalid validator: {}".format(validator))
if "check" in validator and len(validator) > 1: if "check" in validator and len(validator) > 1:
# format1 # format1
@@ -418,7 +418,7 @@ def parse_validator(validator):
elif "expected" in validator: elif "expected" in validator:
expect_value = validator.get("expected") expect_value = validator.get("expected")
else: else:
raise exception.ParamsError("invalid validator: {}".format(validator)) raise exceptions.ParamsError("invalid validator: {}".format(validator))
comparator = validator.get("comparator", "eq") comparator = validator.get("comparator", "eq")
@@ -428,12 +428,12 @@ def parse_validator(validator):
compare_values = validator[comparator] compare_values = validator[comparator]
if not isinstance(compare_values, list) or len(compare_values) != 2: if not isinstance(compare_values, list) or len(compare_values) != 2:
raise exception.ParamsError("invalid validator: {}".format(validator)) raise exceptions.ParamsError("invalid validator: {}".format(validator))
check_item, expect_value = compare_values check_item, expect_value = compare_values
else: else:
raise exception.ParamsError("invalid validator: {}".format(validator)) raise exceptions.ParamsError("invalid validator: {}".format(validator))
return { return {
"check": check_item, "check": check_item,
@@ -711,7 +711,7 @@ def parse_parameters(parameters, testset_path=None):
# e.g. [{'app_version': '2.8.5'}, {'app_version': '2.8.6'}] # e.g. [{'app_version': '2.8.5'}, {'app_version': '2.8.6'}]
# e.g. [{"username": "user1", "password": "111111"}, {"username": "user2", "password": "222222"}] # e.g. [{"username": "user1", "password": "111111"}, {"username": "user2", "password": "222222"}]
if not isinstance(parsed_parameter_content, list): if not isinstance(parsed_parameter_content, list):
raise exception.ParamsError("parameters syntax error!") raise exceptions.ParamsError("parameters syntax error!")
parameter_content_list = [ parameter_content_list = [
# get subset by parameter name # get subset by parameter name
@@ -769,13 +769,13 @@ class TestcaseParser(object):
if item_name in self.variables: if item_name in self.variables:
return self.variables[item_name] return self.variables[item_name]
else: else:
raise exception.ParamsError("bind item should only be function or variable.") raise exceptions.ParamsError("bind item should only be function or variable.")
try: try:
assert self.file_path is not None assert self.file_path is not None
return utils.search_conf_item(self.file_path, item_type, item_name) return utils.search_conf_item(self.file_path, item_type, item_name)
except (AssertionError, exception.FunctionNotFound): except (AssertionError, exceptions.FunctionNotFound):
raise exception.ParamsError( raise exceptions.ParamsError(
"{} is not defined in bind {}s!".format(item_name, item_type)) "{} is not defined in bind {}s!".format(item_name, item_type))
def get_bind_function(self, func_name): def get_bind_function(self, func_name):

View File

@@ -16,7 +16,7 @@ import types
from datetime import datetime from datetime import datetime
import yaml import yaml
from httprunner import exception, logger from httprunner import exceptions, logger
from httprunner.compat import OrderedDict, is_py2, is_py3 from httprunner.compat import OrderedDict, is_py2, is_py3
from requests.structures import CaseInsensitiveDict from requests.structures import CaseInsensitiveDict
@@ -54,13 +54,13 @@ class FileUtils(object):
# testcase file content is empty # testcase file content is empty
err_msg = u"Testcase file content is empty: {}".format(file_path) err_msg = u"Testcase file content is empty: {}".format(file_path)
logger.log_error(err_msg) logger.log_error(err_msg)
raise exception.FileFormatError(err_msg) raise exceptions.FileFormatError(err_msg)
elif not isinstance(content, (list, dict)): elif not isinstance(content, (list, dict)):
# testcase file content does not match testcase format # testcase file content does not match testcase format
err_msg = u"Testcase file content format invalid: {}".format(file_path) err_msg = u"Testcase file content format invalid: {}".format(file_path)
logger.log_error(err_msg) logger.log_error(err_msg)
raise exception.FileFormatError(err_msg) raise exceptions.FileFormatError(err_msg)
@staticmethod @staticmethod
def _load_yaml_file(yaml_file): def _load_yaml_file(yaml_file):
@@ -78,10 +78,10 @@ class FileUtils(object):
with io.open(json_file, encoding='utf-8') as data_file: with io.open(json_file, encoding='utf-8') as data_file:
try: try:
json_content = json.load(data_file) json_content = json.load(data_file)
except exception.JSONDecodeError: except exceptions.JSONDecodeError:
err_msg = u"JSONDecodeError: JSON file format error: {}".format(json_file) err_msg = u"JSONDecodeError: JSON file format error: {}".format(json_file)
logger.log_error(err_msg) logger.log_error(err_msg)
raise exception.FileFormatError(err_msg) raise exceptions.FileFormatError(err_msg)
FileUtils._check_format(json_file, json_content) FileUtils._check_format(json_file, json_content)
return json_content return json_content
@@ -117,7 +117,7 @@ class FileUtils(object):
@staticmethod @staticmethod
def load_file(file_path): def load_file(file_path):
if not os.path.isfile(file_path): if not os.path.isfile(file_path):
raise exception.FileNotFound("{} does not exist.".format(file_path)) raise exceptions.FileNotFound("{} does not exist.".format(file_path))
file_suffix = os.path.splitext(file_path)[1].lower() file_suffix = os.path.splitext(file_path)[1].lower()
if file_suffix == '.json': if file_suffix == '.json':
@@ -190,7 +190,7 @@ def query_json(json_content, query, delimiter='.'):
@return queried result @return queried result
""" """
if json_content == "": if json_content == "":
raise exception.ResponseFailure("response content is empty!") raise exceptions.ResponseFailure("response content is empty!")
try: try:
for key in query.split(delimiter): for key in query.split(delimiter):
@@ -199,10 +199,10 @@ def query_json(json_content, query, delimiter='.'):
elif isinstance(json_content, (dict, CaseInsensitiveDict)): elif isinstance(json_content, (dict, CaseInsensitiveDict)):
json_content = json_content[key] json_content = json_content[key]
else: else:
raise exception.ParseResponseFailure( raise exceptions.ParseResponseFailure(
"response content is in text format! failed to query key {}!".format(key)) "response content is in text format! failed to query key {}!".format(key))
except (KeyError, ValueError, IndexError): except (KeyError, ValueError, IndexError):
raise exception.ParseResponseFailure("failed to query json when extracting response!") raise exceptions.ParseResponseFailure("failed to query json when extracting response!")
return json_content return json_content
@@ -333,9 +333,9 @@ def search_conf_item(start_path, item_type, item_name):
# system root path # system root path
err_msg = "{} not found in recursive upward path!".format(item_name) err_msg = "{} not found in recursive upward path!".format(item_name)
if item_type == "function": if item_type == "function":
raise exception.FunctionNotFound(err_msg) raise exceptions.FunctionNotFound(err_msg)
else: else:
raise exception.VariableNotFound(err_msg) raise exceptions.VariableNotFound(err_msg)
return search_conf_item(dir_path, item_type, item_name) return search_conf_item(dir_path, item_type, item_name)
@@ -422,7 +422,7 @@ def override_variables_binds(variables, new_mapping):
elif isinstance(variables, (OrderedDict, dict)): elif isinstance(variables, (OrderedDict, dict)):
variables_ordered_dict = variables variables_ordered_dict = variables
else: else:
raise exception.ParamsError("variables error!") raise exceptions.ParamsError("variables error!")
return update_ordered_dict( return update_ordered_dict(
variables_ordered_dict, variables_ordered_dict,
@@ -507,7 +507,7 @@ def load_dot_env_file(path):
return return
else: else:
if not os.path.isfile(path): if not os.path.isfile(path):
raise exception.FileNotFound("env file not exist: {}".format(path)) raise exceptions.FileNotFound("env file not exist: {}".format(path))
logger.log_info("Loading environment variables from {}".format(path)) logger.log_info("Loading environment variables from {}".format(path))
with io.open(path, 'r', encoding='utf-8') as fp: with io.open(path, 'r', encoding='utf-8') as fp:

View File

@@ -2,7 +2,7 @@ import os
import time import time
import requests import requests
from httprunner import exception, response, runner, testcase from httprunner import exceptions, response, runner, testcase
from httprunner.context import Context from httprunner.context import Context
from httprunner.utils import FileUtils, gen_md5 from httprunner.utils import FileUtils, gen_md5
from tests.base import ApiServerUnittest from tests.base import ApiServerUnittest
@@ -270,7 +270,7 @@ class VariableBindsUnittest(ApiServerUnittest):
] ]
self.context.bind_variables(variables) self.context.bind_variables(variables)
with self.assertRaises(exception.ValidationFailure): with self.assertRaises(exceptions.ValidationFailure):
self.context.validate(validators, resp_obj) self.context.validate(validators, resp_obj)
validators = [ validators = [
@@ -305,7 +305,7 @@ class VariableBindsUnittest(ApiServerUnittest):
variables = [] variables = []
self.context.bind_variables(variables) self.context.bind_variables(variables)
with self.assertRaises(exception.ParamsError): with self.assertRaises(exceptions.ParamsError):
self.context.validate(validators, resp_obj) self.context.validate(validators, resp_obj)
# expected value missed in variables mapping # expected value missed in variables mapping
@@ -314,5 +314,5 @@ class VariableBindsUnittest(ApiServerUnittest):
] ]
self.context.bind_variables(variables) self.context.bind_variables(variables)
with self.assertRaises(exception.ValidationFailure): with self.assertRaises(exceptions.ValidationFailure):
self.context.validate(validators, resp_obj) self.context.validate(validators, resp_obj)

View File

@@ -2,7 +2,7 @@ import os
import shutil import shutil
from httprunner import HttpRunner from httprunner import HttpRunner
from httprunner.exception import FileNotFound from httprunner.exceptions import FileNotFound
from tests.base import ApiServerUnittest from tests.base import ApiServerUnittest

View File

@@ -1,5 +1,5 @@
import requests import requests
from httprunner import exception, response, utils from httprunner import exceptions, response, utils
from httprunner.compat import bytes from httprunner.compat import bytes
from tests.base import ApiServerUnittest from tests.base import ApiServerUnittest
@@ -138,7 +138,7 @@ class TestResponse(ApiServerUnittest):
] ]
resp_obj = response.ResponseObject(resp) resp_obj = response.ResponseObject(resp)
with self.assertRaises(exception.ParseResponseFailure): with self.assertRaises(exceptions.ParseResponseFailure):
resp_obj.extract_response(extract_binds_list) resp_obj.extract_response(extract_binds_list)
extract_binds_list = [ extract_binds_list = [
@@ -146,7 +146,7 @@ class TestResponse(ApiServerUnittest):
] ]
resp_obj = response.ResponseObject(resp) resp_obj = response.ResponseObject(resp)
with self.assertRaises(exception.ParseResponseFailure): with self.assertRaises(exceptions.ParseResponseFailure):
resp_obj.extract_response(extract_binds_list) resp_obj.extract_response(extract_binds_list)
def test_extract_response_json_string(self): def test_extract_response_json_string(self):
@@ -202,7 +202,7 @@ class TestResponse(ApiServerUnittest):
{"resp_content_key1": "LB123.*RB789"} {"resp_content_key1": "LB123.*RB789"}
] ]
resp_obj = response.ResponseObject(resp) resp_obj = response.ResponseObject(resp)
with self.assertRaises(exception.ParamsError): with self.assertRaises(exceptions.ParamsError):
resp_obj.extract_response(extract_binds_list) resp_obj.extract_response(extract_binds_list)
def test_extract_response_empty(self): def test_extract_response_empty(self):
@@ -225,5 +225,5 @@ class TestResponse(ApiServerUnittest):
{"resp_content_body": "content.data.def"} {"resp_content_body": "content.data.def"}
] ]
resp_obj = response.ResponseObject(resp) resp_obj = response.ResponseObject(resp)
with self.assertRaises(exception.ParseResponseFailure): with self.assertRaises(exceptions.ParseResponseFailure):
resp_obj.extract_response(extract_binds_list) resp_obj.extract_response(extract_binds_list)

View File

@@ -1,7 +1,7 @@
import os import os
import time import time
from httprunner import HttpRunner, exception, runner from httprunner import HttpRunner, exceptions, runner
from httprunner.testcase import TestcaseLoader from httprunner.testcase import TestcaseLoader
from httprunner.utils import FileUtils, deep_update_dict from httprunner.utils import FileUtils, deep_update_dict
from tests.base import ApiServerUnittest from tests.base import ApiServerUnittest
@@ -66,7 +66,7 @@ class TestRunner(ApiServerUnittest):
] ]
} }
with self.assertRaises(exception.ValidationFailure): with self.assertRaises(exceptions.ValidationFailure):
self.test_runner.run_test(test) self.test_runner.run_test(test)
def test_run_testset_with_hooks(self): def test_run_testset_with_hooks(self):

View File

@@ -3,7 +3,7 @@ import time
import unittest import unittest
from httprunner import testcase from httprunner import testcase
from httprunner.exception import ApiNotFound, ParamsError, SuiteNotFound from httprunner.exceptions import ApiNotFound, ParamsError, SuiteNotFound
from httprunner.testcase import TestcaseLoader from httprunner.testcase import TestcaseLoader

View File

@@ -2,7 +2,7 @@ import os
import shutil import shutil
import unittest import unittest
from httprunner import exception, utils from httprunner import exceptions, utils
from httprunner.compat import OrderedDict from httprunner.compat import OrderedDict
from httprunner.utils import FileUtils from httprunner.utils import FileUtils
from tests.base import ApiServerUnittest from tests.base import ApiServerUnittest
@@ -16,7 +16,7 @@ class TestFileUtils(unittest.TestCase):
with open(yaml_tmp_file, 'w') as f: with open(yaml_tmp_file, 'w') as f:
f.write("") f.write("")
with self.assertRaises(exception.FileFormatError): with self.assertRaises(exceptions.FileFormatError):
FileUtils._load_yaml_file(yaml_tmp_file) FileUtils._load_yaml_file(yaml_tmp_file)
os.remove(yaml_tmp_file) os.remove(yaml_tmp_file)
@@ -25,7 +25,7 @@ class TestFileUtils(unittest.TestCase):
with open(yaml_tmp_file, 'w') as f: with open(yaml_tmp_file, 'w') as f:
f.write("abc") f.write("abc")
with self.assertRaises(exception.FileFormatError): with self.assertRaises(exceptions.FileFormatError):
FileUtils._load_yaml_file(yaml_tmp_file) FileUtils._load_yaml_file(yaml_tmp_file)
os.remove(yaml_tmp_file) os.remove(yaml_tmp_file)
@@ -37,7 +37,7 @@ class TestFileUtils(unittest.TestCase):
with open(json_tmp_file, 'w') as f: with open(json_tmp_file, 'w') as f:
f.write("") f.write("")
with self.assertRaises(exception.FileFormatError): with self.assertRaises(exceptions.FileFormatError):
FileUtils._load_json_file(json_tmp_file) FileUtils._load_json_file(json_tmp_file)
os.remove(json_tmp_file) os.remove(json_tmp_file)
@@ -46,7 +46,7 @@ class TestFileUtils(unittest.TestCase):
with open(json_tmp_file, 'w') as f: with open(json_tmp_file, 'w') as f:
f.write("{}") f.write("{}")
with self.assertRaises(exception.FileFormatError): with self.assertRaises(exceptions.FileFormatError):
FileUtils._load_json_file(json_tmp_file) FileUtils._load_json_file(json_tmp_file)
os.remove(json_tmp_file) os.remove(json_tmp_file)
@@ -55,14 +55,14 @@ class TestFileUtils(unittest.TestCase):
with open(json_tmp_file, 'w') as f: with open(json_tmp_file, 'w') as f:
f.write("abc") f.write("abc")
with self.assertRaises(exception.FileFormatError): with self.assertRaises(exceptions.FileFormatError):
FileUtils._load_json_file(json_tmp_file) FileUtils._load_json_file(json_tmp_file)
os.remove(json_tmp_file) os.remove(json_tmp_file)
def test_load_testcases_bad_filepath(self): def test_load_testcases_bad_filepath(self):
testcase_file_path = os.path.join(os.getcwd(), 'tests/data/demo') testcase_file_path = os.path.join(os.getcwd(), 'tests/data/demo')
with self.assertRaises(exception.FileNotFound): with self.assertRaises(exceptions.FileNotFound):
FileUtils.load_file(testcase_file_path) FileUtils.load_file(testcase_file_path)
def test_load_json_testcases(self): def test_load_json_testcases(self):
@@ -163,11 +163,11 @@ class TestUtils(ApiServerUnittest):
self.assertEqual(result, 3) self.assertEqual(result, 3)
query = "ids.str_key" query = "ids.str_key"
with self.assertRaises(exception.ParseResponseFailure): with self.assertRaises(exceptions.ParseResponseFailure):
utils.query_json(json_content, query) utils.query_json(json_content, query)
query = "ids.5" query = "ids.5"
with self.assertRaises(exception.ParseResponseFailure): with self.assertRaises(exceptions.ParseResponseFailure):
utils.query_json(json_content, query) utils.query_json(json_content, query)
query = "person.age" query = "person.age"
@@ -175,7 +175,7 @@ class TestUtils(ApiServerUnittest):
self.assertEqual(result, 29) self.assertEqual(result, 29)
query = "person.not_exist_key" query = "person.not_exist_key"
with self.assertRaises(exception.ParseResponseFailure): with self.assertRaises(exceptions.ParseResponseFailure):
utils.query_json(json_content, query) utils.query_json(json_content, query)
query = "person.cities.0" query = "person.cities.0"
@@ -189,12 +189,12 @@ class TestUtils(ApiServerUnittest):
def test_query_json_content_is_text(self): def test_query_json_content_is_text(self):
json_content = "" json_content = ""
query = "key" query = "key"
with self.assertRaises(exception.ResponseFailure): with self.assertRaises(exceptions.ResponseFailure):
utils.query_json(json_content, query) utils.query_json(json_content, query)
json_content = "<html><body>content</body></html>" json_content = "<html><body>content</body></html>"
query = "key" query = "key"
with self.assertRaises(exception.ParseResponseFailure): with self.assertRaises(exceptions.ParseResponseFailure):
utils.query_json(json_content, query) utils.query_json(json_content, query)
def test_get_uniform_comparator(self): def test_get_uniform_comparator(self):
@@ -302,7 +302,7 @@ class TestUtils(ApiServerUnittest):
self.assertIn("gen_md5", functions_dict) self.assertIn("gen_md5", functions_dict)
self.assertNotIn("urllib", functions_dict) self.assertNotIn("urllib", functions_dict)
with self.assertRaises(exception.FileNotFoundError): with self.assertRaises(exceptions.FileNotFoundError):
utils.get_imported_module_from_file("tests/debugtalk2.py") utils.get_imported_module_from_file("tests/debugtalk2.py")
def test_search_conf_function(self): def test_search_conf_function(self):
@@ -314,10 +314,10 @@ class TestUtils(ApiServerUnittest):
self.assertTrue(utils.is_function(("_", gen_md5))) self.assertTrue(utils.is_function(("_", gen_md5)))
self.assertEqual(gen_md5("abc"), "900150983cd24fb0d6963f7d28e17f72") self.assertEqual(gen_md5("abc"), "900150983cd24fb0d6963f7d28e17f72")
with self.assertRaises(exception.FunctionNotFound): with self.assertRaises(exceptions.FunctionNotFound):
utils.search_conf_item("tests/data/subfolder/test.yml", "function", "func_not_exist") utils.search_conf_item("tests/data/subfolder/test.yml", "function", "func_not_exist")
with self.assertRaises(exception.FunctionNotFound): with self.assertRaises(exceptions.FunctionNotFound):
utils.search_conf_item("/user/local/bin", "function", "gen_md5") utils.search_conf_item("/user/local/bin", "function", "gen_md5")
def test_search_conf_variable(self): def test_search_conf_variable(self):
@@ -329,10 +329,10 @@ class TestUtils(ApiServerUnittest):
self.assertTrue(utils.is_variable(("SECRET_KEY", SECRET_KEY))) self.assertTrue(utils.is_variable(("SECRET_KEY", SECRET_KEY)))
self.assertEqual(SECRET_KEY, "DebugTalk") self.assertEqual(SECRET_KEY, "DebugTalk")
with self.assertRaises(exception.VariableNotFound): with self.assertRaises(exceptions.VariableNotFound):
utils.search_conf_item("tests/data/subfolder/test.yml", "variable", "variable_not_exist") utils.search_conf_item("tests/data/subfolder/test.yml", "variable", "variable_not_exist")
with self.assertRaises(exception.VariableNotFound): with self.assertRaises(exceptions.VariableNotFound):
utils.search_conf_item("/user/local/bin", "variable", "SECRET_KEY") utils.search_conf_item("/user/local/bin", "variable", "SECRET_KEY")
def test_is_variable(self): def test_is_variable(self):
@@ -443,7 +443,7 @@ class TestUtils(ApiServerUnittest):
map_list = "invalid" map_list = "invalid"
override_mapping = {"a": 3, "c": 4} override_mapping = {"a": 3, "c": 4}
with self.assertRaises(exception.ParamsError): with self.assertRaises(exceptions.ParamsError):
utils.override_variables_binds(map_list, override_mapping) utils.override_variables_binds(map_list, override_mapping)
def test_create_scaffold(self): def test_create_scaffold(self):