change: remove support for Python 2.7

This commit is contained in:
debugtalk
2020-03-07 17:05:07 +08:00
parent 3c9eb14409
commit d1fb5e6cdc
10 changed files with 38 additions and 132 deletions

View File

@@ -4,8 +4,6 @@ Built-in validate comparators.
import re import re
from httprunner.compat import basestring, builtin_str, integer_types
def equals(check_value, expect_value): def equals(check_value, expect_value):
assert check_value == expect_value assert check_value == expect_value
@@ -32,46 +30,46 @@ def not_equals(check_value, expect_value):
def string_equals(check_value, expect_value): def string_equals(check_value, expect_value):
assert builtin_str(check_value) == builtin_str(expect_value) assert str(check_value) == str(expect_value)
def length_equals(check_value, expect_value): def length_equals(check_value, expect_value):
assert isinstance(expect_value, integer_types) assert isinstance(expect_value, int)
expect_len = _cast_to_int(expect_value) expect_len = _cast_to_int(expect_value)
assert len(check_value) == expect_len assert len(check_value) == expect_len
def length_greater_than(check_value, expect_value): def length_greater_than(check_value, expect_value):
assert isinstance(expect_value, integer_types) assert isinstance(expect_value, int)
expect_len = _cast_to_int(expect_value) expect_len = _cast_to_int(expect_value)
assert len(check_value) > expect_len assert len(check_value) > expect_len
def length_greater_than_or_equals(check_value, expect_value): def length_greater_than_or_equals(check_value, expect_value):
assert isinstance(expect_value, integer_types) assert isinstance(expect_value, int)
expect_len = _cast_to_int(expect_value) expect_len = _cast_to_int(expect_value)
assert len(check_value) >= expect_len assert len(check_value) >= expect_len
def length_less_than(check_value, expect_value): def length_less_than(check_value, expect_value):
assert isinstance(expect_value, integer_types) assert isinstance(expect_value, int)
expect_len = _cast_to_int(expect_value) expect_len = _cast_to_int(expect_value)
assert len(check_value) < expect_len assert len(check_value) < expect_len
def length_less_than_or_equals(check_value, expect_value): def length_less_than_or_equals(check_value, expect_value):
assert isinstance(expect_value, integer_types) assert isinstance(expect_value, int)
expect_len = _cast_to_int(expect_value) expect_len = _cast_to_int(expect_value)
assert len(check_value) <= expect_len assert len(check_value) <= expect_len
def contains(check_value, expect_value): def contains(check_value, expect_value):
assert isinstance(check_value, (list, tuple, dict, basestring)) assert isinstance(check_value, (list, tuple, dict, str, bytes))
assert expect_value in check_value assert expect_value in check_value
def contained_by(check_value, expect_value): def contained_by(check_value, expect_value):
assert isinstance(expect_value, (list, tuple, dict, basestring)) assert isinstance(expect_value, (list, tuple, dict, str, bytes))
assert check_value in expect_value assert check_value in expect_value
@@ -79,7 +77,7 @@ def type_match(check_value, expect_value):
def get_type(name): def get_type(name):
if isinstance(name, type): if isinstance(name, type):
return name return name
elif isinstance(name, basestring): elif isinstance(name, str, bytes):
try: try:
return __builtins__[name] return __builtins__[name]
except KeyError: except KeyError:
@@ -91,21 +89,21 @@ def type_match(check_value, expect_value):
def regex_match(check_value, expect_value): def regex_match(check_value, expect_value):
assert isinstance(expect_value, basestring) assert isinstance(expect_value, str)
assert isinstance(check_value, basestring) assert isinstance(check_value, str)
assert re.match(expect_value, check_value) assert re.match(expect_value, check_value)
def startswith(check_value, expect_value): def startswith(check_value, expect_value):
assert builtin_str(check_value).startswith(builtin_str(expect_value)) assert str(check_value).startswith(str(expect_value))
def endswith(check_value, expect_value): def endswith(check_value, expect_value):
assert builtin_str(check_value).endswith(builtin_str(expect_value)) assert str(check_value).endswith(str(expect_value))
def _cast_to_int(expect_value): def _cast_to_int(expect_value):
try: try:
return int(expect_value) return int(expect_value)
except Exception: except Exception:
raise AssertionError("%r can't cast to int" % str(expect_value)) raise AssertionError("%r can't cast to int" % str(expect_value))

View File

@@ -7,7 +7,6 @@ import random
import string import string
import time import time
from httprunner.compat import builtin_str, integer_types
from httprunner.exceptions import ParamsError from httprunner.exceptions import ParamsError
@@ -21,8 +20,8 @@ def gen_random_string(str_len):
def get_timestamp(str_len=13): def get_timestamp(str_len=13):
""" get timestamp string, length can only between 0 and 16 """ get timestamp string, length can only between 0 and 16
""" """
if isinstance(str_len, integer_types) and 0 < str_len < 17: if isinstance(str_len, int) and 0 < str_len < 17:
return builtin_str(time.time()).replace(".", "")[:str_len] return str(time.time()).replace(".", "")[:str_len]
raise ParamsError("timestamp length can only between 0 and 16.") raise ParamsError("timestamp length can only between 0 and 16.")

View File

@@ -1,61 +0,0 @@
# encoding: utf-8
"""
httprunner.compat
~~~~~~~~~~~~~~~~~
This module handles import compatibility issues between Python 2 and
Python 3.
"""
try:
import simplejson as json
except ImportError:
import json
import sys
# -------
# Pythons
# -------
# Syntax sugar.
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
# ---------
# Specifics
# ---------
try:
JSONDecodeError = json.JSONDecodeError
except AttributeError:
JSONDecodeError = ValueError
if is_py2:
builtin_str = str
bytes = str
str = unicode
basestring = basestring
numeric_types = (int, long, float)
integer_types = (int, long)
FileNotFoundError = IOError
import StringIO as io
elif is_py3:
builtin_str = str
str = str
bytes = bytes
basestring = (str, bytes)
numeric_types = (int, float)
integer_types = (int,)
FileNotFoundError = FileNotFoundError
import io as io

View File

@@ -1,7 +1,3 @@
# encoding: utf-8
from httprunner.compat import JSONDecodeError, FileNotFoundError
""" failure type exceptions """ failure type exceptions
these exceptions will mark test as failure these exceptions will mark test as failure
""" """

View File

@@ -9,7 +9,6 @@ import re
from loguru import logger from loguru import logger
from httprunner import exceptions, utils, loader from httprunner import exceptions, utils, loader
from httprunner.compat import basestring, numeric_types, str
# use $$ to escape $ notation # use $$ to escape $ notation
dolloar_regex_compile = re.compile(r"\$\$") dolloar_regex_compile = re.compile(r"\$\$")
@@ -46,7 +45,7 @@ def parse_string_value(str_value):
def is_var_or_func_exist(content): def is_var_or_func_exist(content):
""" check if variable or function exist """ check if variable or function exist
""" """
if not isinstance(content, basestring): if not isinstance(content, str):
return False return False
try: try:
@@ -735,7 +734,7 @@ def prepare_lazy_data(content, functions_mapping=None, check_variables_set=None,
""" """
# TODO: refactor type check # TODO: refactor type check
if content is None or isinstance(content, (numeric_types, bool, type)): if content is None or isinstance(content, (int, float, bool, type)):
return content return content
elif isinstance(content, (list, set, tuple)): elif isinstance(content, (list, set, tuple)):
@@ -768,7 +767,7 @@ def prepare_lazy_data(content, functions_mapping=None, check_variables_set=None,
return parsed_content return parsed_content
elif isinstance(content, basestring): elif isinstance(content, str):
# content is in string format here # content is in string format here
if not is_var_or_func_exist(content): if not is_var_or_func_exist(content):
# content is neither variable nor function # content is neither variable nor function
@@ -788,7 +787,7 @@ def parse_lazy_data(content, variables_mapping=None):
Notice: variables_mapping should not contain any variable or function. Notice: variables_mapping should not contain any variable or function.
""" """
# TODO: refactor type check # TODO: refactor type check
if content is None or isinstance(content, (numeric_types, bool, type)): if content is None or isinstance(content, (int, float, bool, type)):
return content return content
elif isinstance(content, LazyString): elif isinstance(content, LazyString):
@@ -1057,7 +1056,7 @@ def __prepare_config(config, project_mapping, session_variables_set=None):
override_variables = utils.deepcopy_dict(project_mapping.get("variables", {})) override_variables = utils.deepcopy_dict(project_mapping.get("variables", {}))
functions = project_mapping.get("functions", {}) functions = project_mapping.get("functions", {})
if isinstance(raw_config_variables, basestring) and function_regex_compile.match( if isinstance(raw_config_variables, str) and function_regex_compile.match(
raw_config_variables): raw_config_variables):
# config variables are generated by calling function # config variables are generated by calling function
# e.g. # e.g.

View File

@@ -1,11 +1,10 @@
import json
from base64 import b64encode from base64 import b64encode
from collections import Iterable from collections import Iterable
from jinja2 import escape from jinja2 import escape
from requests.cookies import RequestsCookieJar from requests.cookies import RequestsCookieJar
from httprunner.compat import basestring, bytes, json, numeric_types, JSONDecodeError
def dumps_json(value): def dumps_json(value):
""" dumps json value to indented string """ dumps json value to indented string
@@ -67,13 +66,13 @@ def __stringify_request(request_data):
# request body is in json format # request body is in json format
value = json.loads(value) value = json.loads(value)
value = dumps_json(value) value = dumps_json(value)
except JSONDecodeError: except json.JSONDecodeError:
pass pass
value = escape(value) value = escape(value)
except UnicodeDecodeError: except UnicodeDecodeError:
pass pass
elif not isinstance(value, (basestring, numeric_types, Iterable)): elif not isinstance(value, (str, bytes, int, float, Iterable)):
# class instance, e.g. MultipartEncoder() # class instance, e.g. MultipartEncoder()
value = repr(value) value = repr(value)
@@ -132,7 +131,7 @@ def __stringify_response(response_data):
except UnicodeDecodeError: except UnicodeDecodeError:
pass pass
elif not isinstance(value, (basestring, numeric_types, Iterable)): elif not isinstance(value, (str, bytes, int, float, Iterable)):
# class instance, e.g. MultipartEncoder() # class instance, e.g. MultipartEncoder()
value = repr(value) value = repr(value)

View File

@@ -5,7 +5,6 @@ import jsonpath
from loguru import logger from loguru import logger
from httprunner import exceptions, utils from httprunner import exceptions, utils
from httprunner.compat import basestring, is_py2
text_extractor_regexp_compile = re.compile(r".*\(.*\).*") text_extractor_regexp_compile = re.compile(r".*\(.*\).*")
@@ -254,7 +253,7 @@ class ResponseObject(object):
def extract_field(self, field): def extract_field(self, field):
""" extract value from requests.Response. """ extract value from requests.Response.
""" """
if not isinstance(field, basestring): if not isinstance(field, str):
err_msg = f"Invalid extractor! => {field}\n" err_msg = f"Invalid extractor! => {field}\n"
logger.error(err_msg) logger.error(err_msg)
raise exceptions.ParamsError(err_msg) raise exceptions.ParamsError(err_msg)
@@ -268,9 +267,6 @@ class ResponseObject(object):
else: else:
value = self._extract_field_with_delimiter(field) value = self._extract_field_with_delimiter(field)
if is_py2 and isinstance(value, unicode):
value = value.encode("utf-8")
msg += f"\t=> {value}" msg += f"\t=> {value}"
logger.debug(msg) logger.debug(msg)

View File

@@ -13,7 +13,6 @@ import sentry_sdk
from loguru import logger from loguru import logger
from httprunner import exceptions, __version__ from httprunner import exceptions, __version__
from httprunner.compat import basestring, bytes, is_py2
from httprunner.exceptions import ParamsError from httprunner.exceptions import ParamsError
absolute_http_url_regexp = re.compile(r"^https?://", re.I) absolute_http_url_regexp = re.compile(r"^https?://", re.I)
@@ -112,7 +111,7 @@ def query_json(json_content, query, delimiter='.'):
response_body = f"response body: {json_content}\n" response_body = f"response body: {json_content}\n"
try: try:
for key in query.split(delimiter): for key in query.split(delimiter):
if isinstance(json_content, (list, basestring)): if isinstance(json_content, (list, str, bytes)):
json_content = json_content[int(key)] json_content = json_content[int(key)]
elif isinstance(json_content, dict): elif isinstance(json_content, dict):
json_content = json_content[key] json_content = json_content[key]
@@ -355,12 +354,6 @@ def print_info(info_mapping):
elif value is None: elif value is None:
value = "None" value = "None"
if is_py2:
if isinstance(key, unicode):
key = key.encode("utf-8")
if isinstance(value, unicode):
value = value.encode("utf-8")
content += content_format.format(key, value) content += content_format.format(key, value)
content += "-" * 48 + "\n" content += "-" * 48 + "\n"
@@ -551,7 +544,7 @@ def prettify_json_file(file_list):
def omit_long_data(body, omit_len=512): def omit_long_data(body, omit_len=512):
""" omit too long str/bytes """ omit too long str/bytes
""" """
if not isinstance(body, basestring): if not isinstance(body, (str, bytes)):
return body return body
body_len = len(body) body_len = len(body)
@@ -583,26 +576,14 @@ def dump_json_file(json_data, json_file_abs_path):
try: try:
with io.open(json_file_abs_path, 'w', encoding='utf-8') as outfile: with io.open(json_file_abs_path, 'w', encoding='utf-8') as outfile:
if is_py2: json.dump(
outfile.write( json_data,
unicode(json.dumps( outfile,
json_data, indent=4,
indent=4, separators=(',', ':'),
separators=(',', ':'), ensure_ascii=False,
encoding="utf8", cls=PythonObjectEncoder
ensure_ascii=False, )
cls=PythonObjectEncoder
))
)
else:
json.dump(
json_data,
outfile,
indent=4,
separators=(',', ':'),
ensure_ascii=False,
cls=PythonObjectEncoder
)
msg = f"dump file: {json_file_abs_path}" msg = f"dump file: {json_file_abs_path}"
logger.info(msg) logger.info(msg)

View File

@@ -1,8 +1,8 @@
import io
import sys import sys
import unittest import unittest
from httprunner.cli import main from httprunner.cli import main
from httprunner.compat import io
class TestCli(unittest.TestCase): class TestCli(unittest.TestCase):

View File

@@ -1,7 +1,6 @@
import requests import requests
from httprunner import exceptions, response from httprunner import exceptions, response
from httprunner.compat import basestring, bytes
from tests.api_server import HTTPBIN_SERVER from tests.api_server import HTTPBIN_SERVER
from tests.base import ApiServerUnittest from tests.base import ApiServerUnittest
@@ -257,7 +256,7 @@ class TestResponse(ApiServerUnittest):
] ]
extract_binds_dict = resp_obj.extract_response(extract_binds_list) extract_binds_dict = resp_obj.extract_response(extract_binds_list)
self.assertIsInstance(extract_binds_dict["resp_content"], basestring) self.assertIsInstance(extract_binds_dict["resp_content"], str)
self.assertIn("httpbin.org", extract_binds_dict["resp_content"]) self.assertIn("httpbin.org", extract_binds_dict["resp_content"])
extract_binds_list = [ extract_binds_list = [